diff --git a/pgsql/doc/extension/autoinc.example b/pgsql/doc/extension/autoinc.example
new file mode 100644
index 0000000000000000000000000000000000000000..08880ce5fad3f7a463e125ff77e53dbcf453fd68
--- /dev/null
+++ b/pgsql/doc/extension/autoinc.example
@@ -0,0 +1,35 @@
+DROP SEQUENCE next_id;
+DROP TABLE ids;
+
+CREATE SEQUENCE next_id START -2 MINVALUE -2;
+
+CREATE TABLE ids (
+ id int4,
+ idesc text
+);
+
+CREATE TRIGGER ids_nextid
+ BEFORE INSERT OR UPDATE ON ids
+ FOR EACH ROW
+ EXECUTE PROCEDURE autoinc (id, next_id);
+
+INSERT INTO ids VALUES (0, 'first (-2 ?)');
+INSERT INTO ids VALUES (null, 'second (-1 ?)');
+INSERT INTO ids(idesc) VALUES ('third (1 ?!)');
+
+SELECT * FROM ids;
+
+UPDATE ids SET id = null, idesc = 'first: -2 --> 2'
+ WHERE idesc = 'first (-2 ?)';
+UPDATE ids SET id = 0, idesc = 'second: -1 --> 3'
+ WHERE id = -1;
+UPDATE ids SET id = 4, idesc = 'third: 1 --> 4'
+ WHERE id = 1;
+
+SELECT * FROM ids;
+
+SELECT 'Wasn''t it 4 ?' as nextval, nextval ('next_id') as value;
+
+insert into ids (idesc) select textcat (idesc, '. Copy.') from ids;
+
+SELECT * FROM ids;
diff --git a/pgsql/doc/extension/insert_username.example b/pgsql/doc/extension/insert_username.example
new file mode 100644
index 0000000000000000000000000000000000000000..2c1eeb0e0dde1b1e3b24e3527d76948e7b8de8a0
--- /dev/null
+++ b/pgsql/doc/extension/insert_username.example
@@ -0,0 +1,20 @@
+DROP TABLE username_test;
+
+CREATE TABLE username_test (
+ name text,
+ username text not null
+);
+
+CREATE TRIGGER insert_usernames
+ BEFORE INSERT OR UPDATE ON username_test
+ FOR EACH ROW
+ EXECUTE PROCEDURE insert_username (username);
+
+INSERT INTO username_test VALUES ('nothing');
+INSERT INTO username_test VALUES ('null', null);
+INSERT INTO username_test VALUES ('empty string', '');
+INSERT INTO username_test VALUES ('space', ' ');
+INSERT INTO username_test VALUES ('tab', ' ');
+INSERT INTO username_test VALUES ('name', 'name');
+
+SELECT * FROM username_test;
diff --git a/pgsql/doc/extension/moddatetime.example b/pgsql/doc/extension/moddatetime.example
new file mode 100644
index 0000000000000000000000000000000000000000..65af388214dfa88b35a80dd8a86ba484ca81cb4e
--- /dev/null
+++ b/pgsql/doc/extension/moddatetime.example
@@ -0,0 +1,27 @@
+DROP TABLE mdt;
+
+CREATE TABLE mdt (
+ id int4,
+ idesc text,
+ moddate timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL
+);
+
+CREATE TRIGGER mdt_moddatetime
+ BEFORE UPDATE ON mdt
+ FOR EACH ROW
+ EXECUTE PROCEDURE moddatetime (moddate);
+
+INSERT INTO mdt VALUES (1, 'first');
+INSERT INTO mdt VALUES (2, 'second');
+INSERT INTO mdt VALUES (3, 'third');
+
+SELECT * FROM mdt;
+
+UPDATE mdt SET id = 4
+ WHERE id = 1;
+UPDATE mdt SET id = 5
+ WHERE id = 2;
+UPDATE mdt SET id = 6
+ WHERE id = 3;
+
+SELECT * FROM mdt;
diff --git a/pgsql/doc/extension/refint.example b/pgsql/doc/extension/refint.example
new file mode 100644
index 0000000000000000000000000000000000000000..299166d504193e9d4ee1ecfab53c4e67f8e203e9
--- /dev/null
+++ b/pgsql/doc/extension/refint.example
@@ -0,0 +1,82 @@
+--Column ID of table A is primary key:
+
+CREATE TABLE A (
+ ID int4 not null
+);
+CREATE UNIQUE INDEX AI ON A (ID);
+
+--Columns REFB of table B and REFC of C are foreign keys referencing ID of A:
+
+CREATE TABLE B (
+ REFB int4
+);
+CREATE INDEX BI ON B (REFB);
+
+CREATE TABLE C (
+ REFC int4
+);
+CREATE INDEX CI ON C (REFC);
+
+--Trigger for table A:
+
+CREATE TRIGGER AT BEFORE DELETE OR UPDATE ON A FOR EACH ROW
+EXECUTE PROCEDURE
+check_foreign_key (2, 'cascade', 'ID', 'B', 'REFB', 'C', 'REFC');
+/*
+2 - means that check must be performed for foreign keys of 2 tables.
+cascade - defines that corresponding keys must be deleted.
+ID - name of primary key column in triggered table (A). You may
+ use as many columns as you need.
+B - name of (first) table with foreign keys.
+REFB - name of foreign key column in this table. You may use as many
+ columns as you need, but number of key columns in referenced
+ table (A) must be the same.
+C - name of second table with foreign keys.
+REFC - name of foreign key column in this table.
+*/
+
+--Trigger for table B:
+
+CREATE TRIGGER BT BEFORE INSERT OR UPDATE ON B FOR EACH ROW
+EXECUTE PROCEDURE
+check_primary_key ('REFB', 'A', 'ID');
+
+/*
+REFB - name of foreign key column in triggered (B) table. You may use as
+ many columns as you need, but number of key columns in referenced
+ table must be the same.
+A - referenced table name.
+ID - name of primary key column in referenced table.
+*/
+
+--Trigger for table C:
+
+CREATE TRIGGER CT BEFORE INSERT OR UPDATE ON C FOR EACH ROW
+EXECUTE PROCEDURE
+check_primary_key ('REFC', 'A', 'ID');
+
+-- Now try
+
+INSERT INTO A VALUES (10);
+INSERT INTO A VALUES (20);
+INSERT INTO A VALUES (30);
+INSERT INTO A VALUES (40);
+INSERT INTO A VALUES (50);
+
+INSERT INTO B VALUES (1); -- invalid reference
+INSERT INTO B VALUES (10);
+INSERT INTO B VALUES (30);
+INSERT INTO B VALUES (30);
+
+INSERT INTO C VALUES (11); -- invalid reference
+INSERT INTO C VALUES (20);
+INSERT INTO C VALUES (20);
+INSERT INTO C VALUES (30);
+
+DELETE FROM A WHERE ID = 10;
+DELETE FROM A WHERE ID = 20;
+DELETE FROM A WHERE ID = 30;
+
+SELECT * FROM A;
+SELECT * FROM B;
+SELECT * FROM C;
diff --git a/pgsql/doc/postgresql/html/acronyms.html b/pgsql/doc/postgresql/html/acronyms.html
new file mode 100644
index 0000000000000000000000000000000000000000..6243a8020457c3e02b04a83d71a870a5ecf36fa7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/acronyms.html
@@ -0,0 +1,224 @@
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/admin.html b/pgsql/doc/postgresql/html/admin.html
new file mode 100644
index 0000000000000000000000000000000000000000..edcd22d7ed0dc77850babe4db2c953b4b78bdc4a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/admin.html
@@ -0,0 +1,26 @@
+
+Part III. Server Administration
+ This part covers topics that are of interest to a
+ PostgreSQL database administrator. This includes
+ installation of the software, set up and configuration of the
+ server, management of users and databases, and maintenance tasks.
+ Anyone who runs a PostgreSQL server, even for
+ personal use, but especially in production, should be familiar
+ with the topics covered in this part.
+
+ The information in this part is arranged approximately in the
+ order in which a new user should read it. But the chapters are
+ self-contained and can be read individually as desired. The
+ information in this part is presented in a narrative fashion in
+ topical units. Readers looking for a complete description of a
+ particular command should see Part VI.
+
+ The first few chapters are written so they can be understood
+ without prerequisite knowledge, so new users who need to set
+ up their own server can begin their exploration with this part.
+ The rest of this part is about tuning and management; that material
+ assumes that the reader is familiar with the general use of
+ the PostgreSQL database system. Readers are
+ encouraged to look at Part I and Part II for additional information.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/adminpack.html b/pgsql/doc/postgresql/html/adminpack.html
new file mode 100644
index 0000000000000000000000000000000000000000..25cdcbe050e9532b93372a4ee51dc6960fc0e310
--- /dev/null
+++ b/pgsql/doc/postgresql/html/adminpack.html
@@ -0,0 +1,89 @@
+
+F.1. adminpack — pgAdmin support toolpack
+ adminpack provides a number of support functions which
+ pgAdmin and other administration and management tools can
+ use to provide additional functionality, such as remote management
+ of server log files.
+ Use of all these functions is only allowed to database superusers by default, but may be
+ allowed to other users by using the GRANT command.
+
+ The functions shown in Table F.1 provide
+ write access to files on the machine hosting the server. (See also the
+ functions in Table 9.101, which
+ provide read-only access.)
+ Only files within the database cluster directory can be accessed, unless the
+ user is a superuser or given privileges of one of the
+ pg_read_server_files or
+ pg_write_server_files roles, as appropriate for the
+ function, but either a relative or absolute path is allowable.
+
+ Lists the log files in the log_directory directory.
+
+ pg_file_write writes the specified data into
+ the file named by filename. If append is
+ false, the file must not already exist. If append is true,
+ the file can already exist, and will be appended to if so.
+ Returns the number of bytes written.
+
+ pg_file_sync fsyncs the specified file or directory
+ named by filename. An error is thrown
+ on failure (e.g., the specified file is not present). Note that
+ data_sync_retry has no effect on this function,
+ and therefore a PANIC-level error will not be raised even on failure to
+ flush database files.
+
+ pg_file_rename renames a file. If archivename
+ is omitted or NULL, it simply renames oldname
+ to newname (which must not already exist).
+ If archivename is provided, it first
+ renames newname to archivename (which must
+ not already exist), and then renames oldname
+ to newname. In event of failure of the second rename step,
+ it will try to rename archivename back
+ to newname before reporting the error.
+ Returns true on success, false if the source file(s) are not present or
+ not writable; other cases throw errors.
+
+ pg_file_unlink removes the specified file.
+ Returns true on success, false if the specified file is not present
+ or the unlink() call fails; other cases throw errors.
+
+ pg_logdir_ls returns the start timestamps and path
+ names of all the log files in the log_directory
+ directory. The log_filename parameter must have its
+ default setting (postgresql-%Y-%m-%d_%H%M%S.log) to use this
+ function.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/amcheck.html b/pgsql/doc/postgresql/html/amcheck.html
new file mode 100644
index 0000000000000000000000000000000000000000..6ff4e148c8682519932143ffc8e78351c1e8d80e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/amcheck.html
@@ -0,0 +1,377 @@
+
+F.2. amcheck — tools to verify table and index consistency
F.2. amcheck — tools to verify table and index consistency
+ The amcheck module provides functions that allow you to
+ verify the logical consistency of the structure of relations.
+
+ The B-Tree checking functions verify various invariants in the
+ structure of the representation of particular relations. The
+ correctness of the access method functions behind index scans and
+ other important operations relies on these invariants always
+ holding. For example, certain functions verify, among other things,
+ that all B-Tree pages have items in “logical” order (e.g.,
+ for B-Tree indexes on text, index tuples should be in
+ collated lexical order). If that particular invariant somehow fails
+ to hold, we can expect binary searches on the affected page to
+ incorrectly guide index scans, resulting in wrong answers to SQL
+ queries. If the structure appears to be valid, no error is raised.
+
+ Verification is performed using the same procedures as those used by
+ index scans themselves, which may be user-defined operator class
+ code. For example, B-Tree index verification relies on comparisons
+ made with one or more B-Tree support function 1 routines. See Section 38.16.3 for details of operator class support
+ functions.
+
+ Unlike the B-Tree checking functions which report corruption by raising
+ errors, the heap checking function verify_heapam checks
+ a table and attempts to return a set of rows, one row per corruption
+ detected. Despite this, if facilities that
+ verify_heapam relies upon are themselves corrupted, the
+ function may be unable to continue and may instead raise an error.
+
+ Permission to execute amcheck functions may be granted
+ to non-superusers, but before granting such permissions careful consideration
+ should be given to data security and privacy concerns. Although the
+ corruption reports generated by these functions do not focus on the contents
+ of the corrupted data so much as on the structure of that data and the nature
+ of the corruptions found, an attacker who gains permission to execute these
+ functions, particularly if the attacker can also induce corruption, might be
+ able to infer something of the data itself from such messages.
+
+ bt_index_check tests that its target, a
+ B-Tree index, respects a variety of invariants. Example usage:
+
+test=# SELECT bt_index_check(index => c.oid, heapallindexed => i.indisunique),
+ c.relname,
+ c.relpages
+FROM pg_index i
+JOIN pg_opclass op ON i.indclass[0] = op.oid
+JOIN pg_am am ON op.opcmethod = am.oid
+JOIN pg_class c ON i.indexrelid = c.oid
+JOIN pg_namespace n ON c.relnamespace = n.oid
+WHERE am.amname = 'btree' AND n.nspname = 'pg_catalog'
+-- Don't check temp tables, which may be from another session:
+AND c.relpersistence != 't'
+-- Function may throw an error when this is omitted:
+AND c.relkind = 'i' AND i.indisready AND i.indisvalid
+ORDER BY c.relpages DESC LIMIT 10;
+ bt_index_check | relname | relpages
+----------------+---------------------------------+----------
+ | pg_depend_reference_index | 43
+ | pg_depend_depender_index | 40
+ | pg_proc_proname_args_nsp_index | 31
+ | pg_description_o_c_o_index | 21
+ | pg_attribute_relid_attnam_index | 14
+ | pg_proc_oid_index | 10
+ | pg_attribute_relid_attnum_index | 9
+ | pg_amproc_fam_proc_index | 5
+ | pg_amop_opr_fam_index | 5
+ | pg_amop_fam_strat_index | 5
+(10 rows)
+
+ This example shows a session that performs verification of the
+ 10 largest catalog indexes in the database “test”.
+ Verification of the presence of heap tuples as index tuples is
+ requested for the subset that are unique indexes. Since no
+ error is raised, all indexes tested appear to be logically
+ consistent. Naturally, this query could easily be changed to
+ call bt_index_check for every index in the
+ database where verification is supported.
+
+ bt_index_check acquires an AccessShareLock
+ on the target index and the heap relation it belongs to. This lock mode
+ is the same lock mode acquired on relations by simple
+ SELECT statements.
+ bt_index_check does not verify invariants
+ that span child/parent relationships, but will verify the
+ presence of all heap tuples as index tuples within the index
+ when heapallindexed is
+ true. When a routine, lightweight test for
+ corruption is required in a live production environment, using
+ bt_index_check often provides the best
+ trade-off between thoroughness of verification and limiting the
+ impact on application performance and availability.
+
+ bt_index_parent_check tests that its
+ target, a B-Tree index, respects a variety of invariants.
+ Optionally, when the heapallindexed
+ argument is true, the function verifies the
+ presence of all heap tuples that should be found within the
+ index. When the optional rootdescend
+ argument is true, verification re-finds
+ tuples on the leaf level by performing a new search from the
+ root page for each tuple. The checks that can be performed by
+ bt_index_parent_check are a superset of the
+ checks that can be performed by bt_index_check.
+ bt_index_parent_check can be thought of as
+ a more thorough variant of bt_index_check:
+ unlike bt_index_check,
+ bt_index_parent_check also checks
+ invariants that span parent/child relationships, including checking
+ that there are no missing downlinks in the index structure.
+ bt_index_parent_check follows the general
+ convention of raising an error if it finds a logical
+ inconsistency or other problem.
+
+ A ShareLock is required on the target index by
+ bt_index_parent_check (a
+ ShareLock is also acquired on the heap relation).
+ These locks prevent concurrent data modification from
+ INSERT, UPDATE, and DELETE
+ commands. The locks also prevent the underlying relation from
+ being concurrently processed by VACUUM, as well as
+ all other utility commands. Note that the function holds locks
+ only while running, not for the entire transaction.
+
+ bt_index_parent_check's additional
+ verification is more likely to detect various pathological
+ cases. These cases may involve an incorrectly implemented
+ B-Tree operator class used by the index that is checked, or,
+ hypothetically, undiscovered bugs in the underlying B-Tree index
+ access method code. Note that
+ bt_index_parent_check cannot be used when
+ hot standby mode is enabled (i.e., on read-only physical
+ replicas), unlike bt_index_check.
+
Tip
+ bt_index_check and
+ bt_index_parent_check both output log
+ messages about the verification process at
+ DEBUG1 and DEBUG2 severity
+ levels. These messages provide detailed information about the
+ verification process that may be of interest to
+ PostgreSQL developers. Advanced users
+ may also find this information helpful, since it provides
+ additional context should verification actually detect an
+ inconsistency. Running:
+
+SET client_min_messages = DEBUG1;
+
+ in an interactive psql session before
+ running a verification query will display messages about the
+ progress of verification with a manageable level of detail.
+
+
+ verify_heapam(relation regclass,
+ on_error_stop boolean,
+ check_toast boolean,
+ skip text,
+ startblock bigint,
+ endblock bigint,
+ blkno OUT bigint,
+ offnum OUT integer,
+ attnum OUT integer,
+ msg OUT text)
+ returns setof record
+
+
+ Checks a table, sequence, or materialized view for structural corruption,
+ where pages in the relation contain data that is invalidly formatted, and
+ for logical corruption, where pages are structurally valid but
+ inconsistent with the rest of the database cluster.
+
+ The following optional arguments are recognized:
+
on_error_stop
+ If true, corruption checking stops at the end of the first block in
+ which any corruptions are found.
+
+ Defaults to false.
+
check_toast
+ If true, toasted values are checked against the target relation's
+ TOAST table.
+
+ This option is known to be slow. Also, if the toast table or its
+ index is corrupt, checking it against toast values could conceivably
+ crash the server, although in many cases this would just produce an
+ error.
+
+ Defaults to false.
+
skip
+ If not none, corruption checking skips blocks that
+ are marked as all-visible or all-frozen, as specified.
+ Valid options are all-visible,
+ all-frozen and none.
+
+ Defaults to none.
+
startblock
+ If specified, corruption checking begins at the specified block,
+ skipping all previous blocks. It is an error to specify a
+ startblock outside the range of blocks in the
+ target table.
+
+ By default, checking begins at the first block.
+
endblock
+ If specified, corruption checking ends at the specified block,
+ skipping all remaining blocks. It is an error to specify an
+ endblock outside the range of blocks in the target
+ table.
+
+ By default, all blocks are checked.
+
+ For each corruption detected, verify_heapam returns
+ a row with the following columns:
+
blkno
+ The number of the block containing the corrupt page.
+
offnum
+ The OffsetNumber of the corrupt tuple.
+
attnum
+ The attribute number of the corrupt column in the tuple, if the
+ corruption is specific to a column and not the tuple as a whole.
+
+ When the heapallindexed argument to B-Tree
+ verification functions is true, an additional
+ phase of verification is performed against the table associated with
+ the target index relation. This consists of a “dummy”
+ CREATE INDEX operation, which checks for the
+ presence of all hypothetical new index tuples against a temporary,
+ in-memory summarizing structure (this is built when needed during
+ the basic first phase of verification). The summarizing structure
+ “fingerprints” every tuple found within the target
+ index. The high level principle behind
+ heapallindexed verification is that a new
+ index that is equivalent to the existing, target index must only
+ have entries that can be found in the existing structure.
+
+ The additional heapallindexed phase adds
+ significant overhead: verification will typically take several times
+ longer. However, there is no change to the relation-level locks
+ acquired when heapallindexed verification is
+ performed.
+
+ The summarizing structure is bound in size by
+ maintenance_work_mem. In order to ensure that
+ there is no more than a 2% probability of failure to detect an
+ inconsistency for each heap tuple that should be represented in the
+ index, approximately 2 bytes of memory are needed per tuple. As
+ less memory is made available per tuple, the probability of missing
+ an inconsistency slowly increases. This approach limits the
+ overhead of verification significantly, while only slightly reducing
+ the probability of detecting a problem, especially for installations
+ where verification is treated as a routine maintenance task. Any
+ single absent or malformed tuple has a new opportunity to be
+ detected with each new verification attempt.
+
+ amcheck can be effective at detecting various types of
+ failure modes that data
+ checksums will fail to catch. These include:
+
+
+ Structural inconsistencies caused by incorrect operator class
+ implementations.
+
+ This includes issues caused by the comparison rules of operating
+ system collations changing. Comparisons of datums of a collatable
+ type like text must be immutable (just as all
+ comparisons used for B-Tree index scans must be immutable), which
+ implies that operating system collation rules must never change.
+ Though rare, updates to operating system collation rules can
+ cause these issues. More commonly, an inconsistency in the
+ collation order between a primary server and a standby server is
+ implicated, possibly because the major operating
+ system version in use is inconsistent. Such inconsistencies will
+ generally only arise on standby servers, and so can generally
+ only be detected on standby servers.
+
+ If a problem like this arises, it may not affect each individual
+ index that is ordered using an affected collation, simply because
+ indexed values might happen to have the same
+ absolute ordering regardless of the behavioral inconsistency. See
+ Section 24.1 and Section 24.2 for
+ further details about how PostgreSQL uses
+ operating system locales and collations.
+
+ Structural inconsistencies between indexes and the heap relations
+ that are indexed (when heapallindexed
+ verification is performed).
+
+ There is no cross-checking of indexes against their heap relation
+ during normal operation. Symptoms of heap corruption can be subtle.
+
+ Corruption caused by hypothetical undiscovered bugs in the
+ underlying PostgreSQL access method
+ code, sort code, or transaction management code.
+
+ Automatic verification of the structural integrity of indexes
+ plays a role in the general testing of new or proposed
+ PostgreSQL features that could plausibly allow a
+ logical inconsistency to be introduced. Verification of table
+ structure and associated visibility and transaction status
+ information plays a similar role. One obvious testing strategy
+ is to call amcheck functions continuously
+ when running the standard regression tests. See Section 33.1 for details on running the tests.
+
+ File system or storage subsystem faults where checksums happen to
+ simply not be enabled.
+
+ Note that amcheck examines a page as represented in some
+ shared memory buffer at the time of verification if there is only a
+ shared buffer hit when accessing the block. Consequently,
+ amcheck does not necessarily examine data read from the
+ file system at the time of verification. Note that when checksums are
+ enabled, amcheck may raise an error due to a checksum
+ failure when a corrupt block is read into a buffer.
+
+ Corruption caused by faulty RAM, or the broader memory subsystem.
+
+ PostgreSQL does not protect against correctable
+ memory errors and it is assumed you will operate using RAM that
+ uses industry standard Error Correcting Codes (ECC) or better
+ protection. However, ECC memory is typically only immune to
+ single-bit errors, and should not be assumed to provide
+ absolute protection against failures that
+ result in memory corruption.
+
+ When heapallindexed verification is
+ performed, there is generally a greatly increased chance of
+ detecting single-bit errors, since strict binary equality is
+ tested, and the indexed attributes within the heap are tested.
+
+
+ Structural corruption can happen due to faulty storage hardware, or
+ relation files being overwritten or modified by unrelated software.
+ This kind of corruption can also be detected with
+ data page
+ checksums.
+
+ Relation pages which are correctly formatted, internally consistent, and
+ correct relative to their own internal checksums may still contain
+ logical corruption. As such, this kind of corruption cannot be detected
+ with checksums. Examples include toasted
+ values in the main table which lack a corresponding entry in the toast
+ table, and tuples in the main table with a Transaction ID that is older
+ than the oldest valid Transaction ID in the database or cluster.
+
+ Multiple causes of logical corruption have been observed in production
+ systems, including bugs in the PostgreSQL
+ server software, faulty and ill-conceived backup and restore tools, and
+ user error.
+
+ Corrupt relations are most concerning in live production environments,
+ precisely the same environments where high risk activities are least
+ welcome. For this reason, verify_heapam has been
+ designed to diagnose corruption without undue risk. It cannot guard
+ against all causes of backend crashes, as even executing the calling
+ query could be unsafe on a badly corrupted system. Access to catalog tables is performed and could
+ be problematic if the catalogs themselves are corrupted.
+
+ In general, amcheck can only prove the presence of
+ corruption; it cannot prove its absence.
+
+ No error concerning corruption raised by amcheck should
+ ever be a false positive. amcheck raises
+ errors in the event of conditions that, by definition, should never
+ happen, and so careful analysis of amcheck
+ errors is often required.
+
+ There is no general method of repairing problems that
+ amcheck detects. An explanation for the root cause of
+ an invariant violation should be sought. pageinspect may play a useful role in diagnosing
+ corruption that amcheck detects. A REINDEX
+ may not be effective in repairing corruption.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-clusterdb.html b/pgsql/doc/postgresql/html/app-clusterdb.html
new file mode 100644
index 0000000000000000000000000000000000000000..125a94ca6e10dd6492ad442329a61e95216ccc55
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-clusterdb.html
@@ -0,0 +1,122 @@
+
+clusterdb
clusterdb [connection-option...] [ --verbose | -v ] --all | -a
Description
+ clusterdb is a utility for reclustering tables
+ in a PostgreSQL database. It finds tables
+ that have previously been clustered, and clusters them again on the same
+ index that was last used. Tables that have never been clustered are not
+ affected.
+
+ clusterdb is a wrapper around the SQL
+ command CLUSTER.
+ There is no effective difference between clustering databases via
+ this utility and via other methods for accessing the server.
+
Options
+ clusterdb accepts the following command-line arguments:
+
+
-a --all
+ Cluster all databases.
+
[-d] dbname [--dbname=]dbname
+ Specifies the name of the database to be clustered,
+ when -a/--all is not used.
+ If this is not specified, the database name is read
+ from the environment variable PGDATABASE. If
+ that is not set, the user name specified for the connection is
+ used. The dbname can be a connection string. If so,
+ connection string parameters will override any conflicting command
+ line options.
+
-e --echo
+ Echo the commands that clusterdb generates
+ and sends to the server.
+
-q --quiet
+ Do not display progress messages.
+
-t table --table=table
+ Cluster table only.
+ Multiple tables can be clustered by writing multiple
+ -t switches.
+
-v --verbose
+ Print detailed information during processing.
+
-V --version
+ Print the clusterdb version and exit.
+
-? --help
+ Show help about clusterdb command line
+ arguments, and exit.
+
+
+ clusterdb also accepts
+ the following command-line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server
+ is listening for connections.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force clusterdb to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ clusterdb will automatically prompt
+ for a password if the server demands password authentication.
+ However, clusterdb will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--maintenance-db=dbname
+ Specifies the name of the database to connect to to discover which
+ databases should be clustered,
+ when -a/--all is used.
+ If not specified, the postgres database will be used,
+ or if that does not exist, template1 will be used.
+ This can be a connection
+ string. If so, connection string parameters will override any
+ conflicting command line options. Also, connection string parameters
+ other than the database name itself will be re-used when connecting
+ to other databases.
+
+
Environment
PGDATABASE PGHOST PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see CLUSTER
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Examples
+ To cluster the database test:
+
+$ clusterdb test
+
+
+ To cluster a single table
+ foo in a database named
+ xyzzy:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-createdb.html b/pgsql/doc/postgresql/html/app-createdb.html
new file mode 100644
index 0000000000000000000000000000000000000000..a0465616abe831293cc0cfbfa5e6d37aa38985f7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-createdb.html
@@ -0,0 +1,155 @@
+
+createdb
+ Normally, the database user who executes this command becomes the owner of
+ the new database.
+ However, a different owner can be specified via the -O
+ option, if the executing user has appropriate privileges.
+
+ createdb is a wrapper around the
+ SQL command CREATE DATABASE.
+ There is no effective difference between creating databases via
+ this utility and via other methods for accessing the server.
+
Options
+ createdb accepts the following command-line arguments:
+
+
dbname
+ Specifies the name of the database to be created. The name must be
+ unique among all PostgreSQL databases in this cluster.
+ The default is to create a database with the same name as the
+ current system user.
+
description
+ Specifies a comment to be associated with the newly created
+ database.
+
-D tablespace --tablespace=tablespace
+ Specifies the default tablespace for the database. (This name
+ is processed as a double-quoted identifier.)
+
-e --echo
+ Echo the commands that createdb generates
+ and sends to the server.
+
-E encoding --encoding=encoding
+ Specifies the character encoding scheme to be used in this
+ database. The character sets supported by the
+ PostgreSQL server are described in
+ Section 24.3.1.
+
-l locale --locale=locale
+ Specifies the locale to be used in this database. This is equivalent
+ to specifying --lc-collate,
+ --lc-ctype, and --icu-locale to the
+ same value. Some locales are only valid for ICU and must be set with
+ --icu-locale.
+
--lc-collate=locale
+ Specifies the LC_COLLATE setting to be used in this database.
+
--lc-ctype=locale
+ Specifies the LC_CTYPE setting to be used in this database.
+
--icu-locale=locale
+ Specifies the ICU locale ID to be used in this database, if the
+ ICU locale provider is selected.
+
--icu-rules=rules
+ Specifies additional collation rules to customize the behavior of the
+ default collation of this database. This is supported for ICU only.
+
--locale-provider={libc|icu}
+ Specifies the locale provider for the database's default collation.
+
-O owner --owner=owner
+ Specifies the database user who will own the new database.
+ (This name is processed as a double-quoted identifier.)
+
+ Specifies the template database from which to build this
+ database. (This name is processed as a double-quoted identifier.)
+
-V --version
+ Print the createdb version and exit.
+
-? --help
+ Show help about createdb command line
+ arguments, and exit.
+
+
+ The options -D, -l, -E,
+ -O, and
+ -T correspond to options of the underlying
+ SQL command CREATE DATABASE; see there for more information
+ about them.
+
+ createdb also accepts the following
+ command-line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the
+ server is running. If the value begins with a slash, it is used
+ as the directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or the local Unix domain socket file
+ extension on which the server is listening for connections.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force createdb to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ createdb will automatically prompt
+ for a password if the server demands password authentication.
+ However, createdb will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--maintenance-db=dbname
+ Specifies the name of the database to connect to when creating the
+ new database. If not specified, the postgres
+ database will be used; if that does not exist (or if it is the name
+ of the new database being created), template1 will
+ be used.
+ This can be a connection
+ string. If so, connection string parameters will override any
+ conflicting command line options.
+
+
Environment
PGDATABASE
+ If set, the name of the database to create, unless overridden on
+ the command line.
+
PGHOST PGPORT PGUSER
+ Default connection parameters. PGUSER also
+ determines the name of the database to create, if it is not
+ specified on the command line or by PGDATABASE.
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see CREATE DATABASE
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Examples
+ To create the database demo using the default
+ database server:
+
+$ createdb demo
+
+
+ To create the database demo using the
+ server on host eden, port 5000, using the
+ template0 template database, here is the
+ command-line command and the underlying SQL command:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-createuser.html b/pgsql/doc/postgresql/html/app-createuser.html
new file mode 100644
index 0000000000000000000000000000000000000000..c0919a92eaea10de3d608805e0fd15990302179f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-createuser.html
@@ -0,0 +1,205 @@
+
+createuser
+ createuser creates a
+ new PostgreSQL user (or more precisely, a role).
+ Only superusers and users with CREATEROLE privilege can create
+ new users, so createuser must be
+ invoked by someone who can connect as a superuser or a user with
+ CREATEROLE privilege.
+
+ If you wish to create a role with the SUPERUSER,
+ REPLICATION, or BYPASSRLS privilege,
+ you must connect as a superuser, not merely with
+ CREATEROLE privilege.
+ Being a superuser implies the ability to bypass all access permission
+ checks within the database, so superuser access should not be granted
+ lightly. CREATEROLE also conveys
+ very extensive privileges.
+
+ createuser is a wrapper around the
+ SQL command CREATE ROLE.
+ There is no effective difference between creating users via
+ this utility and via other methods for accessing the server.
+
Options
+ createuser accepts the following command-line arguments:
+
+
username
+ Specifies the name of the PostgreSQL user
+ to be created.
+ This name must be different from all existing roles in this
+ PostgreSQL installation.
+
-a role --with-admin=role
+ Specifies an existing role that will be automatically added as a member of the new
+ role with admin option, giving it the right to grant membership in the
+ new role to others. Multiple existing roles can be specified by
+ writing multiple -a switches.
+
-c number --connection-limit=number
+ Set a maximum number of connections for the new user.
+ The default is to set no limit.
+
-d --createdb
+ The new user will be allowed to create databases.
+
-D --no-createdb
+ The new user will not be allowed to create databases. This is the
+ default.
+
-e --echo
+ Echo the commands that createuser generates
+ and sends to the server.
+
-E --encrypted
+ This option is obsolete but still accepted for backward
+ compatibility.
+
-g role --member-of=role --role=role (deprecated)
+ Specifies the new role should be automatically added as a member
+ of the specified existing role. Multiple existing roles can be
+ specified by writing multiple -g switches.
+
-i --inherit
+ The new role will automatically inherit privileges of roles
+ it is a member of.
+ This is the default.
+
-I --no-inherit
+ The new role will not automatically inherit privileges of roles
+ it is a member of.
+
--interactive
+ Prompt for the user name if none is specified on the command line, and
+ also prompt for whichever of the options
+ -d/-D,
+ -r/-R,
+ -s/-S is not specified on the command
+ line. (This was the default behavior up to PostgreSQL 9.1.)
+
-l --login
+ The new user will be allowed to log in (that is, the user name
+ can be used as the initial session user identifier).
+ This is the default.
+
-L --no-login
+ The new user will not be allowed to log in.
+ (A role without login privilege is still useful as a means of
+ managing database permissions.)
+
-m role --with-member=role
+ Specifies an existing role that will be automatically
+ added as a member of the new role. Multiple existing roles can
+ be specified by writing multiple -m switches.
+
-P --pwprompt
+ If given, createuser will issue a prompt for
+ the password of the new user. This is not necessary if you do not plan
+ on using password authentication.
+
-r --createrole
+ The new user will be allowed to create, alter, drop, comment on,
+ change the security label for other roles; that is,
+ this user will have CREATEROLE privilege.
+ See role creation for more details about what
+ capabilities are conferred by this privilege.
+
-R --no-createrole
+ The new user will not be allowed to create new roles. This is the
+ default.
+
-s --superuser
+ The new user will be a superuser.
+
-S --no-superuser
+ The new user will not be a superuser. This is the default.
+
-v timestamp --valid-until=timestamp
+ Set a date and time after which the role's password is no longer valid.
+ The default is to set no password expiry date.
+
-V --version
+ Print the createuser version and exit.
+
--bypassrls
+ The new user will bypass every row-level security (RLS) policy.
+
--no-bypassrls
+ The new user will not bypass row-level security (RLS) policies. This is
+ the default.
+
--replication
+ The new user will have the REPLICATION privilege,
+ which is described more fully in the documentation for CREATE ROLE.
+
--no-replication
+ The new user will not have the REPLICATION
+ privilege, which is described more fully in the documentation for CREATE ROLE. This is the default.
+
-? --help
+ Show help about createuser command line
+ arguments, and exit.
+
+
+ createuser also accepts the following
+ command-line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the
+ server
+ is running. If the value begins with a slash, it is used
+ as the directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server
+ is listening for connections.
+
-U username --username=username
+ User name to connect as (not the user name to create).
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force createuser to prompt for a
+ password (for connecting to the server, not for the
+ password of the new user).
+
+ This option is never essential, since
+ createuser will automatically prompt
+ for a password if the server demands password authentication.
+ However, createuser will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
+
Environment
PGHOST PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see CREATE ROLE
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Examples
+ To create a user joe on the default database
+ server:
+
+$ createuser joe
+
+
+ To create a user joe on the default database
+ server with prompting for some additional attributes:
+
+$ createuser --interactive joe
+Shall the new role be a superuser? (y/n) n
+Shall the new role be allowed to create databases? (y/n) n
+Shall the new role be allowed to create more new roles? (y/n) n
+
+
+ To create the same user joe using the
+ server on host eden, port 5000, with attributes explicitly specified,
+ taking a look at the underlying command:
+
+$ createuser -h eden -p 5000 -S -D -R -e joe
+CREATE ROLE joe NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN;
+
+
+ To create the user joe as a superuser,
+ and assign a password immediately:
+
+$ createuser -P -s -e joe
+Enter password for new role: xyzzy
+Enter it again: xyzzy
+CREATE ROLE joe PASSWORD 'md5b5f5ba1a423792b526f799ae4eb3d59e' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;
+
+ In the above example, the new password isn't actually echoed when typed,
+ but we show what was typed for clarity. As you see, the password is
+ encrypted before it is sent to the client.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-dropdb.html b/pgsql/doc/postgresql/html/app-dropdb.html
new file mode 100644
index 0000000000000000000000000000000000000000..3b6293bffec3b868b0cba8a9761fff753309cdde
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-dropdb.html
@@ -0,0 +1,111 @@
+
+dropdb
+ dropdb destroys an existing
+ PostgreSQL database.
+ The user who executes this command must be a database
+ superuser or the owner of the database.
+
+ dropdb is a wrapper around the
+ SQL command DROP DATABASE.
+ There is no effective difference between dropping databases via
+ this utility and via other methods for accessing the server.
+
Options
+ dropdb accepts the following command-line arguments:
+
+
dbname
+ Specifies the name of the database to be removed.
+
-e --echo
+ Echo the commands that dropdb generates
+ and sends to the server.
+
-f --force
+ Attempt to terminate all existing connections to the target database
+ before dropping it. See DROP DATABASE for more
+ information on this option.
+
-i --interactive
+ Issues a verification prompt before doing anything destructive.
+
-V --version
+ Print the dropdb version and exit.
+
--if-exists
+ Do not throw an error if the database does not exist. A notice is issued
+ in this case.
+
-? --help
+ Show help about dropdb command line
+ arguments, and exit.
+
+
+
+ dropdb also accepts the following
+ command-line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the
+ server
+ is running. If the value begins with a slash, it is used
+ as the directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server
+ is listening for connections.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force dropdb to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ dropdb will automatically prompt
+ for a password if the server demands password authentication.
+ However, dropdb will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--maintenance-db=dbname
+ Specifies the name of the database to connect to in order to drop the
+ target database. If not specified, the postgres
+ database will be used; if that does not exist (or is the database
+ being dropped), template1 will be used.
+ This can be a connection
+ string. If so, connection string parameters will override any
+ conflicting command line options.
+
+
Environment
PGHOST PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see DROP DATABASE
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Examples
+ To destroy the database demo on the default
+ database server:
+
+$ dropdb demo
+
+
+ To destroy the database demo using the
+ server on host eden, port 5000, with verification and a peek
+ at the underlying command:
+
+$ dropdb -p 5000 -h eden -i -e demo
+Database "demo" will be permanently deleted.
+Are you sure? (y/n) y
+DROP DATABASE demo;
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-dropuser.html b/pgsql/doc/postgresql/html/app-dropuser.html
new file mode 100644
index 0000000000000000000000000000000000000000..4192a9145a6dd28ad387d809276fec68b456e21f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-dropuser.html
@@ -0,0 +1,104 @@
+
+dropuser
+ dropuser removes an existing
+ PostgreSQL user.
+ Superusers can use this command to remove any role; otherwise, only
+ non-superuser roles can be removed, and only by a user who possesses
+ the CREATEROLE privilege and has been granted
+ ADMIN OPTION on the target role.
+
+ dropuser is a wrapper around the
+ SQL command DROP ROLE.
+ There is no effective difference between dropping users via
+ this utility and via other methods for accessing the server.
+
Options
+ dropuser accepts the following command-line arguments:
+
+
username
+ Specifies the name of the PostgreSQL user to be removed.
+ You will be prompted for a name if none is specified on the command
+ line and the -i/--interactive option
+ is used.
+
-e --echo
+ Echo the commands that dropuser generates
+ and sends to the server.
+
-i --interactive
+ Prompt for confirmation before actually removing the user, and prompt
+ for the user name if none is specified on the command line.
+
-V --version
+ Print the dropuser version and exit.
+
--if-exists
+ Do not throw an error if the user does not exist. A notice is
+ issued in this case.
+
-? --help
+ Show help about dropuser command line
+ arguments, and exit.
+
+
+ dropuser also accepts the following
+ command-line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the
+ server
+ is running. If the value begins with a slash, it is used
+ as the directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server
+ is listening for connections.
+
-U username --username=username
+ User name to connect as (not the user name to drop).
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force dropuser to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ dropuser will automatically prompt
+ for a password if the server demands password authentication.
+ However, dropuser will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
+
Environment
PGHOST PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see DROP ROLE
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Examples
+ To remove user joe from the default database
+ server:
+
+$ dropuser joe
+
+
+ To remove user joe using the server on host
+ eden, port 5000, with verification and a peek at the underlying
+ command:
+
+$ dropuser -p 5000 -h eden -i -e joe
+Role "joe" will be permanently removed.
+Are you sure? (y/n) y
+DROP ROLE joe;
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-ecpg.html b/pgsql/doc/postgresql/html/app-ecpg.html
new file mode 100644
index 0000000000000000000000000000000000000000..8a8dd3fb7d11b44862f0b25b7f830ffc47a0a090
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-ecpg.html
@@ -0,0 +1,108 @@
+
+ecpg
+ ecpg is the embedded SQL preprocessor for C
+ programs. It converts C programs with embedded SQL statements to
+ normal C code by replacing the SQL invocations with special
+ function calls. The output files can then be processed with any C
+ compiler tool chain.
+
+ ecpg will convert each input file given on the
+ command line to the corresponding C output file. If an input file
+ name does not have any extension, .pgc is
+ assumed. The file's extension will be replaced
+ by .c to construct the output file name.
+ But the output file name can be overridden using the
+ -o option.
+
+ If an input file name is just -,
+ ecpg reads the program from standard input
+ (and writes to standard output, unless that is overridden
+ with -o).
+
+ This reference page does not describe the embedded SQL language.
+ See Chapter 36 for more information on that topic.
+
Options
+ ecpg accepts the following command-line
+ arguments:
+
+
-c
+ Automatically generate certain C code from SQL code. Currently, this
+ works for EXEC SQL TYPE.
+
-C mode
+ Set a compatibility mode. mode can
+ be INFORMIX,
+ INFORMIX_SE, or ORACLE.
+
-D symbol[=value]
+ Define a preprocessor symbol, equivalently to the EXEC SQL
+ DEFINE directive. If no value is
+ specified, the symbol is defined with the value 1.
+
-h
+ Process header files. When this option is specified, the output file
+ extension becomes .h not .c,
+ and the default input file extension is .pgh
+ not .pgc. Also, the -c option is
+ forced on.
+
-i
+ Parse system include files as well.
+
-I directory
+ Specify an additional include path, used to find files included
+ via EXEC SQL INCLUDE. Defaults are
+ . (current directory),
+ /usr/local/include, the
+ PostgreSQL include directory which
+ is defined at compile time (default:
+ /usr/local/pgsql/include), and
+ /usr/include, in that order.
+
-o filename
+ Specifies that ecpg should write all
+ its output to the given filename.
+ Write -o - to send all output to standard output.
+
-r option
+ Selects run-time behavior. Option can be
+ one of the following:
+
no_indicator
+ Do not use indicators but instead use special values to represent
+ null values. Historically there have been databases using this approach.
+
prepare
+ Prepare all statements before using them. Libecpg will keep a cache of
+ prepared statements and reuse a statement if it gets executed again. If the
+ cache runs full, libecpg will free the least used statement.
+
questionmarks
+ Allow question mark as placeholder for compatibility reasons.
+ This used to be the default long ago.
+
-t
+ Turn on autocommit of transactions. In this mode, each SQL command is
+ automatically committed unless it is inside an explicit
+ transaction block. In the default mode, commands are committed
+ only when EXEC SQL COMMIT is issued.
+
-v
+ Print additional information including the version and the
+ "include" path.
+
--version
+ Print the ecpg version and exit.
+
-? --help
+ Show help about ecpg command line
+ arguments, and exit.
+
+
Notes
+ When compiling the preprocessed C code files, the compiler needs to
+ be able to find the ECPG header files in the
+ PostgreSQL include directory. Therefore, you might
+ have to use the -I option when invoking the compiler
+ (e.g., -I/usr/local/pgsql/include).
+
+ Programs using C code with embedded SQL have to be linked against
+ the libecpg library, for example using the
+ linker options -L/usr/local/pgsql/lib -lecpg.
+
+ The value of either of these directories that is appropriate for
+ the installation can be found out using pg_config.
+
Examples
+ If you have an embedded SQL C source file named
+ prog1.pgc, you can create an executable
+ program using the following sequence of commands:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-initdb.html b/pgsql/doc/postgresql/html/app-initdb.html
new file mode 100644
index 0000000000000000000000000000000000000000..cb24fa55f011de56a55901bb02bf4eb426b280c0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-initdb.html
@@ -0,0 +1,267 @@
+
+initdb
+ Creating a database cluster consists of creating the
+ directories in
+ which the cluster data will live, generating the shared catalog
+ tables (tables that belong to the whole cluster rather than to any
+ particular database), and creating the postgres,
+ template1, and template0 databases.
+ The postgres database is a default database meant
+ for use by users, utilities and third party applications.
+ template1 and template0 are
+ meant as source databases to be copied by later CREATE
+ DATABASE commands. template0 should never
+ be modified, but you can add objects to template1,
+ which by default will be copied into databases created later. See
+ Section 23.3 for more details.
+
+ Although initdb will attempt to create the
+ specified data directory, it might not have permission if the parent
+ directory of the desired data directory is root-owned. To initialize
+ in such a setup, create an empty data directory as root, then use
+ chown to assign ownership of that directory to the
+ database user account, then su to become the
+ database user to run initdb.
+
+ initdb must be run as the user that will own the
+ server process, because the server needs to have access to the
+ files and directories that initdb creates.
+ Since the server cannot be run as root, you must not run
+ initdb as root either. (It will in fact refuse
+ to do so.)
+
+ For security reasons the new cluster created by initdb
+ will only be accessible by the cluster owner by default. The
+ --allow-group-access option allows any user in the same
+ group as the cluster owner to read files in the cluster. This is useful
+ for performing backups as a non-privileged user.
+
+ initdb initializes the database cluster's default locale
+ and character set encoding. These can also be set separately for each
+ database when it is created. initdb determines those
+ settings for the template databases, which will serve as the default for
+ all other databases.
+
+ By default, initdb uses the locale provider
+ libc (see Section 24.1.4). The
+ libc locale provider takes the locale settings from the
+ environment, and determines the encoding from the locale settings.
+
+ To choose a different locale for the cluster, use the option
+ --locale. There are also individual options
+ --lc-* and --icu-locale (see below) to
+ set values for the individual locale categories. Note that inconsistent
+ settings for different locale categories can give nonsensical results, so
+ this should be used with care.
+
+ Alternatively, initdb can use the ICU library to provide
+ locale services by specifying --locale-provider=icu. The
+ server must be built with ICU support. To choose the specific ICU locale ID
+ to apply, use the option --icu-locale. Note that for
+ implementation reasons and to support legacy code,
+ initdb will still select and initialize libc locale
+ settings when the ICU locale provider is used.
+
+ When initdb runs, it will print out the locale settings
+ it has chosen. If you have complex requirements or specified multiple
+ options, it is advisable to check that the result matches what was
+ intended.
+
+ More details about locale settings can be found in Section 24.1.
+
+ To alter the default encoding, use the --encoding.
+ More details can be found in Section 24.3.
+
+ This option specifies the default authentication method for local
+ users used in pg_hba.conf (host
+ and local lines). See Section 21.1
+ for an overview of valid values.
+
+ initdb will
+ prepopulate pg_hba.conf entries using the
+ specified authentication method for non-replication as well as
+ replication connections.
+
+ Do not use trust unless you trust all local users on your
+ system. trust is the default for ease of installation.
+
+ This option specifies the directory where the database cluster
+ should be stored. This is the only information required by
+ initdb, but you can avoid writing it by
+ setting the PGDATA environment variable, which
+ can be convenient since the database server
+ (postgres) can find the data
+ directory later by the same variable.
+
+ Selects the encoding of the template databases. This will also be the
+ default encoding of any database you create later, unless you override
+ it then. The character sets supported by the
+ PostgreSQL server are described in Section 24.3.1.
+
+ By default, the template database encoding is derived from the
+ locale. If --no-locale is specified
+ (or equivalently, if the locale is C or
+ POSIX), then the default is UTF8
+ for the ICU provider and SQL_ASCII for the
+ libc provider.
+
+ Allows users in the same group as the cluster owner to read all cluster
+ files created by initdb. This option is ignored
+ on Windows as it does not support
+ POSIX-style group permissions.
+
+ Use checksums on data pages to help detect corruption by the
+ I/O system that would otherwise be silent. Enabling checksums
+ may incur a noticeable performance penalty. If set, checksums
+ are calculated for all objects, in all databases. All checksum
+ failures will be reported in the
+
+ pg_stat_database view.
+ See Section 30.2 for details.
+
+ Sets the default locale for the database cluster. If this
+ option is not specified, the locale is inherited from the
+ environment that initdb runs in. Locale
+ support is described in Section 24.1.
+
+ This option sets the locale provider for databases created in the new
+ cluster. It can be overridden in the CREATE
+ DATABASE command when new databases are subsequently
+ created. The default is libc (see Section 24.1.4).
+
+ By default, initdb will wait for all files to be
+ written safely to disk. This option causes initdb
+ to return without waiting, which is faster, but means that a
+ subsequent operating system crash can leave the data directory
+ corrupt. Generally, this option is useful for testing, but should not
+ be used when creating a production installation.
+
+ By default, initdb will write instructions for how
+ to start the cluster at the end of its output. This option causes
+ those instructions to be left out. This is primarily intended for use
+ by tools that wrap initdb in platform-specific
+ behavior, where those instructions are likely to be incorrect.
+
+ Safely write all database files to disk and exit. This does not
+ perform any of the normal initdb operations.
+ Generally, this option is useful for ensuring reliable recovery after
+ changing fsync from off to
+ on.
+
+ Makes initdb prompt for a password
+ to give the bootstrap superuser. If you don't plan on using password
+ authentication, this is not important. Otherwise you won't be
+ able to use password authentication until you have a password
+ set up.
+
+ Set the WAL segment size, in megabytes. This
+ is the size of each individual file in the WAL log. The default size
+ is 16 megabytes. The value must be a power of 2 between 1 and 1024
+ (megabytes). This option can only be set during initialization, and
+ cannot be changed later.
+
+ It may be useful to adjust this size to control the granularity of
+ WAL log shipping or archiving. Also, in databases with a high volume
+ of WAL, the sheer number of WAL files per directory can become a
+ performance and management problem. Increasing the WAL file size
+ will reduce the number of WAL files.
+
+
+ Other, less commonly used, options are also available:
+
+
+ Forcibly set the server parameter name
+ to value during initdb,
+ and also install that setting in the
+ generated postgresql.conf file,
+ so that it will apply during future server runs.
+ This option can be given more than once to set several parameters.
+ It is primarily useful when the environment is such that the server
+ will not start at all using the default parameters.
+
+ Print debugging output from the bootstrap backend and a few other
+ messages of lesser interest for the general public.
+ The bootstrap backend is the program initdb
+ uses to create the catalog tables. This option generates a tremendous
+ amount of extremely boring output.
+
+ Specifies where initdb should find
+ its input files to initialize the database cluster. This is
+ normally not necessary. You will be told if you need to
+ specify their location explicitly.
+
+ By default, when initdb
+ determines that an error prevented it from completely creating the database
+ cluster, it removes any files it might have created before discovering
+ that it cannot finish the job. This option inhibits tidying-up and is
+ thus useful for debugging.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pg-ctl.html b/pgsql/doc/postgresql/html/app-pg-ctl.html
new file mode 100644
index 0000000000000000000000000000000000000000..67276799ca884e00350d6561ebd683fe0a15ca89
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pg-ctl.html
@@ -0,0 +1,288 @@
+
+pg_ctl
+ pg_ctl is a utility for initializing a
+ PostgreSQL database cluster, starting,
+ stopping, or restarting the PostgreSQL
+ database server (postgres), or displaying the
+ status of a running server. Although the server can be started
+ manually, pg_ctl encapsulates tasks such
+ as redirecting log output and properly detaching from the terminal
+ and process group. It also provides convenient options for
+ controlled shutdown.
+
+ The init or initdb mode creates a new
+ PostgreSQL database cluster, that is,
+ a collection of databases that will be managed by a single
+ server instance. This mode invokes the initdb
+ command. See initdb for details.
+
+ start mode launches a new server. The
+ server is started in the background, and its standard input is attached
+ to /dev/null (or nul on Windows).
+ On Unix-like systems, by default, the server's standard output and
+ standard error are sent to pg_ctl's
+ standard output (not standard error). The standard output of
+ pg_ctl should then be redirected to a
+ file or piped to another process such as a log rotating program
+ like rotatelogs; otherwise postgres
+ will write its output to the controlling terminal (from the
+ background) and will not leave the shell's process group. On
+ Windows, by default the server's standard output and standard error
+ are sent to the terminal. These default behaviors can be changed
+ by using -l to append the server's output to a log file.
+ Use of either -l or output redirection is recommended.
+
+ stop mode shuts down the server that is running in
+ the specified data directory. Three different
+ shutdown methods can be selected with the -m
+ option. “Smart” mode disallows new connections, then waits
+ for all existing clients to disconnect.
+ If the server is in hot standby, recovery and streaming replication
+ will be terminated once all clients have disconnected.
+ “Fast” mode (the default) does not wait for clients to disconnect.
+ All active transactions are
+ rolled back and clients are forcibly disconnected, then the
+ server is shut down. “Immediate” mode will abort
+ all server processes immediately, without a clean shutdown. This choice
+ will lead to a crash-recovery cycle during the next server start.
+
+ restart mode effectively executes a stop followed
+ by a start. This allows changing the postgres
+ command-line options, or changing configuration-file options that
+ cannot be changed without restarting the server.
+ If relative paths were used on the command line during server
+ start, restart might fail unless
+ pg_ctl is executed in the same current
+ directory as it was during server start.
+
+ reload mode simply sends the
+ postgres server process a SIGHUP
+ signal, causing it to reread its configuration files
+ (postgresql.conf,
+ pg_hba.conf, etc.). This allows changing
+ configuration-file options that do not require a full server restart
+ to take effect.
+
+ status mode checks whether a server is running in
+ the specified data directory. If it is, the server's PID
+ and the command line options that were used to invoke it are displayed.
+ If the server is not running, pg_ctl returns
+ an exit status of 3. If an accessible data directory is not
+ specified, pg_ctl returns an exit status of 4.
+
+ promote mode commands the standby server that is
+ running in the specified data directory to end standby mode
+ and begin read-write operations.
+
+ logrotate mode rotates the server log file.
+ For details on how to use this mode with external log rotation tools, see
+ Section 25.3.
+
+ kill mode sends a signal to a specified process.
+ This is primarily valuable on Microsoft Windows
+ which does not have a built-in kill command. Use
+ --help to see a list of supported signal names.
+
+ register mode registers the PostgreSQL
+ server as a system service on Microsoft Windows.
+ The -S option allows selection of service start type,
+ either “auto” (start service automatically on system startup)
+ or “demand” (start service on demand).
+
+ unregister mode unregisters a system service
+ on Microsoft Windows. This undoes the effects of the
+ register command.
+
Options
-c --core-files
+ Attempt to allow server crashes to produce core files, on platforms
+ where this is possible, by lifting any soft resource limit placed on
+ core files.
+ This is useful in debugging or diagnosing problems by allowing a
+ stack trace to be obtained from a failed server process.
+
-D datadir --pgdata=datadir
+ Specifies the file system location of the database configuration files. If
+ this option is omitted, the environment variable
+ PGDATA is used.
+
-l filename --log=filename
+ Append the server log output to
+ filename. If the file does not
+ exist, it is created. The umask is set to 077,
+ so access to the log file is disallowed to other users by default.
+
-m mode --mode=mode
+ Specifies the shutdown mode. mode
+ can be smart, fast, or
+ immediate, or the first letter of one of
+ these three. If this option is omitted, fast is
+ the default.
+
-o options --options=options
+ Specifies options to be passed directly to the
+ postgres command.
+ -o can be specified multiple times, with all the given
+ options being passed through.
+
+ The options should usually be surrounded by single or
+ double quotes to ensure that they are passed through as a group.
+
-o initdb-options --options=initdb-options
+ Specifies options to be passed directly to the
+ initdb command.
+ -o can be specified multiple times, with all the given
+ options being passed through.
+
+ The initdb-options should usually be surrounded by single or
+ double quotes to ensure that they are passed through as a group.
+
-p path
+ Specifies the location of the postgres
+ executable. By default the postgres executable is taken from the same
+ directory as pg_ctl, or failing that, the hard-wired
+ installation directory. It is not necessary to use this
+ option unless you are doing something unusual and get errors
+ that the postgres executable was not found.
+
+ In init mode, this option analogously
+ specifies the location of the initdb
+ executable.
+
-s --silent
+ Print only errors, no informational messages.
+
-t seconds --timeout=seconds
+ Specifies the maximum number of seconds to wait when waiting for an
+ operation to complete (see option -w). Defaults to
+ the value of the PGCTLTIMEOUT environment variable or, if
+ not set, to 60 seconds.
+
-V --version
+ Print the pg_ctl version and exit.
+
-w --wait
+ Wait for the operation to complete. This is supported for the
+ modes start, stop,
+ restart, promote,
+ and register, and is the default for those modes.
+
+ When waiting, pg_ctl repeatedly checks the
+ server's PID file, sleeping for a short amount
+ of time between checks. Startup is considered complete when
+ the PID file indicates that the server is ready to
+ accept connections. Shutdown is considered complete when the server
+ removes the PID file.
+ pg_ctl returns an exit code based on the
+ success of the startup or shutdown.
+
+ If the operation does not complete within the timeout (see
+ option -t), then pg_ctl exits with
+ a nonzero exit status. But note that the operation might continue in
+ the background and eventually succeed.
+
-W --no-wait
+ Do not wait for the operation to complete. This is the opposite of
+ the option -w.
+
+ If waiting is disabled, the requested action is triggered, but there
+ is no feedback about its success. In that case, the server log file
+ or an external monitoring system would have to be used to check the
+ progress and success of the operation.
+
+ In prior releases of PostgreSQL, this was the default except for
+ the stop mode.
+
-? --help
+ Show help about pg_ctl command line
+ arguments, and exit.
+
+ If an option is specified that is valid, but not relevant to the selected
+ operating mode, pg_ctl ignores it.
+
Options for Windows
-e source
+ Name of the event source for pg_ctl to use
+ for logging to the event log when running as a Windows service. The
+ default is PostgreSQL. Note that this only controls
+ messages sent from pg_ctl itself; once
+ started, the server will use the event source specified
+ by its event_source parameter. Should the server
+ fail very early in startup, before that parameter has been set,
+ it might also log using the default event
+ source name PostgreSQL.
+
-N servicename
+ Name of the system service to register. This name will be used
+ as both the service name and the display name.
+ The default is PostgreSQL.
+
-P password
+ Password for the user to run the service as.
+
-S start-type
+ Start type of the system service. start-type can
+ be auto, or demand, or
+ the first letter of one of these two. If this option is omitted,
+ auto is the default.
+
-U username
+ User name for the user to run the service as. For domain users, use the
+ format DOMAIN\username.
+
Environment
PGCTLTIMEOUT
+ Default limit on the number of seconds to wait when waiting for startup
+ or shutdown to complete. If not set, the default is 60 seconds.
+
PGDATA
+ Default data directory location.
+
+ Most pg_ctl modes require knowing the data directory
+ location; therefore, the -D option is required
+ unless PGDATA is set.
+
+ pg_ctl, like most other PostgreSQL
+ utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
+ For additional variables that affect the server,
+ see postgres.
+
Files
postmaster.pid
+ pg_ctl examines this file in the data
+ directory to determine whether the server is currently running.
+
postmaster.opts
If this file exists in the data directory,
+ pg_ctl (in restart mode)
+ will pass the contents of the file as options to
+ postgres, unless overridden
+ by the -o option. The contents of this file
+ are also displayed in status mode.
+
Examples
Starting the Server
+ To start the server, waiting until the server is
+ accepting connections:
+
+$pg_ctl start
+
+
+ To start the server using port 5433, and
+ running without fsync, use:
+
+$pg_ctl -o "-F -p 5433" start
+
Stopping the Server
+ To stop the server, use:
+
+$pg_ctl stop
+
+ The -m option allows control over
+ how the server shuts down:
+
+$pg_ctl stop -m smart
+
Restarting the Server
+ Restarting the server is almost equivalent to stopping the
+ server and starting it again, except that by default,
+ pg_ctl saves and reuses the command line options that
+ were passed to the previously-running instance. To restart
+ the server using the same options as before, use:
+
+$pg_ctl restart
+
+
+ But if -o is specified, that replaces any previous options.
+ To restart using port 5433, disabling fsync upon restart:
+
+$pg_ctl -o "-F -p 5433" restart
+
Showing the Server Status
+ Here is sample status output from
+ pg_ctl:
+
+$pg_ctl status
+
+pg_ctl: server is running (PID: 13718)
+/usr/local/pgsql/bin/postgres "-D" "/usr/local/pgsql/data" "-p" "5433" "-B" "128"
+
+ The second line is the command that would be invoked in restart mode.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pg-dumpall.html b/pgsql/doc/postgresql/html/app-pg-dumpall.html
new file mode 100644
index 0000000000000000000000000000000000000000..21903fdd4e90c28d61473ab9e072c66f9737679a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pg-dumpall.html
@@ -0,0 +1,364 @@
+
+pg_dumpall
pg_dumpall — extract a PostgreSQL database cluster into a script file
Synopsis
pg_dumpall [connection-option...] [option...]
Description
+ pg_dumpall is a utility for writing out
+ (“dumping”) all PostgreSQL databases
+ of a cluster into one script file. The script file contains
+ SQL commands that can be used as input to psql to restore the databases. It does this by
+ calling pg_dump for each database in the cluster.
+ pg_dumpall also dumps global objects
+ that are common to all databases, namely database roles, tablespaces,
+ and privilege grants for configuration parameters.
+ (pg_dump does not save these objects.)
+
+ Since pg_dumpall reads tables from all
+ databases you will most likely have to connect as a database
+ superuser in order to produce a complete dump. Also you will need
+ superuser privileges to execute the saved script in order to be
+ allowed to add roles and create databases.
+
+ The SQL script will be written to the standard output. Use the
+ -f/--file option or shell operators to
+ redirect it into a file.
+
+ pg_dumpall needs to connect several
+ times to the PostgreSQL server (once per
+ database). If you use password authentication it will ask for
+ a password each time. It is convenient to have a
+ ~/.pgpass file in such cases. See Section 34.16 for more information.
+
Options
+ The following command-line options control the content and
+ format of the output.
+
+
-a --data-only
+ Dump only the data, not the schema (data definitions).
+
-c --clean
+ Emit SQL commands to DROP all the dumped
+ databases, roles, and tablespaces before recreating them.
+ This option is useful when the restore is to overwrite an existing
+ cluster. If any of the objects do not exist in the destination
+ cluster, ignorable error messages will be reported during
+ restore, unless --if-exists is also specified.
+
-E encoding --encoding=encoding
+ Create the dump in the specified character set encoding. By default,
+ the dump is created in the database encoding. (Another way to get the
+ same result is to set the PGCLIENTENCODING environment
+ variable to the desired dump encoding.)
+
-f filename --file=filename
+ Send output to the specified file. If this is omitted, the
+ standard output is used.
+
-g --globals-only
+ Dump only global objects (roles and tablespaces), no databases.
+
-O --no-owner
+ Do not output commands to set
+ ownership of objects to match the original database.
+ By default, pg_dumpall issues
+ ALTER OWNER or
+ SET SESSION AUTHORIZATION
+ statements to set ownership of created schema elements.
+ These statements
+ will fail when the script is run unless it is started by a superuser
+ (or the same user that owns all of the objects in the script).
+ To make a script that can be restored by any user, but will give
+ that user ownership of all the objects, specify -O.
+
-r --roles-only
+ Dump only roles, no databases or tablespaces.
+
-s --schema-only
+ Dump only the object definitions (schema), not data.
+
-S username --superuser=username
+ Specify the superuser user name to use when disabling triggers.
+ This is relevant only if --disable-triggers is used.
+ (Usually, it's better to leave this out, and instead start the
+ resulting script as superuser.)
+
-t --tablespaces-only
+ Dump only tablespaces, no databases or roles.
+
-v --verbose
+ Specifies verbose mode. This will cause
+ pg_dumpall to output start/stop
+ times to the dump file, and progress messages to standard error.
+ Repeating the option causes additional debug-level messages
+ to appear on standard error.
+ The option is also passed down to pg_dump.
+
-V --version
+ Print the pg_dumpall version and exit.
+
-x --no-privileges --no-acl
+ Prevent dumping of access privileges (grant/revoke commands).
+
--binary-upgrade
+ This option is for use by in-place upgrade utilities. Its use
+ for other purposes is not recommended or supported. The
+ behavior of the option may change in future releases without
+ notice.
+
--column-inserts --attribute-inserts
+ Dump data as INSERT commands with explicit
+ column names (INSERT INTO
+ table
+ (column, ...) VALUES
+ ...). This will make restoration very slow; it is mainly
+ useful for making dumps that can be loaded into
+ non-PostgreSQL databases.
+
--disable-dollar-quoting
+ This option disables the use of dollar quoting for function bodies,
+ and forces them to be quoted using SQL standard string syntax.
+
--disable-triggers
+ This option is relevant only when creating a data-only dump.
+ It instructs pg_dumpall to include commands
+ to temporarily disable triggers on the target tables while
+ the data is restored. Use this if you have referential
+ integrity checks or other triggers on the tables that you
+ do not want to invoke during data restore.
+
+ Presently, the commands emitted for --disable-triggers
+ must be done as superuser. So, you should also specify
+ a superuser name with -S, or preferably be careful to
+ start the resulting script as a superuser.
+
--exclude-database=pattern
+ Do not dump databases whose name matches
+ pattern.
+ Multiple patterns can be excluded by writing multiple
+ --exclude-database switches. The
+ pattern parameter is
+ interpreted as a pattern according to the same rules used by
+ psql's \d
+ commands (see Patterns),
+ so multiple databases can also be excluded by writing wildcard
+ characters in the pattern. When using wildcards, be careful to
+ quote the pattern if needed to prevent shell wildcard expansion.
+
--extra-float-digits=ndigits
+ Use the specified value of extra_float_digits when dumping
+ floating-point data, instead of the maximum available precision.
+ Routine dumps made for backup purposes should not use this option.
+
--if-exists
+ Use DROP ... IF EXISTS commands to drop objects
+ in --clean mode. This suppresses “does not
+ exist” errors that might otherwise be reported. This
+ option is not valid unless --clean is also
+ specified.
+
--inserts
+ Dump data as INSERT commands (rather
+ than COPY). This will make restoration very slow;
+ it is mainly useful for making dumps that can be loaded into
+ non-PostgreSQL databases. Note that
+ the restore might fail altogether if you have rearranged column order.
+ The --column-inserts option is safer, though even
+ slower.
+
--load-via-partition-root
+ When dumping data for a table partition, make
+ the COPY or INSERT statements
+ target the root of the partitioning hierarchy that contains it, rather
+ than the partition itself. This causes the appropriate partition to
+ be re-determined for each row when the data is loaded. This may be
+ useful when restoring data on a server where rows do not always fall
+ into the same partitions as they did on the original server. That
+ could happen, for example, if the partitioning column is of type text
+ and the two systems have different definitions of the collation used
+ to sort the partitioning column.
+
--lock-wait-timeout=timeout
+ Do not wait forever to acquire shared table locks at the beginning of
+ the dump. Instead, fail if unable to lock a table within the specified
+ timeout. The timeout may be
+ specified in any of the formats accepted by SET
+ statement_timeout.
+
--no-comments
+ Do not dump comments.
+
--no-publications
+ Do not dump publications.
+
--no-role-passwords
+ Do not dump passwords for roles. When restored, roles will have a
+ null password, and password authentication will always fail until the
+ password is set. Since password values aren't needed when this option
+ is specified, the role information is read from the catalog
+ view pg_roles instead
+ of pg_authid. Therefore, this option also
+ helps if access to pg_authid is restricted by
+ some security policy.
+
--no-security-labels
+ Do not dump security labels.
+
--no-subscriptions
+ Do not dump subscriptions.
+
--no-sync
+ By default, pg_dumpall will wait for all files
+ to be written safely to disk. This option causes
+ pg_dumpall to return without waiting, which is
+ faster, but means that a subsequent operating system crash can leave
+ the dump corrupt. Generally, this option is useful for testing
+ but should not be used when dumping data from production installation.
+
--no-table-access-method
+ Do not output commands to select table access methods.
+ With this option, all objects will be created with whichever
+ table access method is the default during restore.
+
--no-tablespaces
+ Do not output commands to create tablespaces nor select tablespaces
+ for objects.
+ With this option, all objects will be created in whichever
+ tablespace is the default during restore.
+
--no-toast-compression
+ Do not output commands to set TOAST compression
+ methods.
+ With this option, all columns will be restored with the default
+ compression setting.
+
--no-unlogged-table-data
+ Do not dump the contents of unlogged tables. This option has no
+ effect on whether or not the table definitions (schema) are dumped;
+ it only suppresses dumping the table data.
+
--on-conflict-do-nothing
+ Add ON CONFLICT DO NOTHING to
+ INSERT commands.
+ This option is not valid unless --inserts or
+ --column-inserts is also specified.
+
--quote-all-identifiers
+ Force quoting of all identifiers. This option is recommended when
+ dumping a database from a server whose PostgreSQL
+ major version is different from pg_dumpall's, or when
+ the output is intended to be loaded into a server of a different
+ major version. By default, pg_dumpall quotes only
+ identifiers that are reserved words in its own major version.
+ This sometimes results in compatibility issues when dealing with
+ servers of other versions that may have slightly different sets
+ of reserved words. Using --quote-all-identifiers prevents
+ such issues, at the price of a harder-to-read dump script.
+
--rows-per-insert=nrows
+ Dump data as INSERT commands (rather than
+ COPY). Controls the maximum number of rows per
+ INSERT command. The value specified must be a
+ number greater than zero. Any error during restoring will cause only
+ rows that are part of the problematic INSERT to be
+ lost, rather than the entire table contents.
+
--use-set-session-authorization
+ Output SQL-standard SET SESSION AUTHORIZATION commands
+ instead of ALTER OWNER commands to determine object
+ ownership. This makes the dump more standards compatible, but
+ depending on the history of the objects in the dump, might not restore
+ properly.
+
-? --help
+ Show help about pg_dumpall command line
+ arguments, and exit.
+
+
+ The following command-line options control the database connection parameters.
+
+
-d connstr --dbname=connstr
+ Specifies parameters used to connect to the server, as a connection string; these
+ will override any conflicting command line options.
+
+ The option is called --dbname for consistency with other
+ client applications, but because pg_dumpall
+ needs to connect to many databases, the database name in the
+ connection string will be ignored. Use the -l
+ option to specify the name of the database used for the initial
+ connection, which will dump global objects and discover what other
+ databases should be dumped.
+
-h host --host=host
+ Specifies the host name of the machine on which the database
+ server is running. If the value begins with a slash, it is
+ used as the directory for the Unix domain socket. The default
+ is taken from the PGHOST environment variable,
+ if set, else a Unix domain socket connection is attempted.
+
-l dbname --database=dbname
+ Specifies the name of the database to connect to for dumping global
+ objects and discovering what other databases should be dumped. If
+ not specified, the postgres database will be used,
+ and if that does not exist, template1 will be used.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server is listening for connections.
+ Defaults to the PGPORT environment variable, if
+ set, or a compiled-in default.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force pg_dumpall to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ pg_dumpall will automatically prompt
+ for a password if the server demands password authentication.
+ However, pg_dumpall will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
+ Note that the password prompt will occur again for each database
+ to be dumped. Usually, it's better to set up a
+ ~/.pgpass file than to rely on manual password entry.
+
--role=rolename
+ Specifies a role name to be used to create the dump.
+ This option causes pg_dumpall to issue a
+ SET ROLErolename
+ command after connecting to the database. It is useful when the
+ authenticated user (specified by -U) lacks privileges
+ needed by pg_dumpall, but can switch to a role with
+ the required rights. Some installations have a policy against
+ logging in directly as a superuser, and use of this option allows
+ dumps to be made without violating the policy.
+
+
Environment
PGHOST PGOPTIONS PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Notes
+ Since pg_dumpall calls
+ pg_dump internally, some diagnostic
+ messages will refer to pg_dump.
+
+ The --clean option can be useful even when your
+ intention is to restore the dump script into a fresh cluster. Use of
+ --clean authorizes the script to drop and re-create the
+ built-in postgres and template1
+ databases, ensuring that those databases will retain the same properties
+ (for instance, locale and encoding) that they had in the source cluster.
+ Without the option, those databases will retain their existing
+ database-level properties, as well as any pre-existing contents.
+
+ Once restored, it is wise to run ANALYZE on each
+ database so the optimizer has useful statistics. You
+ can also run vacuumdb -a -z to analyze all
+ databases.
+
+ The dump script should not be expected to run completely without errors.
+ In particular, because the script will issue CREATE ROLE
+ for every role existing in the source cluster, it is certain to get a
+ “role already exists” error for the bootstrap superuser,
+ unless the destination cluster was initialized with a different bootstrap
+ superuser name. This error is harmless and should be ignored. Use of
+ the --clean option is likely to produce additional
+ harmless error messages about non-existent objects, although you can
+ minimize those by adding --if-exists.
+
+ pg_dumpall requires all needed
+ tablespace directories to exist before the restore; otherwise,
+ database creation will fail for databases in non-default
+ locations.
+
Examples
+ To dump all databases:
+
+
+$pg_dumpall > db.out
+
+
+ To restore database(s) from this file, you can use:
+
+$psql -f db.out postgres
+
+ It is not important to which database you connect here since the
+ script file created by pg_dumpall will
+ contain the appropriate commands to create and connect to the saved
+ databases. An exception is that if you specified --clean,
+ you must connect to the postgres database initially;
+ the script will attempt to drop other databases immediately, and that
+ will fail for the database you are connected to.
+
See Also
+ Check pg_dump for details on possible
+ error conditions.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pg-isready.html b/pgsql/doc/postgresql/html/app-pg-isready.html
new file mode 100644
index 0000000000000000000000000000000000000000..e813d6a23e24d66b27d5bfed47293a3d40d307d4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pg-isready.html
@@ -0,0 +1,79 @@
+
+pg_isready
pg_isready — check the connection status of a PostgreSQL server
Synopsis
pg_isready [connection-option...] [option...]
Description
+ pg_isready is a utility for checking the connection
+ status of a PostgreSQL database server. The exit
+ status specifies the result of the connection check.
+
Options
-d dbname --dbname=dbname
+ Specifies the name of the database to connect to. The
+ dbname can be a connection string. If so,
+ connection string parameters will override any conflicting command
+ line options.
+
-h hostname --host=hostname
+ Specifies the host name of the machine on which the
+ server is running. If the value begins
+ with a slash, it is used as the directory for the Unix-domain
+ socket.
+
-p port --port=port
+ Specifies the TCP port or the local Unix-domain
+ socket file extension on which the server is listening for
+ connections. Defaults to the value of the PGPORT
+ environment variable or, if not set, to the port specified at
+ compile time, usually 5432.
+
-q --quiet
+ Do not display status message. This is useful when scripting.
+
-t seconds --timeout=seconds
+ The maximum number of seconds to wait when attempting connection before
+ returning that the server is not responding. Setting to 0 disables. The
+ default is 3 seconds.
+
-U username --username=username
+ Connect to the database as the user username instead of the default.
+
-V --version
+ Print the pg_isready version and exit.
+
-? --help
+ Show help about pg_isready command line
+ arguments, and exit.
+
Exit Status
+ pg_isready returns 0 to the shell if the server
+ is accepting connections normally, 1 if the server is rejecting
+ connections (for example during startup), 2 if there was no response to the
+ connection attempt, and 3 if no attempt was made (for example due to invalid
+ parameters).
+
Environment
+ pg_isready, like most other PostgreSQL
+ utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
+ The environment variable PG_COLOR specifies whether to use
+ color in diagnostic messages. Possible values are
+ always, auto and
+ never.
+
Notes
+ It is not necessary to supply correct user name, password, or database
+ name values to obtain the server status; however, if incorrect values
+ are provided, the server will log a failed connection attempt.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgamcheck.html b/pgsql/doc/postgresql/html/app-pgamcheck.html
new file mode 100644
index 0000000000000000000000000000000000000000..83d0edc67a443c7cc30dc9602dda980a7fc2a8d6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgamcheck.html
@@ -0,0 +1,295 @@
+
+pg_amcheck
pg_amcheck — checks for corruption in one or more
+ PostgreSQL databases
Synopsis
pg_amcheck [option...] [dbname]
Description
+ pg_amcheck supports running
+ amcheck's corruption checking functions against one or
+ more databases, with options to select which schemas, tables and indexes to
+ check, which kinds of checking to perform, and whether to perform the checks
+ in parallel, and if so, the number of parallel connections to establish and
+ use.
+
+ Only ordinary and toast table relations, materialized views, sequences, and
+ btree indexes are currently supported. Other relation types are silently
+ skipped.
+
+ If dbname is specified, it should be the name of a
+ single database to check, and no other database selection options should
+ be present. Otherwise, if any database selection options are present,
+ all matching databases will be checked. If no such options are present,
+ the default database will be checked. Database selection options include
+ --all, --database and
+ --exclude-database. They also include
+ --relation, --exclude-relation,
+ --table, --exclude-table,
+ --index, and --exclude-index,
+ but only when such options are used with a three-part pattern
+ (e.g. mydb*.myschema*.myrel*). Finally, they include
+ --schema and --exclude-schema
+ when such options are used with a two-part pattern
+ (e.g. mydb*.myschema*).
+
+ The following command-line options control what is checked:
+
+
-a --all
+ Check all databases, except for any excluded via
+ --exclude-database.
+
-d pattern --database=pattern
+ Check databases matching the specified
+ pattern,
+ except for any excluded by --exclude-database.
+ This option can be specified more than once.
+
-D pattern --exclude-database=pattern
+ Exclude databases matching the given
+ pattern.
+ This option can be specified more than once.
+
-i pattern --index=pattern
+ Check indexes matching the specified
+ pattern,
+ unless they are otherwise excluded.
+ This option can be specified more than once.
+
+ This is similar to the --relation option, except that
+ it applies only to indexes, not to other relation types.
+
-I pattern --exclude-index=pattern
+ Exclude indexes matching the specified
+ pattern.
+ This option can be specified more than once.
+
+ This is similar to the --exclude-relation option,
+ except that it applies only to indexes, not other relation types.
+
-r pattern --relation=pattern
+ Check relations matching the specified
+ pattern,
+ unless they are otherwise excluded.
+ This option can be specified more than once.
+
+ Patterns may be unqualified, e.g. myrel*, or they
+ may be schema-qualified, e.g. myschema*.myrel* or
+ database-qualified and schema-qualified, e.g.
+ mydb*.myschema*.myrel*. A database-qualified
+ pattern will add matching databases to the list of databases to be
+ checked.
+
-R pattern --exclude-relation=pattern
+ Exclude relations matching the specified
+ pattern.
+ This option can be specified more than once.
+
+ As with --relation, the
+ pattern may be unqualified, schema-qualified,
+ or database- and schema-qualified.
+
-s pattern --schema=pattern
+ Check tables and indexes in schemas matching the specified
+ pattern, unless they are otherwise excluded.
+ This option can be specified more than once.
+
+ To select only tables in schemas matching a particular pattern,
+ consider using something like
+ --table=SCHEMAPAT.* --no-dependent-indexes.
+ To select only indexes, consider using something like
+ --index=SCHEMAPAT.*.
+
+ A schema pattern may be database-qualified. For example, you may
+ write --schema=mydb*.myschema* to select
+ schemas matching myschema* in databases matching
+ mydb*.
+
-S pattern --exclude-schema=pattern
+ Exclude tables and indexes in schemas matching the specified
+ pattern.
+ This option can be specified more than once.
+
+ As with --schema, the pattern may be
+ database-qualified.
+
-t pattern --table=pattern
+ Check tables matching the specified
+ pattern,
+ unless they are otherwise excluded.
+ This option can be specified more than once.
+
+ This is similar to the --relation option, except that
+ it applies only to tables, materialized views, and sequences, not to
+ indexes.
+
-T pattern --exclude-table=pattern
+ Exclude tables matching the specified
+ pattern.
+ This option can be specified more than once.
+
+ This is similar to the --exclude-relation option,
+ except that it applies only to tables, materialized views, and
+ sequences, not to indexes.
+
--no-dependent-indexes
+ By default, if a table is checked, any btree indexes of that table
+ will also be checked, even if they are not explicitly selected by
+ an option such as --index or
+ --relation. This option suppresses that behavior.
+
--no-dependent-toast
+ By default, if a table is checked, its toast table, if any, will also
+ be checked, even if it is not explicitly selected by an option
+ such as --table or --relation.
+ This option suppresses that behavior.
+
--no-strict-names
+ By default, if an argument to --database,
+ --table, --index,
+ or --relation matches no objects, it is a fatal
+ error. This option downgrades that error to a warning.
+
+
+ The following command-line options control checking of tables:
+
+
--exclude-toast-pointers
+ By default, whenever a toast pointer is encountered in a table,
+ a lookup is performed to ensure that it references apparently-valid
+ entries in the toast table. These checks can be quite slow, and this
+ option can be used to skip them.
+
--on-error-stop
+ After reporting all corruptions on the first page of a table where
+ corruption is found, stop processing that table relation and move on
+ to the next table or index.
+
+ Note that index checking always stops after the first corrupt page.
+ This option only has meaning relative to table relations.
+
--skip=option
+ If all-frozen is given, table corruption checks
+ will skip over pages in all tables that are marked as all frozen.
+
+ If all-visible is given, table corruption checks
+ will skip over pages in all tables that are marked as all visible.
+
+ By default, no pages are skipped. This can be specified as
+ none, but since this is the default, it need not be
+ mentioned.
+
--startblock=block
+ Start checking at the specified block number. An error will occur if
+ the table relation being checked has fewer than this number of blocks.
+ This option does not apply to indexes, and is probably only useful
+ when checking a single table relation. See --endblock
+ for further caveats.
+
--endblock=block
+ End checking at the specified block number. An error will occur if the
+ table relation being checked has fewer than this number of blocks.
+ This option does not apply to indexes, and is probably only useful when
+ checking a single table relation. If both a regular table and a toast
+ table are checked, this option will apply to both, but higher-numbered
+ toast blocks may still be accessed while validating toast pointers,
+ unless that is suppressed using
+ --exclude-toast-pointers.
+
+
+ The following command-line options control checking of B-tree indexes:
+
+
--heapallindexed
+ For each index checked, verify the presence of all heap tuples as index
+ tuples in the index using amcheck's
+ heapallindexed option.
+
--parent-check
+ For each btree index checked, use amcheck's
+ bt_index_parent_check function, which performs
+ additional checks of parent/child relationships during index checking.
+
+ The default is to use amcheck's
+ bt_index_check function, but note that use of the
+ --rootdescend option implicitly selects
+ bt_index_parent_check.
+
--rootdescend
+ For each index checked, re-find tuples on the leaf level by performing a
+ new search from the root page for each tuple using
+ amcheck's rootdescend option.
+
+ Use of this option implicitly also selects the
+ --parent-check option.
+
+ This form of verification was originally written to help in the
+ development of btree index features. It may be of limited use or even
+ of no use in helping detect the kinds of corruption that occur in
+ practice. It may also cause corruption checking to take considerably
+ longer and consume considerably more resources on the server.
+
+
Warning
+ The extra checks performed against B-tree indexes when the
+ --parent-check option or the
+ --rootdescend option is specified require
+ relatively strong relation-level locks. These checks are the only
+ checks that will block concurrent data modification from
+ INSERT, UPDATE, and
+ DELETE commands.
+
+ The following command-line options control the connection to the server:
+
+
-h hostname --host=hostname
+ Specifies the host name of the machine on which the server is running.
+ If the value begins with a slash, it is used as the directory for the
+ Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file extension on
+ which the server is listening for connections.
+
-U --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires password
+ authentication and a password is not available by other means such as
+ a .pgpass file, the connection attempt will fail.
+ This option can be useful in batch jobs and scripts where no user is
+ present to enter a password.
+
-W --password
+ Force pg_amcheck to prompt for a password
+ before connecting to a database.
+
+ This option is never essential, since
+ pg_amcheck will automatically prompt for a
+ password if the server demands password authentication. However,
+ pg_amcheck will waste a connection attempt
+ finding out that the server wants a password. In some cases it is
+ worth typing -W to avoid the extra connection attempt.
+
--maintenance-db=dbname
+ Specifies a database or
+ connection string to be
+ used to discover the list of databases to be checked. If neither
+ --all nor any option including a database pattern is
+ used, no such connection is required and this option does nothing.
+ Otherwise, any connection string parameters other than
+ the database name which are included in the value for this option
+ will also be used when connecting to the databases
+ being checked. If this option is omitted, the default is
+ postgres or, if that fails,
+ template1.
+
+
+ Other options are also available:
+
+
-e --echo
+ Echo to stdout all SQL sent to the server.
+
-j num --jobs=num
+ Use num concurrent connections to the server,
+ or one per object to be checked, whichever is less.
+
+ The default is to use a single connection.
+
-P --progress
+ Show progress information. Progress information includes the number
+ of relations for which checking has been completed, and the total
+ size of those relations. It also includes the total number of relations
+ that will eventually be checked, and the estimated size of those
+ relations.
+
-v --verbose
+ Print more messages. In particular, this will print a message for
+ each relation being checked, and will increase the level of detail
+ shown for server errors.
+
-V --version
+ Print the pg_amcheck version and exit.
+
--install-missing --install-missing=schema
+ Install any missing extensions that are required to check the
+ database(s). If not yet installed, each extension's objects will be
+ installed into the given
+ schema, or if not specified
+ into schema pg_catalog.
+
+ At present, the only required extension is amcheck.
+
-? --help
+ Show help about pg_amcheck command line
+ arguments, and exit.
+
+
Notes
+ pg_amcheck is designed to work with
+ PostgreSQL 14.0 and later.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgbasebackup.html b/pgsql/doc/postgresql/html/app-pgbasebackup.html
new file mode 100644
index 0000000000000000000000000000000000000000..7e5750e87e25ff5236e8883769c3c34b5ffc466f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgbasebackup.html
@@ -0,0 +1,555 @@
+
+pg_basebackup
pg_basebackup — take a base backup of a PostgreSQL cluster
Synopsis
pg_basebackup [option...]
Description
+ pg_basebackup is used to take a base backup of
+ a running PostgreSQL database cluster. The backup
+ is taken without affecting other clients of the database, and can be used
+ both for point-in-time recovery (see Section 26.3)
+ and as the starting point for a log-shipping or streaming-replication standby
+ server (see Section 27.2).
+
+ pg_basebackup makes an exact copy of the database
+ cluster's files, while making sure the server is put into and
+ out of backup mode automatically. Backups are always taken of the entire
+ database cluster; it is not possible to back up individual databases or
+ database objects. For selective backups, another tool such as
+ pg_dump must be used.
+
+ The backup is made over a regular PostgreSQL
+ connection that uses the replication protocol. The connection must be made
+ with a user ID that has REPLICATION permissions
+ (see Section 22.2) or is a superuser,
+ and pg_hba.conf
+ must permit the replication connection. The server must also be configured
+ with max_wal_senders set high enough to provide at
+ least one walsender for the backup plus one for WAL streaming (if used).
+
+ There can be multiple pg_basebackups running at the same time, but it is usually
+ better from a performance point of view to take only one backup, and copy
+ the result.
+
+ pg_basebackup can make a base backup from
+ not only a primary server but also a standby. To take a backup from a standby,
+ set up the standby so that it can accept replication connections (that is, set
+ max_wal_senders and hot_standby,
+ and configure its pg_hba.conf appropriately).
+ You will also need to enable full_page_writes on the primary.
+
+ Note that there are some limitations in taking a backup from a standby:
+
+
+ The backup history file is not created in the database cluster backed up.
+
+ pg_basebackup cannot force the standby
+ to switch to a new WAL file at the end of backup.
+ When you are using -X none, if write activity on
+ the primary is low, pg_basebackup may
+ need to wait a long time for the last WAL file required for the backup
+ to be switched and archived. In this case, it may be useful to run
+ pg_switch_wal on the primary in order to
+ trigger an immediate WAL file switch.
+
+ If the standby is promoted to be primary during backup, the backup fails.
+
+ All WAL records required for the backup must contain sufficient full-page writes,
+ which requires you to enable full_page_writes on the primary.
+
+
+ Whenever pg_basebackup is taking a base
+ backup, the server's pg_stat_progress_basebackup
+ view will report the progress of the backup.
+ See Section 28.4.6 for details.
+
Options
+ The following command-line options control the location and format of the
+ output:
+
+
-D directory --pgdata=directory
+ Sets the target directory to write the output to.
+ pg_basebackup will create this directory
+ (and any missing parent directories) if it does not exist. If it
+ already exists, it must be empty.
+
+ When the backup is in tar format, the target directory may be
+ specified as - (dash), causing the tar file to be
+ written to stdout.
+
+ This option is required.
+
-F format --format=format
+ Selects the format for the output. format
+ can be one of the following:
+
+
p plain
+ Write the output as plain files, with the same layout as the
+ source server's data directory and tablespaces. When the cluster has
+ no additional tablespaces, the whole database will be placed in
+ the target directory. If the cluster contains additional
+ tablespaces, the main data directory will be placed in the
+ target directory, but all other tablespaces will be placed
+ in the same absolute path as they have on the source server.
+ (See --tablespace-mapping to change that.)
+
+ This is the default format.
+
t tar
+ Write the output as tar files in the target directory. The main
+ data directory's contents will be written to a file named
+ base.tar, and each other tablespace will be
+ written to a separate tar file named after that tablespace's OID.
+
+ If the target directory is specified as -
+ (dash), the tar contents will be written to
+ standard output, suitable for piping to (for example)
+ gzip. This is only allowed if
+ the cluster has no additional tablespaces and WAL
+ streaming is not used.
+
-R --write-recovery-conf
+ Creates a
+ standby.signal
+
+ file and appends
+ connection settings to the postgresql.auto.conf
+ file in the target directory (or within the base archive file when
+ using tar format). This eases setting up a standby server using the
+ results of the backup.
+
+ The postgresql.auto.conf file will record the connection
+ settings and, if specified, the replication slot
+ that pg_basebackup is using, so that
+ streaming replication will use the same settings later on.
+
-t target --target=target
+ Instructs the server where to place the base backup. The default target
+ is client, which specifies that the backup should
+ be sent to the machine where pg_basebackup
+ is running. If the target is instead set to
+ server:/some/path, the backup will be stored on
+ the machine where the server is running in the
+ /some/path directory. Storing a backup on the
+ server requires superuser privileges or having privileges of the
+ pg_write_server_files role. If the target is set to
+ blackhole, the contents are discarded and not
+ stored anywhere. This should only be used for testing purposes, as you
+ will not end up with an actual backup.
+
+ Since WAL streaming is implemented by
+ pg_basebackup rather than by the server,
+ this option cannot be used together with -Xstream.
+ Since that is the default, when this option is specified, you must also
+ specify either -Xfetch or -Xnone.
+
+ Relocates the tablespace in directory olddir
+ to newdir during the backup. To be
+ effective, olddir must exactly match the
+ path specification of the tablespace as it is defined on the source
+ server. (But it is not an error if there is no tablespace
+ in olddir on the source server.)
+ Meanwhile newdir is a directory in the
+ receiving host's filesystem. As with the main target directory,
+ newdir need not exist already, but if
+ it does exist it must be empty.
+ Both olddir
+ and newdir must be absolute paths. If
+ either path needs to contain an equal sign (=),
+ precede that with a backslash. This option can be specified multiple
+ times for multiple tablespaces.
+
+ If a tablespace is relocated in this way, the symbolic links inside
+ the main data directory are updated to point to the new location. So
+ the new data directory is ready to be used for a new server instance
+ with all tablespaces in the updated locations.
+
+ Currently, this option only works with plain output format; it is
+ ignored if tar format is selected.
+
--waldir=waldir
+ Sets the directory to write WAL (write-ahead log) files to.
+ By default WAL files will be placed in
+ the pg_wal subdirectory of the target
+ directory, but this option can be used to place them elsewhere.
+ waldir must be an absolute path.
+ As with the main target directory,
+ waldir need not exist already, but if
+ it does exist it must be empty.
+ This option can only be specified when
+ the backup is in plain format.
+
-X method --wal-method=method
+ Includes the required WAL (write-ahead log) files in the
+ backup. This will include all write-ahead logs generated during
+ the backup. Unless the method none is specified,
+ it is possible to start a postmaster in the target
+ directory without the need to consult the WAL archive, thus
+ making the output a completely standalone backup.
+
+ The following methods for collecting the
+ write-ahead logs are supported:
+
+
n none
+ Don't include write-ahead logs in the backup.
+
f fetch
+ The write-ahead log files are collected at the end of the backup.
+ Therefore, it is necessary for the source server's
+ wal_keep_size parameter to be set high
+ enough that the required log data is not removed before the end
+ of the backup. If the required log data has been recycled
+ before it's time to transfer it, the backup will fail and be
+ unusable.
+
+ When tar format is used, the write-ahead log files will be
+ included in the base.tar file.
+
s stream
+ Stream write-ahead log data while the backup is being taken.
+ This method will open a second connection to the server and
+ start streaming the write-ahead log in parallel while running
+ the backup. Therefore, it will require two replication
+ connections not just one. As long as the client can keep up
+ with the write-ahead log data, using this method requires no
+ extra write-ahead logs to be saved on the source server.
+
+ When tar format is used, the write-ahead log files will be
+ written to a separate file named pg_wal.tar
+ (if the server is a version earlier than 10, the file will be named
+ pg_xlog.tar).
+
+ This value is the default.
+
-z --gzip
+ Enables gzip compression of tar file output, with the default
+ compression level. Compression is only available when using
+ the tar format, and the suffix .gz will
+ automatically be added to all tar filenames.
+
+ Requests compression of the backup. If client or
+ server is included, it specifies where the
+ compression is to be performed. Compressing on the server will reduce
+ transfer bandwidth but will increase server CPU consumption. The
+ default is client except when
+ --target is used. In that case, the backup is not
+ being sent to the client, so only server compression is sensible.
+ When -Xstream, which is the default, is used,
+ server-side compression will not be applied to the WAL. To compress
+ the WAL, use client-side compression, or
+ specify -Xfetch.
+
+ The compression method can be set to gzip,
+ lz4, zstd,
+ none for no compression or an integer (no
+ compression if 0, gzip if greater than 0).
+ A compression detail string can optionally be specified.
+ If the detail string is an integer, it specifies the compression
+ level. Otherwise, it should be a comma-separated list of items,
+ each of the form keyword or
+ keyword=value.
+ Currently, the supported keywords are level,
+ long, and workers.
+ The detail string cannot be used when the compression method
+ is specified as a plain integer.
+
+ If no compression level is specified, the default compression level
+ will be used. If only a level is specified without mentioning an
+ algorithm, gzip compression will be used if the
+ level is greater than 0, and no compression will be used if the level
+ is 0.
+
+ When the tar format is used with gzip,
+ lz4, or zstd, the suffix
+ .gz, .lz4, or
+ .zst, respectively, will be automatically added to
+ all tar filenames. When the plain format is used, client-side
+ compression may not be specified, but it is still possible to request
+ server-side compression. If this is done, the server will compress the
+ backup for transmission, and the client will decompress and extract it.
+
+ When this option is used in combination with
+ -Xstream, pg_wal.tar will
+ be compressed using gzip if client-side gzip
+ compression is selected, but will not be compressed if any other
+ compression algorithm is selected, or if server-side compression
+ is selected.
+
+
+ The following command-line options control the generation of the
+ backup and the invocation of the program:
+
+
-c {fast|spread} --checkpoint={fast|spread}
+ Sets checkpoint mode to fast (immediate) or spread (the default)
+ (see Section 26.3.3).
+
-C --create-slot
+ Specifies that the replication slot named by the
+ --slot option should be created before starting
+ the backup. An error is raised if the slot already exists.
+
-l label --label=label
+ Sets the label for the backup. If none is specified, a default value of
+ “pg_basebackup base backup” will be used.
+
-n --no-clean
+ By default, when pg_basebackup aborts with an
+ error, it removes any directories it might have created before
+ discovering that it cannot finish the job (for example, the target
+ directory and write-ahead log directory). This option inhibits
+ tidying-up and is thus useful for debugging.
+
+ Note that tablespace directories are not cleaned up either way.
+
-N --no-sync
+ By default, pg_basebackup will wait for all files
+ to be written safely to disk. This option causes
+ pg_basebackup to return without waiting, which is
+ faster, but means that a subsequent operating system crash can leave
+ the base backup corrupt. Generally, this option is useful for testing
+ but should not be used when creating a production installation.
+
-P --progress
+ Enables progress reporting. Turning this on will deliver an approximate
+ progress report during the backup. Since the database may change during
+ the backup, this is only an approximation and may not end at exactly
+ 100%. In particular, when WAL log is included in the
+ backup, the total amount of data cannot be estimated in advance, and
+ in this case the estimated target size will increase once it passes the
+ total estimate without WAL.
+
-r rate --max-rate=rate
+ Sets the maximum transfer rate at which data is collected from the
+ source server. This can be useful to limit the impact
+ of pg_basebackup on the server. Values
+ are in kilobytes per second. Use a suffix of M
+ to indicate megabytes per second. A suffix of k
+ is also accepted, and has no effect. Valid values are between 32
+ kilobytes per second and 1024 megabytes per second.
+
+ This option always affects transfer of the data directory. Transfer of
+ WAL files is only affected if the collection method
+ is fetch.
+
-S slotname --slot=slotname
+ This option can only be used together with -X
+ stream. It causes WAL streaming to use the specified
+ replication slot. If the base backup is intended to be used as a
+ streaming-replication standby using a replication slot, the standby
+ should then use the same replication slot name as
+ primary_slot_name. This ensures that the
+ primary server does not remove any necessary WAL data in the time
+ between the end of the base backup and the start of streaming
+ replication on the new standby.
+
+ The specified replication slot has to exist unless the
+ option -C is also used.
+
+ If this option is not specified and the server supports temporary
+ replication slots (version 10 and later), then a temporary replication
+ slot is automatically used for WAL streaming.
+
-v --verbose
+ Enables verbose mode. Will output some extra steps during startup and
+ shutdown, as well as show the exact file name that is currently being
+ processed if progress reporting is also enabled.
+
--manifest-checksums=algorithm
+ Specifies the checksum algorithm that should be applied to each file
+ included in the backup manifest. Currently, the available
+ algorithms are NONE, CRC32C,
+ SHA224, SHA256,
+ SHA384, and SHA512.
+ The default is CRC32C.
+
+ If NONE is selected, the backup manifest will
+ not contain any checksums. Otherwise, it will contain a checksum
+ of each file in the backup using the specified algorithm. In addition,
+ the manifest will always contain a SHA256
+ checksum of its own contents. The SHA algorithms
+ are significantly more CPU-intensive than CRC32C,
+ so selecting one of them may increase the time required to complete
+ the backup.
+
+ Using a SHA hash function provides a cryptographically secure digest
+ of each file for users who wish to verify that the backup has not been
+ tampered with, while the CRC32C algorithm provides a checksum that is
+ much faster to calculate; it is good at catching errors due to accidental
+ changes but is not resistant to malicious modifications. Note that, to
+ be useful against an adversary who has access to the backup, the backup
+ manifest would need to be stored securely elsewhere or otherwise
+ verified not to have been modified since the backup was taken.
+
+ pg_verifybackup can be used to check the
+ integrity of a backup against the backup manifest.
+
--manifest-force-encode
+ Forces all filenames in the backup manifest to be hex-encoded.
+ If this option is not specified, only non-UTF8 filenames are
+ hex-encoded. This option is mostly intended to test that tools which
+ read a backup manifest file properly handle this case.
+
--no-estimate-size
+ Prevents the server from estimating the total
+ amount of backup data that will be streamed, resulting in the
+ backup_total column in the
+ pg_stat_progress_basebackup view
+ always being NULL.
+
+ Without this option, the backup will start by enumerating
+ the size of the entire database, and then go back and send
+ the actual contents. This may make the backup take slightly
+ longer, and in particular it will take longer before the first
+ data is sent. This option is useful to avoid such estimation
+ time if it's too long.
+
+ This option is not allowed when using --progress.
+
--no-manifest
+ Disables generation of a backup manifest. If this option is not
+ specified, the server will generate and send a backup manifest
+ which can be verified using pg_verifybackup.
+ The manifest is a list of every file present in the backup with the
+ exception of any WAL files that may be included. It also stores the
+ size, last modification time, and an optional checksum for each file.
+
--no-slot
+ Prevents the creation of a temporary replication slot
+ for the backup.
+
+ By default, if log streaming is selected but no slot name is given
+ with the -S option, then a temporary replication
+ slot is created (if supported by the source server).
+
+ The main purpose of this option is to allow taking a base backup when
+ the server has no free replication slots. Using a replication slot
+ is almost always preferred, because it prevents needed WAL from being
+ removed by the server during the backup.
+
--no-verify-checksums
+ Disables verification of checksums, if they are enabled on the server
+ the base backup is taken from.
+
+ By default, checksums are verified and checksum failures will result
+ in a non-zero exit status. However, the base backup will not be
+ removed in such a case, as if the --no-clean option
+ had been used. Checksum verification failures will also be reported
+ in the
+ pg_stat_database view.
+
+
+ The following command-line options control the connection to the source
+ server:
+
+
-d connstr --dbname=connstr
+ Specifies parameters used to connect to the server, as a connection string; these
+ will override any conflicting command line options.
+
+ The option is called --dbname for consistency with other
+ client applications, but because pg_basebackup
+ doesn't connect to any particular database in the cluster, any database
+ name in the connection string will be ignored.
+
-h host --host=host
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for a Unix domain socket. The default is taken
+ from the PGHOST environment variable, if set,
+ else a Unix domain socket connection is attempted.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server is listening for connections.
+ Defaults to the PGPORT environment variable, if
+ set, or a compiled-in default.
+
-s interval --status-interval=interval
+ Specifies the number of seconds between status packets sent back to
+ the source server. Smaller values allow more accurate monitoring of
+ backup progress from the server.
+ A value of zero disables periodic status updates completely,
+ although an update will still be sent when requested by the server, to
+ avoid timeout-based disconnects. The default value is 10 seconds.
+
-U username --username=username
+ Specifies the user name to connect as.
+
-w --no-password
+ Prevents issuing a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Forces pg_basebackup to prompt for a
+ password before connecting to the source server.
+
+ This option is never essential, since
+ pg_basebackup will automatically prompt
+ for a password if the server demands password authentication.
+ However, pg_basebackup will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
+
+ Other options are also available:
+
+
-V --version
+ Prints the pg_basebackup version and exits.
+
-? --help
+ Shows help about pg_basebackup command line
+ arguments, and exits.
+
+
Environment
+ This utility, like most other PostgreSQL utilities,
+ uses the environment variables supported by libpq
+ (see Section 34.15).
+
+ The environment variable PG_COLOR specifies whether to use
+ color in diagnostic messages. Possible values are
+ always, auto and
+ never.
+
Notes
+ At the beginning of the backup, a checkpoint needs to be performed on the
+ source server. This can take some time (especially if the option
+ --checkpoint=fast is not used), during
+ which pg_basebackup will appear to be idle.
+
+ The backup will include all files in the data directory and tablespaces,
+ including the configuration files and any additional files placed in the
+ directory by third parties, except certain temporary files managed by
+ PostgreSQL and operating system files. But only regular files and
+ directories are copied, except that
+ symbolic links used for tablespaces are preserved. Symbolic links pointing
+ to certain directories known to PostgreSQL are copied as empty directories.
+ Other symbolic links and special device files are skipped.
+ See Section 55.4 for the precise details.
+
+ In plain format, tablespaces will be backed up to the same path
+ they have on the source server, unless the
+ option --tablespace-mapping is used. Without
+ this option, running a plain format base backup on the same host as the
+ server will not work if tablespaces are in use, because the backup would
+ have to be written to the same directory locations as the original
+ tablespaces.
+
+ When tar format is used, it is the user's responsibility to unpack each
+ tar file before starting a PostgreSQL server that uses the data. If there
+ are additional tablespaces, the
+ tar files for them need to be unpacked in the correct locations. In this
+ case the symbolic links for those tablespaces will be created by the server
+ according to the contents of the tablespace_map file that is
+ included in the base.tar file.
+
+ pg_basebackup works with servers of the same
+ or an older major version, down to 9.1. However, WAL streaming mode (-X
+ stream) only works with server version 9.3 and later, and tar format
+ (--format=tar) only works with server version 9.5
+ and later.
+
+ pg_basebackup will preserve group permissions
+ for data files if group permissions are enabled on the source cluster.
+
Examples
+ To create a base backup of the server at mydbserver
+ and store it in the local directory
+ /usr/local/pgsql/data:
+
+ To create a backup of the local server with one compressed
+ tar file for each tablespace, and store it in the directory
+ backup, showing a progress report while running:
+
+$pg_basebackup -D backup -Ft -z -P
+
+
+ To create a backup of a single-tablespace local database and compress
+ this with bzip2:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgchecksums.html b/pgsql/doc/postgresql/html/app-pgchecksums.html
new file mode 100644
index 0000000000000000000000000000000000000000..336df0336a09a296f54befaf2360981873bf5021
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgchecksums.html
@@ -0,0 +1,75 @@
+
+pg_checksums
+ pg_checksums checks, enables or disables data
+ checksums in a PostgreSQL cluster. The server
+ must be shut down cleanly before running
+ pg_checksums. When verifying checksums, the exit
+ status is zero if there are no checksum errors, and nonzero if at least one
+ checksum failure is detected. When enabling or disabling checksums, the
+ exit status is nonzero if the operation failed.
+
+ When verifying checksums, every file in the cluster is scanned. When
+ enabling checksums, each relation file block with a changed checksum is
+ rewritten in-place.
+ Disabling checksums only updates the file pg_control.
+
Options
+ The following command-line options are available:
+
+
-D directory --pgdata=directory
+ Specifies the directory where the database cluster is stored.
+
-c --check
+ Checks checksums. This is the default mode if nothing else is
+ specified.
+
-d --disable
+ Disables checksums.
+
-e --enable
+ Enables checksums.
+
-f filenode --filenode=filenode
+ Only validate checksums in the relation with filenode
+ filenode.
+
-N --no-sync
+ By default, pg_checksums will wait for all files
+ to be written safely to disk. This option causes
+ pg_checksums to return without waiting, which is
+ faster, but means that a subsequent operating system crash can leave
+ the updated data directory corrupt. Generally, this option is useful
+ for testing but should not be used on a production installation.
+ This option has no effect when using --check.
+
-P --progress
+ Enable progress reporting. Turning this on will deliver a progress
+ report while checking or enabling checksums.
+
-v --verbose
+ Enable verbose output. Lists all checked files.
+
-V --version
+ Print the pg_checksums version and exit.
+
-? --help
+ Show help about pg_checksums command line
+ arguments, and exit.
+
+
Environment
PGDATA
+ Specifies the directory where the database cluster is
+ stored; can be overridden using the -D option.
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
Notes
+ Enabling checksums in a large cluster can potentially take a long time.
+ During this operation, the cluster or other programs that write to the
+ data directory must not be started or else data loss may occur.
+
+ When using a replication setup with tools which perform direct copies
+ of relation file blocks (for example pg_rewind),
+ enabling or disabling checksums can lead to page corruptions in the
+ shape of incorrect checksums if the operation is not done consistently
+ across all nodes. When enabling or disabling checksums in a replication
+ setup, it is thus recommended to stop all the clusters before switching
+ them all consistently. Destroying all standbys, performing the operation
+ on the primary and finally recreating the standbys from scratch is also
+ safe.
+
+ If pg_checksums is aborted or killed while
+ enabling or disabling checksums, the cluster's data checksum configuration
+ remains unchanged, and pg_checksums can be
+ re-run to perform the same operation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgconfig.html b/pgsql/doc/postgresql/html/app-pgconfig.html
new file mode 100644
index 0000000000000000000000000000000000000000..4fae09fb36b897857b95b7d64f2e1dac9d9768d8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgconfig.html
@@ -0,0 +1,110 @@
+
+pg_config
pg_config — retrieve information about the installed version of PostgreSQL
Synopsis
pg_config [option...]
Description
+ The pg_config utility prints configuration parameters
+ of the currently installed version of PostgreSQL. It is
+ intended, for example, to be used by software packages that want to interface
+ to PostgreSQL to facilitate finding the required header files
+ and libraries.
+
Options
+ To use pg_config, supply one or more of the following
+ options:
+
--bindir
+ Print the location of user executables. Use this, for example, to find
+ the psql program. This is normally also the location
+ where the pg_config program resides.
+
--docdir
+ Print the location of documentation files.
+
--htmldir
+ Print the location of HTML documentation files.
+
--includedir
+ Print the location of C header files of the client interfaces.
+
--pkgincludedir
+ Print the location of other C header files.
+
--includedir-server
+ Print the location of C header files for server programming.
+
--libdir
+ Print the location of object code libraries.
+
--pkglibdir
+ Print the location of dynamically loadable modules, or where
+ the server would search for them. (Other
+ architecture-dependent data files might also be installed in this
+ directory.)
+
--localedir
+ Print the location of locale support files. (This will be an empty
+ string if locale support was not configured when
+ PostgreSQL was built.)
+
--mandir
+ Print the location of manual pages.
+
--sharedir
+ Print the location of architecture-independent support files.
+
--sysconfdir
+ Print the location of system-wide configuration files.
+
--pgxs
+ Print the location of extension makefiles.
+
--configure
+ Print the options that were given to the configure
+ script when PostgreSQL was configured for building.
+ This can be used to reproduce the identical configuration, or
+ to find out with what options a binary package was built. (Note
+ however that binary packages often contain vendor-specific custom
+ patches.) See also the examples below.
+
--cc
+ Print the value of the CC variable that was used for building
+ PostgreSQL. This shows the C compiler used.
+
--cppflags
+ Print the value of the CPPFLAGS variable that was used for building
+ PostgreSQL. This shows C compiler switches needed
+ at preprocessing time (typically, -I switches).
+
--cflags
+ Print the value of the CFLAGS variable that was used for building
+ PostgreSQL. This shows C compiler switches.
+
--cflags_sl
+ Print the value of the CFLAGS_SL variable that was used for building
+ PostgreSQL. This shows extra C compiler switches
+ used for building shared libraries.
+
--ldflags
+ Print the value of the LDFLAGS variable that was used for building
+ PostgreSQL. This shows linker switches.
+
--ldflags_ex
+ Print the value of the LDFLAGS_EX variable that was used for building
+ PostgreSQL. This shows linker switches
+ used for building executables only.
+
--ldflags_sl
+ Print the value of the LDFLAGS_SL variable that was used for building
+ PostgreSQL. This shows linker switches
+ used for building shared libraries only.
+
--libs
+ Print the value of the LIBS variable that was used for building
+ PostgreSQL. This normally contains -l
+ switches for external libraries linked into PostgreSQL.
+
--version
+ Print the version of PostgreSQL.
+
-? --help
+ Show help about pg_config command line
+ arguments, and exit.
+
+
+ If more than one option is given, the information is printed in that order,
+ one item per line. If no options are given, all available information
+ is printed, with labels.
+
Notes
+ The options --docdir, --pkgincludedir,
+ --localedir, --mandir,
+ --sharedir, --sysconfdir,
+ --cc, --cppflags,
+ --cflags, --cflags_sl,
+ --ldflags, --ldflags_sl,
+ and --libs were added in PostgreSQL 8.1.
+ The option --htmldir was added in PostgreSQL 8.4.
+ The option --ldflags_ex was added in PostgreSQL 9.0.
+
Example
+ To reproduce the build configuration of the current PostgreSQL
+ installation, run the following command:
+
+eval ./configure `pg_config --configure`
+
+ The output of pg_config --configure contains
+ shell quotation marks so arguments with spaces are represented
+ correctly. Therefore, using eval is required
+ for proper results.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgcontroldata.html b/pgsql/doc/postgresql/html/app-pgcontroldata.html
new file mode 100644
index 0000000000000000000000000000000000000000..86daa8080547e9ddfecd18ae815736579e197b71
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgcontroldata.html
@@ -0,0 +1,23 @@
+
+pg_controldata
+ pg_controldata prints information initialized during
+ initdb, such as the catalog version.
+ It also shows information about write-ahead logging and checkpoint
+ processing. This information is cluster-wide, and not specific to any one
+ database.
+
+ This utility can only be run by the user who initialized the cluster because
+ it requires read access to the data directory.
+ You can specify the data directory on the command line, or use
+ the environment variable PGDATA. This utility supports the options
+ -V and --version, which print the
+ pg_controldata version and exit. It also
+ supports options -? and --help, which output the
+ supported arguments.
+
Environment
PGDATA
+ Default data directory location
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgdump.html b/pgsql/doc/postgresql/html/app-pgdump.html
new file mode 100644
index 0000000000000000000000000000000000000000..be8ad938966fc764361500fc3a1e6a1be79f0208
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgdump.html
@@ -0,0 +1,863 @@
+
+pg_dump
+ pg_dump is a utility for backing up a
+ PostgreSQL database. It makes consistent
+ backups even if the database is being used concurrently.
+ pg_dump does not block other users
+ accessing the database (readers or writers).
+
+ pg_dump only dumps a single database.
+ To back up an entire cluster, or to back up global objects that are
+ common to all databases in a cluster (such as roles and tablespaces),
+ use pg_dumpall.
+
+ Dumps can be output in script or archive file formats. Script
+ dumps are plain-text files containing the SQL commands required
+ to reconstruct the database to the state it was in at the time it was
+ saved. To restore from such a script, feed it to psql. Script files
+ can be used to reconstruct the database even on other machines and
+ other architectures; with some modifications, even on other SQL
+ database products.
+
+ The alternative archive file formats must be used with
+ pg_restore to rebuild the database. They
+ allow pg_restore to be selective about
+ what is restored, or even to reorder the items prior to being
+ restored.
+ The archive file formats are designed to be portable across
+ architectures.
+
+ When used with one of the archive file formats and combined with
+ pg_restore,
+ pg_dump provides a flexible archival and
+ transfer mechanism. pg_dump can be used to
+ backup an entire database, then pg_restore
+ can be used to examine the archive and/or select which parts of the
+ database are to be restored. The most flexible output file formats are
+ the “custom” format (-Fc) and the
+ “directory” format (-Fd). They allow
+ for selection and reordering of all archived items, support parallel
+ restoration, and are compressed by default. The “directory”
+ format is the only format that supports parallel dumps.
+
+ While running pg_dump, one should examine the
+ output for any warnings (printed on standard error), especially in
+ light of the limitations listed below.
+
Options
+ The following command-line options control the content and
+ format of the output.
+
+
dbname
+ Specifies the name of the database to be dumped. If this is
+ not specified, the environment variable
+ PGDATABASE is used. If that is not set, the
+ user name specified for the connection is used.
+
-a --data-only
+ Dump only the data, not the schema (data definitions).
+ Table data, large objects, and sequence values are dumped.
+
+ This option is similar to, but for historical reasons not identical
+ to, specifying --section=data.
+
-b --large-objects --blobs (deprecated)
+ Include large objects in the dump. This is the default behavior
+ except when --schema, --table, or
+ --schema-only is specified. The -b
+ switch is therefore only useful to add large objects to dumps
+ where a specific schema or table has been requested. Note that
+ large objects are considered data and therefore will be included when
+ --data-only is used, but not
+ when --schema-only is.
+
-B --no-large-objects --no-blobs (deprecated)
+ Exclude large objects in the dump.
+
+ When both -b and -B are given, the behavior
+ is to output large objects, when data is being dumped, see the
+ -b documentation.
+
-c --clean
+ Output commands to DROP all the dumped
+ database objects prior to outputting the commands for creating them.
+ This option is useful when the restore is to overwrite an existing
+ database. If any of the objects do not exist in the destination
+ database, ignorable error messages will be reported during
+ restore, unless --if-exists is also specified.
+
+ This option is ignored when emitting an archive (non-text) output
+ file. For the archive formats, you can specify the option when you
+ call pg_restore.
+
-C --create
+ Begin the output with a command to create the
+ database itself and reconnect to the created database. (With a
+ script of this form, it doesn't matter which database in the
+ destination installation you connect to before running the script.)
+ If --clean is also specified, the script drops and
+ recreates the target database before reconnecting to it.
+
+ With --create, the output also includes the
+ database's comment if any, and any configuration variable settings
+ that are specific to this database, that is,
+ any ALTER DATABASE ... SET ...
+ and ALTER ROLE ... IN DATABASE ... SET ...
+ commands that mention this database.
+ Access privileges for the database itself are also dumped,
+ unless --no-acl is specified.
+
+ This option is ignored when emitting an archive (non-text) output
+ file. For the archive formats, you can specify the option when you
+ call pg_restore.
+
-e pattern --extension=pattern
+ Dump only extensions matching pattern. When this option is not
+ specified, all non-system extensions in the target database will be
+ dumped. Multiple extensions can be selected by writing multiple
+ -e switches. The pattern parameter is interpreted as a
+ pattern according to the same rules used by
+ psql's \d commands (see
+ Patterns), so multiple extensions can also
+ be selected by writing wildcard characters in the pattern. When using
+ wildcards, be careful to quote the pattern if needed to prevent the
+ shell from expanding the wildcards.
+
+ Any configuration relation registered by
+ pg_extension_config_dump is included in the
+ dump if its extension is specified by --extension.
+
Note
+ When -e is specified,
+ pg_dump makes no attempt to dump any other
+ database objects that the selected extension(s) might depend upon.
+ Therefore, there is no guarantee that the results of a
+ specific-extension dump can be successfully restored by themselves
+ into a clean database.
+
-E encoding --encoding=encoding
+ Create the dump in the specified character set encoding. By default,
+ the dump is created in the database encoding. (Another way to get the
+ same result is to set the PGCLIENTENCODING environment
+ variable to the desired dump encoding.) The supported encodings are
+ described in Section 24.3.1.
+
-f file --file=file
+ Send output to the specified file. This parameter can be omitted for
+ file based output formats, in which case the standard output is used.
+ It must be given for the directory output format however, where it
+ specifies the target directory instead of a file. In this case the
+ directory is created by pg_dump and must not exist
+ before.
+
-F format --format=format
+ Selects the format of the output.
+ format can be one of the following:
+
+
p plain
+ Output a plain-text SQL script file (the default).
+
c custom
+ Output a custom-format archive suitable for input into
+ pg_restore.
+ Together with the directory output format, this is the most flexible
+ output format in that it allows manual selection and reordering of
+ archived items during restore. This format is also compressed by
+ default.
+
d directory
+ Output a directory-format archive suitable for input into
+ pg_restore. This will create a directory
+ with one file for each table and large object being dumped, plus a
+ so-called Table of Contents file describing the dumped objects in a
+ machine-readable format that pg_restore
+ can read. A directory format archive can be manipulated with
+ standard Unix tools; for example, files in an uncompressed archive
+ can be compressed with the gzip,
+ lz4, or
+ zstd tools.
+ This format is compressed by default using gzip
+ and also supports parallel dumps.
+
t tar
+ Output a tar-format archive suitable for input
+ into pg_restore. The tar format is
+ compatible with the directory format: extracting a tar-format
+ archive produces a valid directory-format archive.
+ However, the tar format does not support compression. Also, when
+ using tar format the relative order of table data items cannot be
+ changed during restore.
+
-j njobs --jobs=njobs
+ Run the dump in parallel by dumping njobs
+ tables simultaneously. This option may reduce the time needed to perform the dump but it also
+ increases the load on the database server. You can only use this option with the
+ directory output format because this is the only output format where multiple processes
+ can write their data at the same time.
+
pg_dump will open njobs
+ + 1 connections to the database, so make sure your max_connections
+ setting is high enough to accommodate all connections.
+
+ Requesting exclusive locks on database objects while running a parallel dump could
+ cause the dump to fail. The reason is that the pg_dump leader process
+ requests shared locks (ACCESS SHARE) on the
+ objects that the worker processes are going to dump later in order to
+ make sure that nobody deletes them and makes them go away while the dump is running.
+ If another client then requests an exclusive lock on a table, that lock will not be
+ granted but will be queued waiting for the shared lock of the leader process to be
+ released. Consequently any other access to the table will not be granted either and
+ will queue after the exclusive lock request. This includes the worker process trying
+ to dump the table. Without any precautions this would be a classic deadlock situation.
+ To detect this conflict, the pg_dump worker process requests another
+ shared lock using the NOWAIT option. If the worker process is not granted
+ this shared lock, somebody else must have requested an exclusive lock in the meantime
+ and there is no way to continue with the dump, so pg_dump has no choice
+ but to abort the dump.
+
+ To perform a parallel dump, the database server needs to support
+ synchronized snapshots, a feature that was introduced in
+ PostgreSQL 9.2 for primary servers and 10
+ for standbys. With this feature, database clients can ensure they see
+ the same data set even though they use different connections.
+ pg_dump -j uses multiple database connections; it
+ connects to the database once with the leader process and once again
+ for each worker job. Without the synchronized snapshot feature, the
+ different worker jobs wouldn't be guaranteed to see the same data in
+ each connection, which could lead to an inconsistent backup.
+
-n pattern --schema=pattern
+ Dump only schemas matching pattern; this selects both the
+ schema itself, and all its contained objects. When this option is
+ not specified, all non-system schemas in the target database will be
+ dumped. Multiple schemas can be
+ selected by writing multiple -n switches. The
+ pattern parameter is
+ interpreted as a pattern according to the same rules used by
+ psql's \d commands
+ (see Patterns),
+ so multiple schemas can also be selected by writing wildcard characters
+ in the pattern. When using wildcards, be careful to quote the pattern
+ if needed to prevent the shell from expanding the wildcards; see
+ Examples below.
+
Note
+ When -n is specified, pg_dump
+ makes no attempt to dump any other database objects that the selected
+ schema(s) might depend upon. Therefore, there is no guarantee
+ that the results of a specific-schema dump can be successfully
+ restored by themselves into a clean database.
+
Note
+ Non-schema objects such as large objects are not dumped when -n is
+ specified. You can add large objects back to the dump with the
+ --large-objects switch.
+
-N pattern --exclude-schema=pattern
+ Do not dump any schemas matching pattern. The pattern is
+ interpreted according to the same rules as for -n.
+ -N can be given more than once to exclude schemas
+ matching any of several patterns.
+
+ When both -n and -N are given, the behavior
+ is to dump just the schemas that match at least one -n
+ switch but no -N switches. If -N appears
+ without -n, then schemas matching -N are
+ excluded from what is otherwise a normal dump.
+
-O --no-owner
+ Do not output commands to set
+ ownership of objects to match the original database.
+ By default, pg_dump issues
+ ALTER OWNER or
+ SET SESSION AUTHORIZATION
+ statements to set ownership of created database objects.
+ These statements
+ will fail when the script is run unless it is started by a superuser
+ (or the same user that owns all of the objects in the script).
+ To make a script that can be restored by any user, but will give
+ that user ownership of all the objects, specify -O.
+
+ This option is ignored when emitting an archive (non-text) output
+ file. For the archive formats, you can specify the option when you
+ call pg_restore.
+
-R --no-reconnect
+ This option is obsolete but still accepted for backwards
+ compatibility.
+
-s --schema-only
+ Dump only the object definitions (schema), not data.
+
+ This option is the inverse of --data-only.
+ It is similar to, but for historical reasons not identical to,
+ specifying
+ --section=pre-data --section=post-data.
+
+ (Do not confuse this with the --schema option, which
+ uses the word “schema” in a different meaning.)
+
+ To exclude table data for only a subset of tables in the database,
+ see --exclude-table-data.
+
-S username --superuser=username
+ Specify the superuser user name to use when disabling triggers.
+ This is relevant only if --disable-triggers is used.
+ (Usually, it's better to leave this out, and instead start the
+ resulting script as superuser.)
+
-t pattern --table=pattern
+ Dump only tables with names matching
+ pattern. Multiple tables
+ can be selected by writing multiple -t switches. The
+ pattern parameter is
+ interpreted as a pattern according to the same rules used by
+ psql's \d commands
+ (see Patterns),
+ so multiple tables can also be selected by writing wildcard characters
+ in the pattern. When using wildcards, be careful to quote the pattern
+ if needed to prevent the shell from expanding the wildcards; see
+ Examples below.
+
+ As well as tables, this option can be used to dump the definition of matching
+ views, materialized views, foreign tables, and sequences. It will not dump the
+ contents of views or materialized views, and the contents of foreign tables will
+ only be dumped if the corresponding foreign server is specified with
+ --include-foreign-data.
+
+ The -n and -N switches have no effect when
+ -t is used, because tables selected by -t will
+ be dumped regardless of those switches, and non-table objects will not
+ be dumped.
+
Note
+ When -t is specified, pg_dump
+ makes no attempt to dump any other database objects that the selected
+ table(s) might depend upon. Therefore, there is no guarantee
+ that the results of a specific-table dump can be successfully
+ restored by themselves into a clean database.
+
-T pattern --exclude-table=pattern
+ Do not dump any tables matching pattern. The pattern is
+ interpreted according to the same rules as for -t.
+ -T can be given more than once to exclude tables
+ matching any of several patterns.
+
+ When both -t and -T are given, the behavior
+ is to dump just the tables that match at least one -t
+ switch but no -T switches. If -T appears
+ without -t, then tables matching -T are
+ excluded from what is otherwise a normal dump.
+
-v --verbose
+ Specifies verbose mode. This will cause
+ pg_dump to output detailed object
+ comments and start/stop times to the dump file, and progress
+ messages to standard error.
+ Repeating the option causes additional debug-level messages
+ to appear on standard error.
+
-V --version
+ Print the pg_dump version and exit.
+
-x --no-privileges --no-acl
+ Prevent dumping of access privileges (grant/revoke commands).
+
+ Specify the compression method and/or the compression level to use.
+ The compression method can be set to gzip,
+ lz4, zstd,
+ or none for no compression.
+ A compression detail string can optionally be specified. If the
+ detail string is an integer, it specifies the compression level.
+ Otherwise, it should be a comma-separated list of items, each of the
+ form keyword or keyword=value.
+ Currently, the supported keywords are level and
+ long.
+
+ If no compression level is specified, the default compression
+ level will be used. If only a level is specified without mentioning
+ an algorithm, gzip compression will be used if
+ the level is greater than 0, and no compression
+ will be used if the level is 0.
+
+ For the custom and directory archive formats, this specifies compression of
+ individual table-data segments, and the default is to compress using
+ gzip at a moderate level. For plain text output,
+ setting a nonzero compression level causes the entire output file to be compressed,
+ as though it had been fed through gzip,
+ lz4, or zstd;
+ but the default is not to compress.
+ With zstd compression, long mode may improve the
+ compression ratio, at the cost of increased memory use.
+
+ The tar archive format currently does not support compression at all.
+
--binary-upgrade
+ This option is for use by in-place upgrade utilities. Its use
+ for other purposes is not recommended or supported. The
+ behavior of the option may change in future releases without
+ notice.
+
--column-inserts --attribute-inserts
+ Dump data as INSERT commands with explicit
+ column names (INSERT INTO
+ table
+ (column, ...) VALUES
+ ...). This will make restoration very slow; it is mainly
+ useful for making dumps that can be loaded into
+ non-PostgreSQL databases.
+ Any error during restoring will cause only rows that are part of the
+ problematic INSERT to be lost, rather than the
+ entire table contents.
+
--disable-dollar-quoting
+ This option disables the use of dollar quoting for function bodies,
+ and forces them to be quoted using SQL standard string syntax.
+
--disable-triggers
+ This option is relevant only when creating a data-only dump.
+ It instructs pg_dump to include commands
+ to temporarily disable triggers on the target tables while
+ the data is restored. Use this if you have referential
+ integrity checks or other triggers on the tables that you
+ do not want to invoke during data restore.
+
+ Presently, the commands emitted for --disable-triggers
+ must be done as superuser. So, you should also specify
+ a superuser name with -S, or preferably be careful to
+ start the resulting script as a superuser.
+
+ This option is ignored when emitting an archive (non-text) output
+ file. For the archive formats, you can specify the option when you
+ call pg_restore.
+
--enable-row-security
+ This option is relevant only when dumping the contents of a table
+ which has row security. By default, pg_dump will set
+ row_security to off, to ensure
+ that all data is dumped from the table. If the user does not have
+ sufficient privileges to bypass row security, then an error is thrown.
+ This parameter instructs pg_dump to set
+ row_security to on instead, allowing the user
+ to dump the parts of the contents of the table that they have access to.
+
+ Note that if you use this option currently, you probably also want
+ the dump be in INSERT format, as the
+ COPY FROM during restore does not support row security.
+
--exclude-table-and-children=pattern
+ This is the same as
+ the -T/--exclude-table option,
+ except that it also excludes any partitions or inheritance child
+ tables of the table(s) matching the
+ pattern.
+
--exclude-table-data=pattern
+ Do not dump data for any tables matching pattern. The pattern is
+ interpreted according to the same rules as for -t.
+ --exclude-table-data can be given more than once to
+ exclude tables matching any of several patterns. This option is
+ useful when you need the definition of a particular table even
+ though you do not need the data in it.
+
+ To exclude data for all tables in the database, see --schema-only.
+
--exclude-table-data-and-children=pattern
+ This is the same as the --exclude-table-data option,
+ except that it also excludes data of any partitions or inheritance
+ child tables of the table(s) matching the
+ pattern.
+
--extra-float-digits=ndigits
+ Use the specified value of extra_float_digits when dumping
+ floating-point data, instead of the maximum available precision.
+ Routine dumps made for backup purposes should not use this option.
+
--if-exists
+ Use DROP ... IF EXISTS commands to drop objects
+ in --clean mode. This suppresses “does not
+ exist” errors that might otherwise be reported. This
+ option is not valid unless --clean is also
+ specified.
+
--include-foreign-data=foreignserver
+ Dump the data for any foreign table with a foreign server
+ matching foreignserver
+ pattern. Multiple foreign servers can be selected by writing multiple
+ --include-foreign-data switches.
+ Also, the foreignserver parameter is
+ interpreted as a pattern according to the same rules used by
+ psql's \d commands
+ (see Patterns),
+ so multiple foreign servers can also be selected by writing wildcard characters
+ in the pattern. When using wildcards, be careful to quote the pattern
+ if needed to prevent the shell from expanding the wildcards; see
+ Examples below.
+ The only exception is that an empty pattern is disallowed.
+
Note
+ When --include-foreign-data is specified,
+ pg_dump does not check that the foreign
+ table is writable. Therefore, there is no guarantee that the
+ results of a foreign table dump can be successfully restored.
+
--inserts
+ Dump data as INSERT commands (rather
+ than COPY). This will make restoration very slow;
+ it is mainly useful for making dumps that can be loaded into
+ non-PostgreSQL databases.
+ Any error during restoring will cause only rows that are part of the
+ problematic INSERT to be lost, rather than the
+ entire table contents. Note that the restore might fail altogether if
+ you have rearranged column order. The
+ --column-inserts option is safe against column order
+ changes, though even slower.
+
--load-via-partition-root
+ When dumping data for a table partition, make
+ the COPY or INSERT statements
+ target the root of the partitioning hierarchy that contains it, rather
+ than the partition itself. This causes the appropriate partition to
+ be re-determined for each row when the data is loaded. This may be
+ useful when restoring data on a server where rows do not always fall
+ into the same partitions as they did on the original server. That
+ could happen, for example, if the partitioning column is of type text
+ and the two systems have different definitions of the collation used
+ to sort the partitioning column.
+
--lock-wait-timeout=timeout
+ Do not wait forever to acquire shared table locks at the beginning of
+ the dump. Instead fail if unable to lock a table within the specified
+ timeout. The timeout may be
+ specified in any of the formats accepted by SET
+ statement_timeout. (Allowed formats vary depending on the server
+ version you are dumping from, but an integer number of milliseconds
+ is accepted by all versions.)
+
--no-comments
+ Do not dump comments.
+
--no-publications
+ Do not dump publications.
+
--no-security-labels
+ Do not dump security labels.
+
--no-subscriptions
+ Do not dump subscriptions.
+
--no-sync
+ By default, pg_dump will wait for all files
+ to be written safely to disk. This option causes
+ pg_dump to return without waiting, which is
+ faster, but means that a subsequent operating system crash can leave
+ the dump corrupt. Generally, this option is useful for testing
+ but should not be used when dumping data from production installation.
+
--no-table-access-method
+ Do not output commands to select table access methods.
+ With this option, all objects will be created with whichever
+ table access method is the default during restore.
+
+ This option is ignored when emitting an archive (non-text) output
+ file. For the archive formats, you can specify the option when you
+ call pg_restore.
+
--no-tablespaces
+ Do not output commands to select tablespaces.
+ With this option, all objects will be created in whichever
+ tablespace is the default during restore.
+
+ This option is ignored when emitting an archive (non-text) output
+ file. For the archive formats, you can specify the option when you
+ call pg_restore.
+
--no-toast-compression
+ Do not output commands to set TOAST compression
+ methods.
+ With this option, all columns will be restored with the default
+ compression setting.
+
--no-unlogged-table-data
+ Do not dump the contents of unlogged tables and sequences. This
+ option has no effect on whether or not the table and sequence
+ definitions (schema) are dumped; it only suppresses dumping the table
+ and sequence data. Data in unlogged tables and sequences
+ is always excluded when dumping from a standby server.
+
--on-conflict-do-nothing
+ Add ON CONFLICT DO NOTHING to
+ INSERT commands.
+ This option is not valid unless --inserts,
+ --column-inserts or
+ --rows-per-insert is also specified.
+
--quote-all-identifiers
+ Force quoting of all identifiers. This option is recommended when
+ dumping a database from a server whose PostgreSQL
+ major version is different from pg_dump's, or when
+ the output is intended to be loaded into a server of a different
+ major version. By default, pg_dump quotes only
+ identifiers that are reserved words in its own major version.
+ This sometimes results in compatibility issues when dealing with
+ servers of other versions that may have slightly different sets
+ of reserved words. Using --quote-all-identifiers prevents
+ such issues, at the price of a harder-to-read dump script.
+
--rows-per-insert=nrows
+ Dump data as INSERT commands (rather than
+ COPY). Controls the maximum number of rows per
+ INSERT command. The value specified must be a
+ number greater than zero. Any error during restoring will cause only
+ rows that are part of the problematic INSERT to be
+ lost, rather than the entire table contents.
+
--section=sectionname
+ Only dump the named section. The section name can be
+ pre-data, data, or post-data.
+ This option can be specified more than once to select multiple
+ sections. The default is to dump all sections.
+
+ The data section contains actual table data, large-object
+ contents, and sequence values.
+ Post-data items include definitions of indexes, triggers, rules,
+ and constraints other than validated check constraints.
+ Pre-data items include all other data definition items.
+
--serializable-deferrable
+ Use a serializable transaction for the dump, to
+ ensure that the snapshot used is consistent with later database
+ states; but do this by waiting for a point in the transaction stream
+ at which no anomalies can be present, so that there isn't a risk of
+ the dump failing or causing other transactions to roll back with a
+ serialization_failure. See Chapter 13
+ for more information about transaction isolation and concurrency
+ control.
+
+ This option is not beneficial for a dump which is intended only for
+ disaster recovery. It could be useful for a dump used to load a
+ copy of the database for reporting or other read-only load sharing
+ while the original database continues to be updated. Without it the
+ dump may reflect a state which is not consistent with any serial
+ execution of the transactions eventually committed. For example, if
+ batch processing techniques are used, a batch may show as closed in
+ the dump without all of the items which are in the batch appearing.
+
+ This option will make no difference if there are no read-write
+ transactions active when pg_dump is started. If read-write
+ transactions are active, the start of the dump may be delayed for an
+ indeterminate length of time. Once running, performance with or
+ without the switch is the same.
+
--snapshot=snapshotname
+ Use the specified synchronized snapshot when making a dump of the
+ database (see
+ Table 9.94 for more
+ details).
+
+ This option is useful when needing to synchronize the dump with
+ a logical replication slot (see Chapter 49)
+ or with a concurrent session.
+
+ In the case of a parallel dump, the snapshot name defined by this
+ option is used rather than taking a new snapshot.
+
--strict-names
+ Require that each
+ extension (-e/--extension),
+ schema (-n/--schema) and
+ table (-t/--table) pattern
+ match at least one extension/schema/table in the database to be dumped.
+ Note that if none of the extension/schema/table patterns find
+ matches, pg_dump will generate an error
+ even without --strict-names.
+
+ This option has no effect
+ on -N/--exclude-schema,
+ -T/--exclude-table,
+ or --exclude-table-data. An exclude pattern failing
+ to match any objects is not considered an error.
+
--table-and-children=pattern
+ This is the same as
+ the -t/--table option,
+ except that it also includes any partitions or inheritance child
+ tables of the table(s) matching the
+ pattern.
+
--use-set-session-authorization
+ Output SQL-standard SET SESSION AUTHORIZATION commands
+ instead of ALTER OWNER commands to determine object
+ ownership. This makes the dump more standards-compatible, but
+ depending on the history of the objects in the dump, might not restore
+ properly. Also, a dump using SET SESSION AUTHORIZATION
+ will certainly require superuser privileges to restore correctly,
+ whereas ALTER OWNER requires lesser privileges.
+
-? --help
+ Show help about pg_dump command line
+ arguments, and exit.
+
+
+ The following command-line options control the database connection parameters.
+
+
-d dbname --dbname=dbname
+ Specifies the name of the database to connect to. This is
+ equivalent to specifying dbname as the first non-option
+ argument on the command line. The dbname
+ can be a connection string.
+ If so, connection string parameters will override any conflicting
+ command line options.
+
-h host --host=host
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for the Unix domain socket. The default is taken
+ from the PGHOST environment variable, if set,
+ else a Unix domain socket connection is attempted.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server is listening for connections.
+ Defaults to the PGPORT environment variable, if
+ set, or a compiled-in default.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force pg_dump to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ pg_dump will automatically prompt
+ for a password if the server demands password authentication.
+ However, pg_dump will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--role=rolename
+ Specifies a role name to be used to create the dump.
+ This option causes pg_dump to issue a
+ SET ROLErolename
+ command after connecting to the database. It is useful when the
+ authenticated user (specified by -U) lacks privileges
+ needed by pg_dump, but can switch to a role with
+ the required rights. Some installations have a policy against
+ logging in directly as a superuser, and use of this option allows
+ dumps to be made without violating the policy.
+
+
Environment
PGDATABASE PGHOST PGOPTIONS PGPORT PGUSER
+ Default connection parameters.
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ pg_dump internally executes
+ SELECT statements. If you have problems running
+ pg_dump, make sure you are able to
+ select information from the database using, for example, psql. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
+ The database activity of pg_dump is
+ normally collected by the cumulative statistics system. If this is
+ undesirable, you can set parameter track_counts
+ to false via PGOPTIONS or the ALTER
+ USER command.
+
Notes
+ If your database cluster has any local additions to the template1 database,
+ be careful to restore the output of pg_dump into a
+ truly empty database; otherwise you are likely to get errors due to
+ duplicate definitions of the added objects. To make an empty database
+ without any local additions, copy from template0 not template1,
+ for example:
+
+CREATE DATABASE foo WITH TEMPLATE template0;
+
+
+ When a data-only dump is chosen and the option --disable-triggers
+ is used, pg_dump emits commands
+ to disable triggers on user tables before inserting the data,
+ and then commands to re-enable them after the data has been
+ inserted. If the restore is stopped in the middle, the system
+ catalogs might be left in the wrong state.
+
+ The dump file produced by pg_dump
+ does not contain the statistics used by the optimizer to make
+ query planning decisions. Therefore, it is wise to run
+ ANALYZE after restoring from a dump file
+ to ensure optimal performance; see Section 25.1.3
+ and Section 25.1.6 for more information.
+
+ Because pg_dump is used to transfer data
+ to newer versions of PostgreSQL, the output of
+ pg_dump can be expected to load into
+ PostgreSQL server versions newer than
+ pg_dump's version. pg_dump can also
+ dump from PostgreSQL servers older than its own version.
+ (Currently, servers back to version 9.2 are supported.)
+ However, pg_dump cannot dump from
+ PostgreSQL servers newer than its own major version;
+ it will refuse to even try, rather than risk making an invalid dump.
+ Also, it is not guaranteed that pg_dump's output can
+ be loaded into a server of an older major version — not even if the
+ dump was taken from a server of that version. Loading a dump file
+ into an older server may require manual editing of the dump file
+ to remove syntax not understood by the older server.
+ Use of the --quote-all-identifiers option is recommended
+ in cross-version cases, as it can prevent problems arising from varying
+ reserved-word lists in different PostgreSQL versions.
+
+ When dumping logical replication subscriptions,
+ pg_dump will generate CREATE
+ SUBSCRIPTION commands that use the connect = false
+ option, so that restoring the subscription does not make remote connections
+ for creating a replication slot or for initial table copy. That way, the
+ dump can be restored without requiring network access to the remote
+ servers. It is then up to the user to reactivate the subscriptions in a
+ suitable way. If the involved hosts have changed, the connection
+ information might have to be changed. It might also be appropriate to
+ truncate the target tables before initiating a new full table copy. If users
+ intend to copy initial data during refresh they must create the slot with
+ two_phase = false. After the initial sync, the
+ two_phase
+ option will be automatically enabled by the subscriber if the subscription
+ had been originally created with two_phase = true option.
+
Examples
+ To dump a database called mydb into an SQL-script file:
+
+$pg_dump mydb > db.sql
+
+
+ To reload such a script into a (freshly created) database named
+ newdb:
+
+
+$psql -d newdb -f db.sql
+
+
+ To dump a database into a custom-format archive file:
+
+
+$pg_dump -Fc mydb > db.dump
+
+
+ To dump a database into a directory-format archive:
+
+
+$pg_dump -Fd mydb -f dumpdir
+
+
+ To dump a database into a directory-format archive in parallel with
+ 5 worker jobs:
+
+
+$pg_dump -Fd mydb -j 5 -f dumpdir
+
+
+ To reload an archive file into a (freshly created) database named
+ newdb:
+
+
+$pg_restore -d newdb db.dump
+
+
+ To reload an archive file into the same database it was dumped from,
+ discarding the current contents of that database:
+
+
+ To dump all database objects except for tables whose names begin with
+ ts_:
+
+
+$pg_dump -T 'ts_*' mydb > db.sql
+
+
+ To specify an upper-case or mixed-case name in -t and related
+ switches, you need to double-quote the name; else it will be folded to
+ lower case (see Patterns). But
+ double quotes are special to the shell, so in turn they must be quoted.
+ Thus, to dump a single table with a mixed-case name, you need something
+ like
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgreceivewal.html b/pgsql/doc/postgresql/html/app-pgreceivewal.html
new file mode 100644
index 0000000000000000000000000000000000000000..224cd57f84b1743426700ac214d8d0de251b3a62
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgreceivewal.html
@@ -0,0 +1,251 @@
+
+pg_receivewal
pg_receivewal — stream write-ahead logs from a PostgreSQL server
Synopsis
pg_receivewal [option...]
Description
+ pg_receivewal is used to stream the write-ahead log
+ from a running PostgreSQL cluster. The write-ahead
+ log is streamed using the streaming replication protocol, and is written
+ to a local directory of files. This directory can be used as the archive
+ location for doing a restore using point-in-time recovery (see
+ Section 26.3).
+
+ pg_receivewal streams the write-ahead
+ log in real time as it's being generated on the server, and does not wait
+ for segments to complete like archive_command and
+ archive_library do.
+ For this reason, it is not necessary to set
+ archive_timeout when using
+ pg_receivewal.
+
+ Unlike the WAL receiver of a PostgreSQL standby server, pg_receivewal
+ by default flushes WAL data only when a WAL file is closed.
+ The option --synchronous must be specified to flush WAL data
+ in real time. Since pg_receivewal does not
+ apply WAL, you should not allow it to become a synchronous standby when
+ synchronous_commit equals
+ remote_apply. If it does, it will appear to be a
+ standby that never catches up, and will cause transaction commits to
+ block. To avoid this, you should either configure an appropriate value
+ for synchronous_standby_names, or specify
+ application_name for
+ pg_receivewal that does not match it, or
+ change the value of synchronous_commit to
+ something other than remote_apply.
+
+ The write-ahead log is streamed over a regular
+ PostgreSQL connection and uses the replication
+ protocol. The connection must be made with a user having
+ REPLICATION permissions (see
+ Section 22.2) or a superuser, and
+ pg_hba.conf must permit the replication connection.
+ The server must also be configured with
+ max_wal_senders set high enough to leave at least
+ one session available for the stream.
+
+ The starting point of the write-ahead log streaming is calculated when
+ pg_receivewal starts:
+
+ First, scan the directory where the WAL segment files are written and
+ find the newest completed segment file, using as the starting point the
+ beginning of the next WAL segment file.
+
+ If a starting point cannot be calculated with the previous method,
+ and if a replication slot is used, an extra
+ READ_REPLICATION_SLOT command is issued to retrieve
+ the slot's restart_lsn to use as the starting point.
+ This option is only available when streaming write-ahead logs from
+ PostgreSQL 15 and up.
+
+ If a starting point cannot be calculated with the previous method,
+ the latest WAL flush location is used as reported by the server from
+ an IDENTIFY_SYSTEM command.
+
+
+ If the connection is lost, or if it cannot be initially established,
+ with a non-fatal error, pg_receivewal will
+ retry the connection indefinitely, and reestablish streaming as soon
+ as possible. To avoid this behavior, use the -n
+ parameter.
+
+ In the absence of fatal errors, pg_receivewal
+ will run until terminated by the SIGINT
+ (Control+C)
+ or SIGTERM signal.
+
Options
-D directory --directory=directory
+ Directory to write the output to.
+
+ This parameter is required.
+
-E lsn --endpos=lsn
+ Automatically stop replication and exit with normal exit status 0 when
+ receiving reaches the specified LSN.
+
+ If there is a record with LSN exactly equal to lsn,
+ the record will be processed.
+
--if-not-exists
+ Do not error out when --create-slot is specified
+ and a slot with the specified name already exists.
+
-n --no-loop
+ Don't loop on connection errors. Instead, exit right away with
+ an error.
+
--no-sync
+ This option causes pg_receivewal to not force WAL
+ data to be flushed to disk. This is faster, but means that a
+ subsequent operating system crash can leave the WAL segments corrupt.
+ Generally, this option is useful for testing but should not be used
+ when doing WAL archiving on a production deployment.
+
+ This option is incompatible with --synchronous.
+
-s interval --status-interval=interval
+ Specifies the number of seconds between status packets sent back to the
+ server. This allows for easier monitoring of the progress from server.
+ A value of zero disables the periodic status updates completely,
+ although an update will still be sent when requested by the server, to
+ avoid timeout disconnect. The default value is 10 seconds.
+
-S slotname --slot=slotname
+ Require pg_receivewal to use an existing
+ replication slot (see Section 27.2.6).
+ When this option is used, pg_receivewal will report
+ a flush position to the server, indicating when each segment has been
+ synchronized to disk so that the server can remove that segment if it
+ is not otherwise needed.
+
+ When the replication client
+ of pg_receivewal is configured on the
+ server as a synchronous standby, then using a replication slot will
+ report the flush position to the server, but only when a WAL file is
+ closed. Therefore, that configuration will cause transactions on the
+ primary to wait for a long time and effectively not work
+ satisfactorily. The option --synchronous (see
+ below) must be specified in addition to make this work correctly.
+
--synchronous
+ Flush the WAL data to disk immediately after it has been received. Also
+ send a status packet back to the server immediately after flushing,
+ regardless of --status-interval.
+
+ This option should be specified if the replication client
+ of pg_receivewal is configured on the
+ server as a synchronous standby, to ensure that timely feedback is
+ sent to the server.
+
+ The compression method can be set to gzip,
+ lz4 (if PostgreSQL
+ was compiled with --with-lz4) or
+ none for no compression.
+ A compression detail string can optionally be specified. If the
+ detail string is an integer, it specifies the compression level.
+ Otherwise, it should be a comma-separated list of items, each of the
+ form keyword or keyword=value.
+ Currently, the only supported keyword is level.
+
+ If no compression level is specified, the default compression level
+ will be used. If only a level is specified without mentioning an
+ algorithm, gzip compression will be used if the
+ level is greater than 0, and no compression will be used if the level
+ is 0.
+
+ The suffix .gz will automatically be added to
+ all filenames when using gzip, and the suffix
+ .lz4 is added when using lz4.
+
+ The following command-line options control the database connection parameters.
+
+
-d connstr --dbname=connstr
+ Specifies parameters used to connect to the server, as a connection string; these
+ will override any conflicting command line options.
+
+ The option is called --dbname for consistency with other
+ client applications, but because pg_receivewal
+ doesn't connect to any particular database in the cluster, database
+ name in the connection string will be ignored.
+
-h host --host=host
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for the Unix domain socket. The default is taken
+ from the PGHOST environment variable, if set,
+ else a Unix domain socket connection is attempted.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server is listening for connections.
+ Defaults to the PGPORT environment variable, if
+ set, or a compiled-in default.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force pg_receivewal to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ pg_receivewal will automatically prompt
+ for a password if the server demands password authentication.
+ However, pg_receivewal will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
+
+ pg_receivewal can perform one of the two
+ following actions in order to control physical replication slots:
+
+
--create-slot
+ Create a new physical replication slot with the name specified in
+ --slot, then exit.
+
--drop-slot
+ Drop the replication slot with the name specified in
+ --slot, then exit.
+
+
+ Other options are also available:
+
+
-V --version
+ Print the pg_receivewal version and exit.
+
-? --help
+ Show help about pg_receivewal command line
+ arguments, and exit.
+
+
Exit Status
+ pg_receivewal will exit with status 0 when
+ terminated by the SIGINT or
+ SIGTERM signal. (That is the
+ normal way to end it. Hence it is not an error.) For fatal errors or
+ other signals, the exit status will be nonzero.
+
Environment
+ This utility, like most other PostgreSQL utilities,
+ uses the environment variables supported by libpq
+ (see Section 34.15).
+
+ The environment variable PG_COLOR specifies whether to use
+ color in diagnostic messages. Possible values are
+ always, auto and
+ never.
+
Notes
+ When using pg_receivewal instead of
+ archive_command or
+ archive_library as the main WAL backup method, it is
+ strongly recommended to use replication slots. Otherwise, the server is
+ free to recycle or remove write-ahead log files before they are backed up,
+ because it does not have any information, either
+ from archive_command or
+ archive_library or the replication slots, about
+ how far the WAL stream has been archived. Note, however, that a
+ replication slot will fill up the server's disk space if the receiver does
+ not keep up with fetching the WAL data.
+
+ pg_receivewal will preserve group permissions on
+ the received WAL files if group permissions are enabled on the source
+ cluster.
+
Examples
+ To stream the write-ahead log from the server at
+ mydbserver and store it in the local directory
+ /usr/local/pgsql/archive:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgreceivexlog.html b/pgsql/doc/postgresql/html/app-pgreceivexlog.html
new file mode 100644
index 0000000000000000000000000000000000000000..8fff1bd0cc21dc1504888b36f7b9938f14076cc8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgreceivexlog.html
@@ -0,0 +1,10 @@
+
+O.5. pg_receivexlog renamed to pg_receivewal
+ PostgreSQL 9.6 and below provided a command named
+ pg_receivexlog
+
+ to fetch write-ahead-log (WAL) files. This command was renamed to pg_receivewal, see
+ pg_receivewal for documentation of pg_receivewal and see
+ the release notes for PostgreSQL 10 for details
+ on this change.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgrecvlogical.html b/pgsql/doc/postgresql/html/app-pgrecvlogical.html
new file mode 100644
index 0000000000000000000000000000000000000000..9e0f0a4ee84444fa785e25c1cff5f1819841ff71
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgrecvlogical.html
@@ -0,0 +1,188 @@
+
+pg_recvlogical
pg_recvlogical — control PostgreSQL logical decoding streams
Synopsis
pg_recvlogical [option...]
Description
+ pg_recvlogical controls logical decoding replication
+ slots and streams data from such replication slots.
+
+ It creates a replication-mode connection, so it is subject to the same
+ constraints as pg_receivewal, plus those for logical
+ replication (see Chapter 49).
+
+ pg_recvlogical has no equivalent to the logical decoding
+ SQL interface's peek and get modes. It sends replay confirmations for
+ data lazily as it receives it and on clean exit. To examine pending data on
+ a slot without consuming it, use
+ pg_logical_slot_peek_changes.
+
+ In the absence of fatal errors, pg_recvlogical
+ will run until terminated by the SIGINT
+ (Control+C)
+ or SIGTERM signal.
+
Options
+ At least one of the following options must be specified to select an action:
+
+
--create-slot
+ Create a new logical replication slot with the name specified by
+ --slot, using the output plugin specified by
+ --plugin, for the database specified
+ by --dbname.
+
+ The --two-phase can be specified with
+ --create-slot to enable decoding of prepared transactions.
+
--drop-slot
+ Drop the replication slot with the name specified
+ by --slot, then exit.
+
--start
+ Begin streaming changes from the logical replication slot specified
+ by --slot, continuing until terminated by a
+ signal. If the server side change stream ends with a server shutdown
+ or disconnect, retry in a loop unless
+ --no-loop is specified.
+
+ The stream format is determined by the output plugin specified when
+ the slot was created.
+
+ The connection must be to the same database used to create the slot.
+
+
+ --create-slot and --start can be
+ specified together. --drop-slot cannot be combined with
+ another action.
+
+ The following command-line options control the location and format of the
+ output and other replication behavior:
+
+
-E lsn --endpos=lsn
+ In --start mode, automatically stop replication
+ and exit with normal exit status 0 when receiving reaches the
+ specified LSN. If specified when not in --start
+ mode, an error is raised.
+
+ If there's a record with LSN exactly equal to lsn,
+ the record will be output.
+
+ The --endpos option is not aware of transaction
+ boundaries and may truncate output partway through a transaction.
+ Any partially output transaction will not be consumed and will be
+ replayed again when the slot is next read from. Individual messages
+ are never truncated.
+
-f filename --file=filename
+ Write received and decoded transaction data into this
+ file. Use - for stdout.
+
+ Specifies how often pg_recvlogical should
+ issue fsync() calls to ensure the output file is
+ safely flushed to disk.
+
+ The server will occasionally request the client to perform a flush and
+ report the flush position to the server. This setting is in addition
+ to that, to perform flushes more frequently.
+
+ Specifying an interval of 0 disables
+ issuing fsync() calls altogether, while still
+ reporting progress to the server. In this case, data could be lost in
+ the event of a crash.
+
-I lsn --startpos=lsn
+ In --start mode, start replication from the given
+ LSN. For details on the effect of this, see the documentation
+ in Chapter 49
+ and Section 55.4. Ignored in other modes.
+
--if-not-exists
+ Do not error out when --create-slot is specified
+ and a slot with the specified name already exists.
+
-n --no-loop
+ When the connection to the server is lost, do not retry in a loop, just exit.
+
-o name[=value] --option=name[=value]
+ Pass the option name to the output plugin with,
+ if specified, the option value value. Which
+ options exist and their effects depends on the used output plugin.
+
-P plugin --plugin=plugin
+ When creating a slot, use the specified logical decoding output
+ plugin. See Chapter 49. This option has no
+ effect if the slot already exists.
+
+ This option has the same effect as the option of the same name
+ in pg_receivewal. See the description there.
+
-S slot_name --slot=slot_name
+ In --start mode, use the existing logical replication slot named
+ slot_name. In --create-slot
+ mode, create the slot with this name. In --drop-slot
+ mode, delete the slot with this name.
+
-t --two-phase
+ Enables decoding of prepared transactions. This option may only be specified with
+ --create-slot
+
-v --verbose
+ Enables verbose mode.
+
+
+ The following command-line options control the database connection parameters.
+
+
-d dbname --dbname=dbname
+ The database to connect to. See the description
+ of the actions for what this means in detail.
+ The dbname can be a connection string. If so,
+ connection string parameters will override any conflicting
+ command line options. Defaults to the user name.
+
-h hostname-or-ip --host=hostname-or-ip
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for the Unix domain socket. The default is taken
+ from the PGHOST environment variable, if set,
+ else a Unix domain socket connection is attempted.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server is listening for connections.
+ Defaults to the PGPORT environment variable, if
+ set, or a compiled-in default.
+
-U user --username=user
+ User name to connect as. Defaults to current operating system user
+ name.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force pg_recvlogical to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ pg_recvlogical will automatically prompt
+ for a password if the server demands password authentication.
+ However, pg_recvlogical will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
+
+ The following additional options are available:
+
+
-V --version
+ Print the pg_recvlogical version and exit.
+
-? --help
+ Show help about pg_recvlogical command line
+ arguments, and exit.
+
+
Exit Status
+ pg_recvlogical will exit with status 0 when
+ terminated by the SIGINT or
+ SIGTERM signal. (That is the
+ normal way to end it. Hence it is not an error.) For fatal errors or
+ other signals, the exit status will be nonzero.
+
Environment
+ This utility, like most other PostgreSQL utilities,
+ uses the environment variables supported by libpq
+ (see Section 34.15).
+
+ The environment variable PG_COLOR specifies whether to use
+ color in diagnostic messages. Possible values are
+ always, auto and
+ never.
+
Notes
+ pg_recvlogical will preserve group permissions on
+ the received WAL files if group permissions are enabled on the source
+ cluster.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgresetwal.html b/pgsql/doc/postgresql/html/app-pgresetwal.html
new file mode 100644
index 0000000000000000000000000000000000000000..0f9903b3bcd8cd14a87682da32b1be5a00527223
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgresetwal.html
@@ -0,0 +1,169 @@
+
+pg_resetwal
+ pg_resetwal clears the write-ahead log (WAL) and
+ optionally resets some other control information stored in the
+ pg_control file. This function is sometimes needed
+ if these files have become corrupted. It should be used only as a
+ last resort, when the server will not start due to such corruption.
+
+ After running this command, it should be possible to start the server,
+ but bear in mind that the database might contain inconsistent data due to
+ partially-committed transactions. You should immediately dump your data,
+ run initdb, and restore. After restore, check for
+ inconsistencies and repair as needed.
+
+ This utility can only be run by the user who installed the server, because
+ it requires read/write access to the data directory.
+ For safety reasons, you must specify the data directory on the command line.
+ pg_resetwal does not use the environment variable
+ PGDATA.
+
+ If pg_resetwal complains that it cannot determine
+ valid data for pg_control, you can force it to proceed anyway
+ by specifying the -f (force) option. In this case plausible
+ values will be substituted for the missing data. Most of the fields can be
+ expected to match, but manual assistance might be needed for the next OID,
+ next transaction ID and epoch, next multitransaction ID and offset, and
+ WAL starting location fields. These fields can be set using the options
+ discussed below. If you are not able to determine correct values for all
+ these fields, -f can still be used, but
+ the recovered database must be treated with even more suspicion than
+ usual: an immediate dump and restore is imperative. Do not
+ execute any data-modifying operations in the database before you dump,
+ as any such action is likely to make the corruption worse.
+
Options
-f --force
+ Force pg_resetwal to proceed even if it cannot determine
+ valid data for pg_control, as explained above.
+
-n --dry-run
+ The -n/--dry-run option instructs
+ pg_resetwal to print the values reconstructed from
+ pg_control and values about to be changed, and then exit
+ without modifying anything. This is mainly a debugging tool, but can be
+ useful as a sanity check before allowing pg_resetwal
+ to proceed for real.
+
-V --version
Display version information, then exit.
-? --help
Show help, then exit.
+ The following options are only needed when
+ pg_resetwal is unable to determine appropriate values
+ by reading pg_control. Safe values can be determined as
+ described below. For values that take numeric arguments, hexadecimal
+ values can be specified by using the prefix 0x.
+
-c xid,xid --commit-timestamp-ids=xid,xid
+ Manually set the oldest and newest transaction IDs for which the commit
+ time can be retrieved.
+
+ A safe value for the oldest transaction ID for which the commit time can
+ be retrieved (first part) can be determined by looking
+ for the numerically smallest file name in the directory
+ pg_commit_ts under the data directory. Conversely, a safe
+ value for the newest transaction ID for which the commit time can be
+ retrieved (second part) can be determined by looking for the numerically
+ greatest file name in the same directory. The file names are in
+ hexadecimal.
+
-e xid_epoch --epoch=xid_epoch
+ Manually set the next transaction ID's epoch.
+
+ The transaction ID epoch is not actually stored anywhere in the database
+ except in the field that is set by pg_resetwal,
+ so any value will work so far as the database itself is concerned.
+ You might need to adjust this value to ensure that replication
+ systems such as Slony-I and
+ Skytools work correctly —
+ if so, an appropriate value should be obtainable from the state of
+ the downstream replicated database.
+
-l walfile --next-wal-file=walfile
+ Manually set the WAL starting location by specifying the name of the
+ next WAL segment file.
+
+ The name of next WAL segment file should be
+ larger than any WAL segment file name currently existing in
+ the directory pg_wal under the data directory.
+ These names are also in hexadecimal and have three parts. The first
+ part is the “timeline ID” and should usually be kept the same.
+ For example, if 00000001000000320000004A is the
+ largest entry in pg_wal, use -l 00000001000000320000004B or higher.
+
+ Note that when using nondefault WAL segment sizes, the numbers in the WAL
+ file names are different from the LSNs that are reported by system
+ functions and system views. This option takes a WAL file name, not an
+ LSN.
+
Note
+ pg_resetwal itself looks at the files in
+ pg_wal and chooses a default -l setting
+ beyond the last existing file name. Therefore, manual adjustment of
+ -l should only be needed if you are aware of WAL segment
+ files that are not currently present in pg_wal, such as
+ entries in an offline archive; or if the contents of
+ pg_wal have been lost entirely.
+
-m mxid,mxid --multixact-ids=mxid,mxid
+ Manually set the next and oldest multitransaction ID.
+
+ A safe value for the next multitransaction ID (first part) can be
+ determined by looking for the numerically largest file name in the
+ directory pg_multixact/offsets under the data directory,
+ adding one, and then multiplying by 65536 (0x10000). Conversely, a safe
+ value for the oldest multitransaction ID (second part of
+ -m) can be determined by looking for the numerically smallest
+ file name in the same directory and multiplying by 65536. The file
+ names are in hexadecimal, so the easiest way to do this is to specify
+ the option value in hexadecimal and append four zeroes.
+
-o oid --next-oid=oid
+ Manually set the next OID.
+
+ There is no comparably easy way to determine a next OID that's beyond
+ the largest one in the database, but fortunately it is not critical to
+ get the next-OID setting right.
+
-O mxoff --multixact-offset=mxoff
+ Manually set the next multitransaction offset.
+
+ A safe value can be determined by looking for the numerically largest
+ file name in the directory pg_multixact/members under the
+ data directory, adding one, and then multiplying by 52352 (0xCC80).
+ The file names are in hexadecimal. There is no simple recipe such as
+ the ones for other options of appending zeroes.
+
--wal-segsize=wal_segment_size
+ Set the new WAL segment size, in megabytes. The value must be set to a
+ power of 2 between 1 and 1024 (megabytes). See the same option of initdb for more information.
+
Note
+ While pg_resetwal will set the WAL starting address
+ beyond the latest existing WAL segment file, some segment size changes
+ can cause previous WAL file names to be reused. It is recommended to
+ use -l together with this option to manually set the
+ WAL starting address if WAL file name overlap will cause problems with
+ your archiving strategy.
+
-u xid --oldest-transaction-id=xid
+ Manually set the oldest unfrozen transaction ID.
+
+ A safe value can be determined by looking for the numerically smallest
+ file name in the directory pg_xact under the data directory
+ and then multiplying by 1048576 (0x100000). Note that the file names are in
+ hexadecimal. It is usually easiest to specify the option value in
+ hexadecimal too. For example, if 0007 is the smallest entry
+ in pg_xact, -u 0x700000 will work (five
+ trailing zeroes provide the proper multiplier).
+
-x xid --next-transaction-id=xid
+ Manually set the next transaction ID.
+
+ A safe value can be determined by looking for the numerically largest
+ file name in the directory pg_xact under the data directory,
+ adding one,
+ and then multiplying by 1048576 (0x100000). Note that the file names are in
+ hexadecimal. It is usually easiest to specify the option value in
+ hexadecimal too. For example, if 0011 is the largest entry
+ in pg_xact, -x 0x1200000 will work (five
+ trailing zeroes provide the proper multiplier).
+
Environment
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
Notes
+ This command must not be used when the server is
+ running. pg_resetwal will refuse to start up if
+ it finds a server lock file in the data directory. If the
+ server crashed then a lock file might have been left
+ behind; in that case you can remove the lock file to allow
+ pg_resetwal to run. But before you do
+ so, make doubly certain that there is no server process still alive.
+
+ pg_resetwal works only with servers of the same
+ major version.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgresetxlog.html b/pgsql/doc/postgresql/html/app-pgresetxlog.html
new file mode 100644
index 0000000000000000000000000000000000000000..80d5570949ffd441531de4fa0b801eb7f62265d7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgresetxlog.html
@@ -0,0 +1,10 @@
+
+O.4. pg_resetxlog renamed to pg_resetwal
+ PostgreSQL 9.6 and below provided a command named
+ pg_resetxlog
+
+ to reset the write-ahead-log (WAL) files. This command was renamed to pg_resetwal, see
+ pg_resetwal for documentation of pg_resetwal and see
+ the release notes for PostgreSQL 10 for details
+ on this change.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgrestore.html b/pgsql/doc/postgresql/html/app-pgrestore.html
new file mode 100644
index 0000000000000000000000000000000000000000..969f3ded2657cf82db05f44eb8aed4c3fb8b3659
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgrestore.html
@@ -0,0 +1,504 @@
+
+pg_restore
+ pg_restore is a utility for restoring a
+ PostgreSQL database from an archive
+ created by pg_dump in one of the non-plain-text
+ formats. It will issue the commands necessary to reconstruct the
+ database to the state it was in at the time it was saved. The
+ archive files also allow pg_restore to
+ be selective about what is restored, or even to reorder the items
+ prior to being restored. The archive files are designed to be
+ portable across architectures.
+
+ pg_restore can operate in two modes.
+ If a database name is specified, pg_restore
+ connects to that database and restores archive contents directly into
+ the database. Otherwise, a script containing the SQL
+ commands necessary to rebuild the database is created and written
+ to a file or standard output. This script output is equivalent to
+ the plain text output format of pg_dump.
+ Some of the options controlling the output are therefore analogous to
+ pg_dump options.
+
+ Obviously, pg_restore cannot restore information
+ that is not present in the archive file. For instance, if the
+ archive was made using the “dump data as
+ INSERT commands” option,
+ pg_restore will not be able to load the data
+ using COPY statements.
+
Options
+ pg_restore accepts the following command
+ line arguments.
+
+
filename
+ Specifies the location of the archive file (or directory, for a
+ directory-format archive) to be restored.
+ If not specified, the standard input is used.
+
-a --data-only
+ Restore only the data, not the schema (data definitions).
+ Table data, large objects, and sequence values are restored,
+ if present in the archive.
+
+ This option is similar to, but for historical reasons not identical
+ to, specifying --section=data.
+
-c --clean
+ Before restoring database objects, issue commands
+ to DROP all the objects that will be restored.
+ This option is useful for overwriting an existing database.
+ If any of the objects do not exist in the destination database,
+ ignorable error messages will be reported,
+ unless --if-exists is also specified.
+
-C --create
+ Create the database before restoring into it.
+ If --clean is also specified, drop and
+ recreate the target database before connecting to it.
+
+ With --create, pg_restore
+ also restores the database's comment if any, and any configuration
+ variable settings that are specific to this database, that is,
+ any ALTER DATABASE ... SET ...
+ and ALTER ROLE ... IN DATABASE ... SET ...
+ commands that mention this database.
+ Access privileges for the database itself are also restored,
+ unless --no-acl is specified.
+
+ When this option is used, the database named with -d
+ is used only to issue the initial DROP DATABASE and
+ CREATE DATABASE commands. All data is restored into the
+ database name that appears in the archive.
+
-d dbname --dbname=dbname
+ Connect to database dbname and restore directly
+ into the database. The dbname can
+ be a connection string.
+ If so, connection string parameters will override any conflicting
+ command line options.
+
-e --exit-on-error
+ Exit if an error is encountered while sending SQL commands to
+ the database. The default is to continue and to display a count of
+ errors at the end of the restoration.
+
-f filename --file=filename
+ Specify output file for generated script, or for the listing
+ when used with -l. Use -
+ for stdout.
+
-F format --format=format
+ Specify format of the archive. It is not necessary to specify
+ the format, since pg_restore will
+ determine the format automatically. If specified, it can be
+ one of the following:
+
+
c custom
+ The archive is in the custom format of
+ pg_dump.
+
d directory
+ The archive is a directory archive.
+
t tar
+ The archive is a tar archive.
+
-I index --index=index
+ Restore definition of named index only. Multiple indexes
+ may be specified with multiple -I switches.
+
-j number-of-jobs --jobs=number-of-jobs
+ Run the most time-consuming steps
+ of pg_restore — those that load data,
+ create indexes, or create constraints — concurrently, using up
+ to number-of-jobs
+ concurrent sessions. This option can dramatically reduce the time
+ to restore a large database to a server running on a
+ multiprocessor machine. This option is ignored when emitting a script
+ rather than connecting directly to a database server.
+
+ Each job is one process or one thread, depending on the
+ operating system, and uses a separate connection to the
+ server.
+
+ The optimal value for this option depends on the hardware
+ setup of the server, of the client, and of the network.
+ Factors include the number of CPU cores and the disk setup. A
+ good place to start is the number of CPU cores on the server,
+ but values larger than that can also lead to faster restore
+ times in many cases. Of course, values that are too high will
+ lead to decreased performance because of thrashing.
+
+ Only the custom and directory archive formats are supported
+ with this option.
+ The input must be a regular file or directory (not, for example, a
+ pipe or standard input). Also, multiple
+ jobs cannot be used together with the
+ option --single-transaction.
+
-l --list
+ List the table of contents of the archive. The output of this operation
+ can be used as input to the -L option. Note that
+ if filtering switches such as -n or -t are
+ used with -l, they will restrict the items listed.
+
-L list-file --use-list=list-file
+ Restore only those archive elements that are listed in list-file, and restore them in the
+ order they appear in the file. Note that
+ if filtering switches such as -n or -t are
+ used with -L, they will further restrict the items restored.
+
list-file is normally created by
+ editing the output of a previous -l operation.
+ Lines can be moved or removed, and can also
+ be commented out by placing a semicolon (;) at the
+ start of the line. See below for examples.
+
-n schema --schema=schema
+ Restore only objects that are in the named schema. Multiple schemas
+ may be specified with multiple -n switches. This can be
+ combined with the -t option to restore just a
+ specific table.
+
-N schema --exclude-schema=schema
+ Do not restore objects that are in the named schema. Multiple schemas
+ to be excluded may be specified with multiple -N switches.
+
+ When both -n and -N are given for the same
+ schema name, the -N switch wins and the schema is excluded.
+
-O --no-owner
+ Do not output commands to set
+ ownership of objects to match the original database.
+ By default, pg_restore issues
+ ALTER OWNER or
+ SET SESSION AUTHORIZATION
+ statements to set ownership of created schema elements.
+ These statements will fail unless the initial connection to the
+ database is made by a superuser
+ (or the same user that owns all of the objects in the script).
+ With -O, any user name can be used for the
+ initial connection, and this user will own all the created objects.
+
+ Restore the named function only. Be careful to spell the function
+ name and arguments exactly as they appear in the dump file's table
+ of contents. Multiple functions may be specified with multiple
+ -P switches.
+
-R --no-reconnect
+ This option is obsolete but still accepted for backwards
+ compatibility.
+
-s --schema-only
+ Restore only the schema (data definitions), not data,
+ to the extent that schema entries are present in the archive.
+
+ This option is the inverse of --data-only.
+ It is similar to, but for historical reasons not identical to,
+ specifying
+ --section=pre-data --section=post-data.
+
+ (Do not confuse this with the --schema option, which
+ uses the word “schema” in a different meaning.)
+
-S username --superuser=username
+ Specify the superuser user name to use when disabling triggers.
+ This is relevant only if --disable-triggers is used.
+
-t table --table=table
+ Restore definition and/or data of only the named table.
+ For this purpose, “table” includes views, materialized views,
+ sequences, and foreign tables. Multiple tables
+ can be selected by writing multiple -t switches.
+ This option can be combined with the -n option to
+ specify table(s) in a particular schema.
+
Note
+ When -t is specified, pg_restore
+ makes no attempt to restore any other database objects that the
+ selected table(s) might depend upon. Therefore, there is no
+ guarantee that a specific-table restore into a clean database will
+ succeed.
+
Note
+ This flag does not behave identically to the -t
+ flag of pg_dump. There is not currently
+ any provision for wild-card matching in pg_restore,
+ nor can you include a schema name within its -t.
+ And, while pg_dump's -t
+ flag will also dump subsidiary objects (such as indexes) of the
+ selected table(s),
+ pg_restore's -t
+ flag does not include such subsidiary objects.
+
Note
+ In versions prior to PostgreSQL 9.6, this flag
+ matched only tables, not any other type of relation.
+
-T trigger --trigger=trigger
+ Restore named trigger only. Multiple triggers may be specified with
+ multiple -T switches.
+
-v --verbose
+ Specifies verbose mode. This will cause
+ pg_restore to output detailed object
+ comments and start/stop times to the output file, and progress
+ messages to standard error.
+ Repeating the option causes additional debug-level messages
+ to appear on standard error.
+
-V --version
+ Print the pg_restore version and exit.
+
-x --no-privileges --no-acl
+ Prevent restoration of access privileges (grant/revoke commands).
+
-1 --single-transaction
+ Execute the restore as a single transaction (that is, wrap the
+ emitted commands in BEGIN/COMMIT). This
+ ensures that either all the commands complete successfully, or no
+ changes are applied. This option implies
+ --exit-on-error.
+
--disable-triggers
+ This option is relevant only when performing a data-only restore.
+ It instructs pg_restore to execute commands
+ to temporarily disable triggers on the target tables while
+ the data is restored. Use this if you have referential
+ integrity checks or other triggers on the tables that you
+ do not want to invoke during data restore.
+
+ Presently, the commands emitted for
+ --disable-triggers must be done as superuser. So you
+ should also specify a superuser name with -S or,
+ preferably, run pg_restore as a
+ PostgreSQL superuser.
+
--enable-row-security
+ This option is relevant only when restoring the contents of a table
+ which has row security. By default, pg_restore will set
+ row_security to off, to ensure
+ that all data is restored in to the table. If the user does not have
+ sufficient privileges to bypass row security, then an error is thrown.
+ This parameter instructs pg_restore to set
+ row_security to on instead, allowing the user to attempt to restore
+ the contents of the table with row security enabled. This might still
+ fail if the user does not have the right to insert the rows from the
+ dump into the table.
+
+ Note that this option currently also requires the dump be in INSERT
+ format, as COPY FROM does not support row security.
+
--if-exists
+ Use DROP ... IF EXISTS commands to drop objects
+ in --clean mode. This suppresses “does not
+ exist” errors that might otherwise be reported. This
+ option is not valid unless --clean is also
+ specified.
+
--no-comments
+ Do not output commands to restore comments, even if the archive
+ contains them.
+
--no-data-for-failed-tables
+ By default, table data is restored even if the creation command
+ for the table failed (e.g., because it already exists).
+ With this option, data for such a table is skipped.
+ This behavior is useful if the target database already
+ contains the desired table contents. For example,
+ auxiliary tables for PostgreSQL extensions
+ such as PostGIS might already be loaded in
+ the target database; specifying this option prevents duplicate
+ or obsolete data from being loaded into them.
+
+ This option is effective only when restoring directly into a
+ database, not when producing SQL script output.
+
--no-publications
+ Do not output commands to restore publications, even if the archive
+ contains them.
+
--no-security-labels
+ Do not output commands to restore security labels,
+ even if the archive contains them.
+
--no-subscriptions
+ Do not output commands to restore subscriptions, even if the archive
+ contains them.
+
--no-table-access-method
+ Do not output commands to select table access methods.
+ With this option, all objects will be created with whichever
+ access method is the default during restore.
+
--no-tablespaces
+ Do not output commands to select tablespaces.
+ With this option, all objects will be created in whichever
+ tablespace is the default during restore.
+
--section=sectionname
+ Only restore the named section. The section name can be
+ pre-data, data, or post-data.
+ This option can be specified more than once to select multiple
+ sections. The default is to restore all sections.
+
+ The data section contains actual table data as well as large-object
+ definitions.
+ Post-data items consist of definitions of indexes, triggers, rules
+ and constraints other than validated check constraints.
+ Pre-data items consist of all other data definition items.
+
--strict-names
+ Require that each schema
+ (-n/--schema) and table
+ (-t/--table) qualifier match at
+ least one schema/table in the backup file.
+
--use-set-session-authorization
+ Output SQL-standard SET SESSION AUTHORIZATION commands
+ instead of ALTER OWNER commands to determine object
+ ownership. This makes the dump more standards-compatible, but
+ depending on the history of the objects in the dump, might not restore
+ properly.
+
-? --help
+ Show help about pg_restore command line
+ arguments, and exit.
+
+
+ pg_restore also accepts
+ the following command line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for the Unix domain socket. The default is taken
+ from the PGHOST environment variable, if set,
+ else a Unix domain socket connection is attempted.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server is listening for connections.
+ Defaults to the PGPORT environment variable, if
+ set, or a compiled-in default.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force pg_restore to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ pg_restore will automatically prompt
+ for a password if the server demands password authentication.
+ However, pg_restore will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--role=rolename
+ Specifies a role name to be used to perform the restore.
+ This option causes pg_restore to issue a
+ SET ROLErolename
+ command after connecting to the database. It is useful when the
+ authenticated user (specified by -U) lacks privileges
+ needed by pg_restore, but can switch to a role with
+ the required rights. Some installations have a policy against
+ logging in directly as a superuser, and use of this option allows
+ restores to be performed without violating the policy.
+
+
Environment
PGHOST PGOPTIONS PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15). However, it does not read
+ PGDATABASE when a database name is not supplied.
+
Diagnostics
+ When a direct database connection is specified using the
+ -d option, pg_restore
+ internally executes SQL statements. If you have
+ problems running pg_restore, make sure
+ you are able to select information from the database using, for
+ example, psql. Also, any default connection
+ settings and environment variables used by the
+ libpq front-end library will apply.
+
Notes
+ If your installation has any local additions to the
+ template1 database, be careful to load the output of
+ pg_restore into a truly empty database;
+ otherwise you are likely to get errors due to duplicate definitions
+ of the added objects. To make an empty database without any local
+ additions, copy from template0 not template1, for example:
+
+CREATE DATABASE foo WITH TEMPLATE template0;
+
+
+ The limitations of pg_restore are detailed below.
+
+
+ When restoring data to a pre-existing table and the option
+ --disable-triggers is used,
+ pg_restore emits commands
+ to disable triggers on user tables before inserting the data, then emits commands to
+ re-enable them after the data has been inserted. If the restore is stopped in the
+ middle, the system catalogs might be left in the wrong state.
+
pg_restore cannot restore large objects
+ selectively; for instance, only those for a specific table. If
+ an archive contains large objects, then all large objects will be
+ restored, or none of them if they are excluded via -L,
+ -t, or other options.
+
+
+ See also the pg_dump documentation for details on
+ limitations of pg_dump.
+
+ Once restored, it is wise to run ANALYZE on each
+ restored table so the optimizer has useful statistics; see
+ Section 25.1.3 and
+ Section 25.1.6 for more information.
+
Examples
+ Assume we have dumped a database called mydb into a
+ custom-format dump file:
+
+
+$pg_dump -Fc mydb > db.dump
+
+
+ To drop the database and recreate it from the dump:
+
+
+
+ The database named in the -d switch can be any database existing
+ in the cluster; pg_restore only uses it to issue the
+ CREATE DATABASE command for mydb. With
+ -C, data is always restored into the database name that appears
+ in the dump file.
+
+ To restore the dump into a new database called newdb:
+
+
+
+ Notice we don't use -C, and instead connect directly to the
+ database to be restored into. Also note that we clone the new database
+ from template0 not template1, to ensure it is
+ initially empty.
+
+ To reorder database items, it is first necessary to dump the table of
+ contents of the archive:
+
+$pg_restore -l db.dump > db.list
+
+ The listing file consists of a header and one line for each item, e.g.:
+
+;
+; Archive created at Mon Sep 14 13:55:39 2009
+; dbname: DBDEMOS
+; TOC Entries: 81
+; Compression: 9
+; Dump Version: 1.10-0
+; Format: CUSTOM
+; Integer: 4 bytes
+; Offset: 8 bytes
+; Dumped from database version: 8.3.5
+; Dumped by pg_dump version: 8.3.8
+;
+;
+; Selected TOC Entries:
+;
+3; 2615 2200 SCHEMA - public pasha
+1861; 0 0 COMMENT - SCHEMA public pasha
+1862; 0 0 ACL - public pasha
+317; 1247 17715 TYPE public composite pasha
+319; 1247 25899 DOMAIN public domain0 pasha
+
+ Semicolons start a comment, and the numbers at the start of lines refer to the
+ internal archive ID assigned to each item.
+
+ Lines in the file can be commented out, deleted, and reordered. For example:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgrewind.html b/pgsql/doc/postgresql/html/app-pgrewind.html
new file mode 100644
index 0000000000000000000000000000000000000000..96ceddc641bfc25323fa283999153159dc9e35b7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgrewind.html
@@ -0,0 +1,210 @@
+
+pg_rewind
+ pg_rewind is a tool for synchronizing a PostgreSQL cluster
+ with another copy of the same cluster, after the clusters' timelines have
+ diverged. A typical scenario is to bring an old primary server back online
+ after failover as a standby that follows the new primary.
+
+ After a successful rewind, the state of the target data directory is
+ analogous to a base backup of the source data directory. Unlike taking
+ a new base backup or using a tool like rsync,
+ pg_rewind does not require comparing or copying
+ unchanged relation blocks in the cluster. Only changed blocks from existing
+ relation files are copied; all other files, including new relation files,
+ configuration files, and WAL segments, are copied in full. As such the
+ rewind operation is significantly faster than other approaches when the
+ database is large and only a small fraction of blocks differ between the
+ clusters.
+
+ pg_rewind examines the timeline histories of the source
+ and target clusters to determine the point where they diverged, and
+ expects to find WAL in the target cluster's pg_wal directory
+ reaching all the way back to the point of divergence. The point of divergence
+ can be found either on the target timeline, the source timeline, or their common
+ ancestor. In the typical failover scenario where the target cluster was
+ shut down soon after the divergence, this is not a problem, but if the
+ target cluster ran for a long time after the divergence, its old WAL
+ files might no longer be present. In this case, you can manually copy them
+ from the WAL archive to the pg_wal directory, or run
+ pg_rewind with the -c option to
+ automatically retrieve them from the WAL archive. The use of
+ pg_rewind is not limited to failover, e.g., a standby
+ server can be promoted, run some write transactions, and then rewound
+ to become a standby again.
+
+ After running pg_rewind, WAL replay needs to
+ complete for the data directory to be in a consistent state. When the
+ target server is started again it will enter archive recovery and replay
+ all WAL generated in the source server from the last checkpoint before
+ the point of divergence. If some of the WAL was no longer available in the
+ source server when pg_rewind was run, and
+ therefore could not be copied by the pg_rewind
+ session, it must be made available when the target server is started.
+ This can be done by creating a recovery.signal file
+ in the target data directory and by configuring a suitable
+ restore_command in
+ postgresql.conf.
+
+ pg_rewind requires that the target server either has
+ the wal_log_hints option enabled
+ in postgresql.conf or data checksums enabled when
+ the cluster was initialized with initdb. Neither of these
+ are currently on by default. full_page_writes
+ must also be set to on, but is enabled by default.
+
Warning: Failures While Rewinding
+ If pg_rewind fails while processing, then
+ the data folder of the target is likely not in a state that can be
+ recovered. In such a case, taking a new fresh backup is recommended.
+
+ As pg_rewind copies configuration files
+ entirely from the source, it may be required to correct the configuration
+ used for recovery before restarting the target server, especially if
+ the target is reintroduced as a standby of the source. If you restart
+ the server after the rewind operation has finished but without configuring
+ recovery, the target may again diverge from the primary.
+
+ pg_rewind will fail immediately if it finds
+ files it cannot write directly to. This can happen for example when
+ the source and the target server use the same file mapping for read-only
+ SSL keys and certificates. If such files are present on the target server
+ it is recommended to remove them before running
+ pg_rewind. After doing the rewind, some of
+ those files may have been copied from the source, in which case it may
+ be necessary to remove the data copied and restore back the set of links
+ used before the rewind.
+
Options
+ pg_rewind accepts the following command-line
+ arguments:
+
+
-D directory --target-pgdata=directory
+ This option specifies the target data directory that is synchronized
+ with the source. The target server must be shut down cleanly before
+ running pg_rewind
+
--source-pgdata=directory
+ Specifies the file system path to the data directory of the source
+ server to synchronize the target with. This option requires the
+ source server to be cleanly shut down.
+
--source-server=connstr
+ Specifies a libpq connection string to connect to the source
+ PostgreSQL server to synchronize the target
+ with. The connection must be a normal (non-replication) connection
+ with a role having sufficient permissions to execute the functions
+ used by pg_rewind on the source server
+ (see Notes section for details) or a superuser role. This option
+ requires the source server to be running and accepting connections.
+
-R --write-recovery-conf
+ Create standby.signal and append connection
+ settings to postgresql.auto.conf in the output
+ directory. --source-server is mandatory with
+ this option.
+
-n --dry-run
+ Do everything except actually modifying the target directory.
+
-N --no-sync
+ By default, pg_rewind will wait for all files
+ to be written safely to disk. This option causes
+ pg_rewind to return without waiting, which is
+ faster, but means that a subsequent operating system crash can leave
+ the data directory corrupt. Generally, this option is useful for
+ testing but should not be used on a production
+ installation.
+
-P --progress
+ Enables progress reporting. Turning this on will deliver an approximate
+ progress report while copying data from the source cluster.
+
-c --restore-target-wal
+ Use restore_command defined in the target cluster
+ configuration to retrieve WAL files from the WAL archive if these
+ files are no longer available in the pg_wal
+ directory.
+
--config-file=filename
+ Use the specified main server configuration file for the target
+ cluster. This affects pg_rewind when
+ it uses internally the postgres command
+ for the rewind operation on this cluster (when retrieving
+ restore_command with the option
+ -c/--restore-target-wal and when forcing a
+ completion of crash recovery).
+
--debug
+ Print verbose debugging output that is mostly useful for developers
+ debugging pg_rewind.
+
--no-ensure-shutdown
+ pg_rewind requires that the target server
+ is cleanly shut down before rewinding. By default, if the target server
+ is not shut down cleanly, pg_rewind starts
+ the target server in single-user mode to complete crash recovery first,
+ and stops it.
+ By passing this option, pg_rewind skips
+ this and errors out immediately if the server is not cleanly shut
+ down. Users are expected to handle the situation themselves in that
+ case.
+
-V --version
Display version information, then exit.
-? --help
Show help, then exit.
+
Environment
+ When --source-server option is used,
+ pg_rewind also uses the environment variables
+ supported by libpq (see Section 34.15).
+
+ The environment variable PG_COLOR specifies whether to use
+ color in diagnostic messages. Possible values are
+ always, auto and
+ never.
+
Notes
+ When executing pg_rewind using an online
+ cluster as source, a role having sufficient permissions to execute the
+ functions used by pg_rewind on the source
+ cluster can be used instead of a superuser. Here is how to create such
+ a role, named rewind_user here:
+
+CREATE USER rewind_user LOGIN;
+GRANT EXECUTE ON function pg_catalog.pg_ls_dir(text, boolean, boolean) TO rewind_user;
+GRANT EXECUTE ON function pg_catalog.pg_stat_file(text, boolean) TO rewind_user;
+GRANT EXECUTE ON function pg_catalog.pg_read_binary_file(text) TO rewind_user;
+GRANT EXECUTE ON function pg_catalog.pg_read_binary_file(text, bigint, bigint, boolean) TO rewind_user;
+
+
How It Works
+ The basic idea is to copy all file system-level changes from the source
+ cluster to the target cluster:
+
+ Scan the WAL log of the target cluster, starting from the last
+ checkpoint before the point where the source cluster's timeline
+ history forked off from the target cluster. For each WAL record,
+ record each data block that was touched. This yields a list of all
+ the data blocks that were changed in the target cluster, after the
+ source cluster forked off. If some of the WAL files are no longer
+ available, try re-running pg_rewind with
+ the -c option to search for the missing files in
+ the WAL archive.
+
+ Copy all those changed blocks from the source cluster to
+ the target cluster, either using direct file system access
+ (--source-pgdata) or SQL (--source-server).
+ Relation files are now in a state equivalent to the moment of the last
+ completed checkpoint prior to the point at which the WAL timelines of the
+ source and target diverged plus the current state on the source of any
+ blocks changed on the target after that divergence.
+
+ Copy all other files, including new relation files, WAL segments,
+ pg_xact, and configuration files from the source
+ cluster to the target cluster. Similarly to base backups, the contents
+ of the directories pg_dynshmem/,
+ pg_notify/, pg_replslot/,
+ pg_serial/, pg_snapshots/,
+ pg_stat_tmp/, and pg_subtrans/
+ are omitted from the data copied from the source cluster. The files
+ backup_label,
+ tablespace_map,
+ pg_internal.init,
+ postmaster.opts,
+ postmaster.pid and
+ .DS_Store as well as any file or directory
+ beginning with pgsql_tmp, are omitted.
+
+ Create a backup_label file to begin WAL replay at
+ the checkpoint created at failover and configure the
+ pg_control file with a minimum consistency LSN
+ defined as the result of pg_current_wal_insert_lsn()
+ when rewinding from a live source or the last checkpoint LSN when
+ rewinding from a stopped source.
+
+ When starting the target, PostgreSQL replays
+ all the required WAL, resulting in a data directory in a consistent
+ state.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-pgverifybackup.html b/pgsql/doc/postgresql/html/app-pgverifybackup.html
new file mode 100644
index 0000000000000000000000000000000000000000..4d5d149307b54df598d4194e4de6b2302f2c1634
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-pgverifybackup.html
@@ -0,0 +1,150 @@
+
+pg_verifybackup
pg_verifybackup — verify the integrity of a base backup of a
+ PostgreSQL cluster
Synopsis
pg_verifybackup [option...]
Description
+ pg_verifybackup is used to check the
+ integrity of a database cluster backup taken using
+ pg_basebackup against a
+ backup_manifest generated by the server at the time
+ of the backup. The backup must be stored in the "plain"
+ format; a "tar" format backup can be checked after extracting it.
+
+ It is important to note that the validation which is performed by
+ pg_verifybackup does not and cannot include
+ every check which will be performed by a running server when attempting
+ to make use of the backup. Even if you use this tool, you should still
+ perform test restores and verify that the resulting databases work as
+ expected and that they appear to contain the correct data. However,
+ pg_verifybackup can detect many problems
+ that commonly occur due to storage problems or user error.
+
+ Backup verification proceeds in four stages. First,
+ pg_verifybackup reads the
+ backup_manifest file. If that file
+ does not exist, cannot be read, is malformed, or fails verification
+ against its own internal checksum, pg_verifybackup
+ will terminate with a fatal error.
+
+ Second, pg_verifybackup will attempt to verify that
+ the data files currently stored on disk are exactly the same as the data
+ files which the server intended to send, with some exceptions that are
+ described below. Extra and missing files will be detected, with a few
+ exceptions. This step will ignore the presence or absence of, or any
+ modifications to, postgresql.auto.conf,
+ standby.signal, and recovery.signal,
+ because it is expected that these files may have been created or modified
+ as part of the process of taking the backup. It also won't complain about
+ a backup_manifest file in the target directory or
+ about anything inside pg_wal, even though these
+ files won't be listed in the backup manifest. Only files are checked;
+ the presence or absence of directories is not verified, except
+ indirectly: if a directory is missing, any files it should have contained
+ will necessarily also be missing.
+
+ Next, pg_verifybackup will checksum all the files,
+ compare the checksums against the values in the manifest, and emit errors
+ for any files for which the computed checksum does not match the
+ checksum stored in the manifest. This step is not performed for any files
+ which produced errors in the previous step, since they are already known
+ to have problems. Files which were ignored in the previous step are also
+ ignored in this step.
+
+ Finally, pg_verifybackup will use the manifest to
+ verify that the write-ahead log records which will be needed to recover
+ the backup are present and that they can be read and parsed. The
+ backup_manifest contains information about which
+ write-ahead log records will be needed, and
+ pg_verifybackup will use that information to
+ invoke pg_waldump to parse those write-ahead log
+ records. The --quiet flag will be used, so that
+ pg_waldump will only report errors, without producing
+ any other output. While this level of verification is sufficient to
+ detect obvious problems such as a missing file or one whose internal
+ checksums do not match, they aren't extensive enough to detect every
+ possible problem that might occur when attempting to recover. For
+ instance, a server bug that produces write-ahead log records that have
+ the correct checksums but specify nonsensical actions can't be detected
+ by this method.
+
+ Note that if extra WAL files which are not required to recover the backup
+ are present, they will not be checked by this tool, although
+ a separate invocation of pg_waldump could be used for
+ that purpose. Also note that WAL verification is version-specific: you
+ must use the version of pg_verifybackup, and thus of
+ pg_waldump, which pertains to the backup being checked.
+ In contrast, the data file integrity checks should work with any version
+ of the server that generates a backup_manifest file.
+
Options
+ pg_verifybackup accepts the following
+ command-line arguments:
+
+
-e --exit-on-error
+ Exit as soon as a problem with the backup is detected. If this option
+ is not specified, pg_verifybackup will continue
+ checking the backup even after a problem has been detected, and will
+ report all problems detected as errors.
+
-i path --ignore=path
+ Ignore the specified file or directory, which should be expressed
+ as a relative path name, when comparing the list of data files
+ actually present in the backup to those listed in the
+ backup_manifest file. If a directory is
+ specified, this option affects the entire subtree rooted at that
+ location. Complaints about extra files, missing files, file size
+ differences, or checksum mismatches will be suppressed if the
+ relative path name matches the specified path name. This option
+ can be specified multiple times.
+
-m path --manifest-path=path
+ Use the manifest file at the specified path, rather than one located
+ in the root of the backup directory.
+
-n --no-parse-wal
+ Don't attempt to parse write-ahead log data that will be needed
+ to recover from this backup.
+
-P --progress
+ Enable progress reporting. Turning this on will deliver a progress
+ report while verifying checksums.
+
+ This option cannot be used together with the option
+ --quiet.
+
-q --quiet
+ Don't print anything when a backup is successfully verified.
+
-s --skip-checksums
+ Do not verify data file checksums. The presence or absence of
+ files and the sizes of those files will still be checked. This is
+ much faster, because the files themselves do not need to be read.
+
-w path --wal-directory=path
+ Try to parse WAL files stored in the specified directory, rather than
+ in pg_wal. This may be useful if the backup is
+ stored in a separate location from the WAL archive.
+
+
+ Other options are also available:
+
+
-V --version
+ Print the pg_verifybackup version and exit.
+
-? --help
+ Show help about pg_verifybackup command
+ line arguments, and exit.
+
+
Examples
+ To create a base backup of the server at mydbserver and
+ verify the integrity of the backup:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-postgres.html b/pgsql/doc/postgresql/html/app-postgres.html
new file mode 100644
index 0000000000000000000000000000000000000000..c0e137d895fd14900ec0ad7a4ca344ad0adb2fd0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-postgres.html
@@ -0,0 +1,416 @@
+
+postgres
+ postgres is the
+ PostgreSQL database server. In order
+ for a client application to access a database it connects (over a
+ network or locally) to a running postgres instance.
+ The postgres instance then starts a separate server
+ process to handle the connection.
+
+ One postgres instance always manages the data of
+ exactly one database cluster. A database cluster is a collection
+ of databases that is stored at a common file system location (the
+ “data area”). More than one
+ postgres instance can run on a system at one
+ time, so long as they use different data areas and different
+ communication ports (see below). When
+ postgres starts it needs to know the location
+ of the data area. The location must be specified by the
+ -D option or the PGDATA environment
+ variable; there is no default. Typically, -D or
+ PGDATA points directly to the data area directory
+ created by initdb. Other possible file layouts are
+ discussed in Section 20.2.
+
+ By default postgres starts in the
+ foreground and prints log messages to the standard error stream. In
+ practical applications postgres
+ should be started as a background process, perhaps at boot time.
+
+ The postgres command can also be called in
+ single-user mode. The primary use for this mode is during
+ bootstrapping by initdb. Sometimes it is used
+ for debugging or disaster recovery; note that running a single-user
+ server is not truly suitable for debugging the server, since no
+ realistic interprocess communication and locking will happen.
+ When invoked in single-user
+ mode from the shell, the user can enter queries and the results
+ will be printed to the screen, but in a form that is more useful
+ for developers than end users. In the single-user mode,
+ the session user will be set to the user with ID 1, and implicit
+ superuser powers are granted to this user.
+ This user does not actually have to exist, so the single-user mode
+ can be used to manually recover from certain
+ kinds of accidental damage to the system catalogs.
+
Options
+ postgres accepts the following command-line
+ arguments. For a detailed discussion of the options consult Chapter 20. You can save typing most of these
+ options by setting up a configuration file. Some (safe) options
+ can also be set from the connecting client in an
+ application-dependent way to apply only for that session. For
+ example, if the environment variable PGOPTIONS is
+ set, then libpq-based clients will pass that
+ string to the server, which will interpret it as
+ postgres command-line options.
+
General Purpose
-B nbuffers
+ Sets the number of shared buffers for use by the server
+ processes. The default value of this parameter is chosen
+ automatically by initdb.
+ Specifying this option is equivalent to setting the
+ shared_buffers configuration parameter.
+
-c name=value
+ Sets a named run-time parameter. The configuration parameters
+ supported by PostgreSQL are
+ described in Chapter 20. Most of the
+ other command line options are in fact short forms of such a
+ parameter assignment. -c can appear multiple times
+ to set multiple parameters.
+
-C name
+ Prints the value of the named run-time parameter, and exits.
+ (See the -c option above for details.) This
+ returns values from
+ postgresql.conf, modified by any parameters
+ supplied in this invocation. It does not reflect parameters
+ supplied when the cluster was started.
+
+ This option is meant for other programs that interact with a server
+ instance, such as pg_ctl, to query configuration
+ parameter values. User-facing applications should instead use SHOW or the pg_settings view.
+
-d debug-level
+ Sets the debug level. The higher this value is set, the more
+ debugging output is written to the server log. Values are
+ from 1 to 5. It is also possible to pass -d
+ 0 for a specific session, which will prevent the
+ server log level of the parent postgres process from being
+ propagated to this session.
+
-D datadir
+ Specifies the file system location of the database
+ configuration files. See
+ Section 20.2 for details.
+
-e
+ Sets the default date style to “European”, that is
+ DMY ordering of input date fields. This also causes
+ the day to be printed before the month in certain date output formats.
+ See Section 8.5 for more information.
+
-F
+ Disables fsync calls for improved
+ performance, at the risk of data corruption in the event of a
+ system crash. Specifying this option is equivalent to
+ disabling the fsync configuration
+ parameter. Read the detailed documentation before using this!
+
-h hostname
+ Specifies the IP host name or address on which
+ postgres is to listen for TCP/IP
+ connections from client applications. The value can also be a
+ comma-separated list of addresses, or * to specify
+ listening on all available interfaces. An empty value
+ specifies not listening on any IP addresses, in which case
+ only Unix-domain sockets can be used to connect to the
+ server. Defaults to listening only on
+ localhost.
+ Specifying this option is equivalent to setting the listen_addresses configuration parameter.
+
-i
+ Allows remote clients to connect via TCP/IP (Internet domain)
+ connections. Without this option, only local connections are
+ accepted. This option is equivalent to setting
+ listen_addresses to * in
+ postgresql.conf or via -h.
+
+ This option is deprecated since it does not allow access to the
+ full functionality of listen_addresses.
+ It's usually better to set listen_addresses directly.
+
-k directory
+ Specifies the directory of the Unix-domain socket on which
+ postgres is to listen for
+ connections from client applications. The value can also be a
+ comma-separated list of directories. An empty value
+ specifies not listening on any Unix-domain sockets, in which case
+ only TCP/IP sockets can be used to connect to the server.
+ The default value is normally
+ /tmp, but that can be changed at build time.
+ Specifying this option is equivalent to setting the unix_socket_directories configuration parameter.
+
-l
+ Enables secure connections using SSL.
+ PostgreSQL must have been compiled with
+ support for SSL for this option to be
+ available. For more information on using SSL,
+ refer to Section 19.9.
+
-N max-connections
+ Sets the maximum number of client connections that this
+ server will accept. The default value of this parameter is chosen
+ automatically by initdb.
+ Specifying this option is equivalent to setting the
+ max_connections configuration parameter.
+
-p port
+ Specifies the TCP/IP port or local Unix domain socket file
+ extension on which postgres
+ is to listen for connections from client applications.
+ Defaults to the value of the PGPORT environment
+ variable, or if PGPORT is not set, then
+ defaults to the value established during compilation (normally
+ 5432). If you specify a port other than the default port,
+ then all client applications must specify the same port using
+ either command-line options or PGPORT.
+
-s
+ Print time information and other statistics at the end of each command.
+ This is useful for benchmarking or for use in tuning the number of
+ buffers.
+
-Swork-mem
+ Specifies the base amount of memory to be used by sorts and
+ hash tables before resorting to temporary disk files. See the
+ description of the work_mem configuration
+ parameter in Section 20.4.1.
+
-V --version
+ Print the postgres version and exit.
+
--name=value
+ Sets a named run-time parameter; a shorter form of
+ -c.
+
--describe-config
+ This option dumps out the server's internal configuration variables,
+ descriptions, and defaults in tab-delimited COPY format.
+ It is designed primarily for use by administration tools.
+
-? --help
+ Show help about postgres command line
+ arguments, and exit.
+
Semi-Internal Options
+ The options described here are used
+ mainly for debugging purposes, and in some cases to assist with
+ recovery of severely damaged databases. There should be no reason
+ to use them in a production database setup. They are listed
+ here only for use by PostgreSQL
+ system developers. Furthermore, these options might
+ change or be removed in a future release without notice.
+
-f{ s | i | o | b | t | n | m | h }
+ Forbids the use of particular scan and join methods:
+ s and i
+ disable sequential and index scans respectively,
+ o, b and t
+ disable index-only scans, bitmap index scans, and TID scans
+ respectively, while
+ n, m, and h
+ disable nested-loop, merge and hash joins respectively.
+
+ Neither sequential scans nor nested-loop joins can be disabled
+ completely; the -fs and
+ -fn options simply discourage the optimizer
+ from using those plan types if it has any other alternative.
+
-O
+ Allows the structure of system tables to be modified. This is
+ used by initdb.
+
-P
+ Ignore system indexes when reading system tables, but still update
+ the indexes when modifying the tables. This is useful when
+ recovering from damaged system indexes.
+
-tpa[rser] | pl[anner] | e[xecutor]
+ Print timing statistics for each query relating to each of the
+ major system modules. This option cannot be used together
+ with the -s option.
+
-T
+ This option is for debugging problems that cause a server
+ process to die abnormally. The ordinary strategy in this
+ situation is to notify all other server processes that they
+ must terminate, by sending them SIGQUIT
+ signals. With this option, SIGABRT
+ will be sent instead, resulting in production of core dump files.
+
-vprotocol
+ Specifies the version number of the frontend/backend protocol
+ to be used for a particular session. This option is for
+ internal use only.
+
-Wseconds
+ A delay of this many seconds occurs when a new server process
+ is started, after it conducts the authentication procedure.
+ This is intended to give an opportunity to attach to the
+ server process with a debugger.
+
Options for Single-User Mode
+ The following options only apply to the single-user mode
+ (see Single-User Mode below).
+
--single
+ Selects the single-user mode. This must be the first argument
+ on the command line.
+
database
+ Specifies the name of the database to be accessed. This must be
+ the last argument on the command line. If it is
+ omitted it defaults to the user name.
+
-E
+ Echo all commands to standard output before executing them.
+
-j
+ Use semicolon followed by two newlines, rather than just newline,
+ as the command entry terminator.
+
-rfilename
+ Send all server log output to filename. This option is only
+ honored when supplied as a command-line option.
+
Environment
PGCLIENTENCODING
+ Default character encoding used by clients. (The clients can
+ override this individually.) This value can also be set in the
+ configuration file.
+
PGDATA
+ Default data directory location
+
PGDATESTYLE
+ Default value of the DateStyle run-time
+ parameter. (The use of this environment variable is deprecated.)
+
PGPORT
+ Default port number (preferably set in the configuration file)
+
Diagnostics
+ A failure message mentioning semget or
+ shmget probably indicates you need to configure your
+ kernel to provide adequate shared memory and semaphores. For more
+ discussion see Section 19.4. You might be able
+ to postpone reconfiguring your kernel by decreasing shared_buffers to reduce the shared memory
+ consumption of PostgreSQL, and/or by reducing
+ max_connections to reduce the semaphore
+ consumption.
+
+ A failure message suggesting that another server is already running
+ should be checked carefully, for example by using the command
+
+$ps ax | grep postgres
+
+ or
+
+$ps -ef | grep postgres
+
+ depending on your system. If you are certain that no conflicting
+ server is running, you can remove the lock file mentioned in the
+ message and try again.
+
+ A failure message indicating inability to bind to a port might
+ indicate that that port is already in use by some
+ non-PostgreSQL process. You might also
+ get this error if you terminate postgres
+ and immediately restart it using the same port; in this case, you
+ must simply wait a few seconds until the operating system closes
+ the port before trying again. Finally, you might get this error if
+ you specify a port number that your operating system considers to
+ be reserved. For example, many versions of Unix consider port
+ numbers under 1024 to be “trusted” and only permit
+ the Unix superuser to access them.
+
Notes
+ The utility command pg_ctl can be used to
+ start and shut down the postgres server
+ safely and comfortably.
+
+ If at all possible, do not use
+ SIGKILL to kill the main
+ postgres server. Doing so will prevent
+ postgres from freeing the system
+ resources (e.g., shared memory and semaphores) that it holds before
+ terminating. This might cause problems for starting a fresh
+ postgres run.
+
+ To terminate the postgres server normally, the
+ signals SIGTERM, SIGINT, or
+ SIGQUIT can be used. The first will wait for
+ all clients to terminate before quitting, the second will
+ forcefully disconnect all clients, and the third will quit
+ immediately without proper shutdown, resulting in a recovery run
+ during restart.
+
+ The SIGHUP signal will reload
+ the server configuration files. It is also possible to send
+ SIGHUP to an individual server process, but that
+ is usually not sensible.
+
+ To cancel a running query, send the SIGINT signal
+ to the process running that command. To terminate a backend process
+ cleanly, send SIGTERM to that process. See
+ also pg_cancel_backend and pg_terminate_backend
+ in Section 9.27.2 for the SQL-callable equivalents
+ of these two actions.
+
+ The postgres server uses SIGQUIT
+ to tell subordinate server processes to terminate without normal
+ cleanup.
+ This signal should not be used by users. It
+ is also unwise to send SIGKILL to a server
+ process — the main postgres process will
+ interpret this as a crash and will force all the sibling processes
+ to quit as part of its standard crash-recovery procedure.
+
Bugs
+ The -- options will not work on FreeBSD or OpenBSD.
+ Use -c instead. This is a bug in the affected operating
+ systems; a future release of PostgreSQL
+ will provide a workaround if this is not fixed.
+
Single-User Mode
+ To start a single-user mode server, use a command like
+
+ Provide the correct path to the database directory with -D, or
+ make sure that the environment variable PGDATA is set.
+ Also specify the name of the particular database you want to work in.
+
+ Normally, the single-user mode server treats newline as the command
+ entry terminator; there is no intelligence about semicolons,
+ as there is in psql. To continue a command
+ across multiple lines, you must type backslash just before each
+ newline except the last one. The backslash and adjacent newline are
+ both dropped from the input command. Note that this will happen even
+ when within a string literal or comment.
+
+ But if you use the -j command line switch, a single newline
+ does not terminate command entry; instead, the sequence
+ semicolon-newline-newline does. That is, type a semicolon immediately
+ followed by a completely empty line. Backslash-newline is not
+ treated specially in this mode. Again, there is no intelligence about
+ such a sequence appearing within a string literal or comment.
+
+ In either input mode, if you type a semicolon that is not just before or
+ part of a command entry terminator, it is considered a command separator.
+ When you do type a command entry terminator, the multiple statements
+ you've entered will be executed as a single transaction.
+
+ To quit the session, type EOF
+ (Control+D, usually).
+ If you've entered any text since the last command entry terminator,
+ then EOF will be taken as a command entry terminator,
+ and another EOF will be needed to exit.
+
+ Note that the single-user mode server does not provide sophisticated
+ line-editing features (no command history, for example).
+ Single-user mode also does not do any background processing, such as
+ automatic checkpoints or replication.
+
Examples
+ To start postgres in the background
+ using default values, type:
+
+
+$nohup postgres >logfile 2>&1 </dev/null &
+
+
+ To start postgres with a specific
+ port, e.g., 1234:
+
+$postgres -p 1234
+
+ To connect to this server using psql, specify this port with the -p option:
+
+$psql -p 1234
+
+ or set the environment variable PGPORT:
+
+$export PGPORT=1234
+$psql
+
+
+ Named run-time parameters can be set in either of these styles:
+
+ Either form overrides whatever setting might exist for
+ work_mem in postgresql.conf. Notice that
+ underscores in parameter names can be written as either underscore
+ or dash on the command line. Except for short-term experiments,
+ it's probably better practice to edit the setting in
+ postgresql.conf than to rely on a command-line switch
+ to set a parameter.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-psql.html b/pgsql/doc/postgresql/html/app-psql.html
new file mode 100644
index 0000000000000000000000000000000000000000..4aa12347ed285e801c32553f932c8a5b104979ac
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-psql.html
@@ -0,0 +1,3042 @@
+
+psql
+ psql is a terminal-based front-end to
+ PostgreSQL. It enables you to type in
+ queries interactively, issue them to
+ PostgreSQL, and see the query results.
+ Alternatively, input can be from a file or from command line
+ arguments. In addition, psql provides a
+ number of meta-commands and various shell-like features to
+ facilitate writing scripts and automating a wide variety of tasks.
+
+ Print all nonempty input lines to standard output as they are read.
+ (This does not apply to lines read interactively.) This is
+ equivalent to setting the variable ECHO to
+ all.
+
+ Specifies that psql is to execute the given
+ command string, command.
+ This option can be repeated and combined in any order with
+ the -f option. When either -c
+ or -f is specified, psql
+ does not read commands from standard input; instead it terminates
+ after processing all the -c and -f
+ options in sequence.
+
+ command must be either
+ a command string that is completely parsable by the server (i.e.,
+ it contains no psql-specific features),
+ or a single backslash command. Thus you cannot mix
+ SQL and psql
+ meta-commands within a -c option. To achieve that,
+ you could use repeated -c options or pipe the string
+ into psql, for example:
+
+psql -c '\x' -c 'SELECT * FROM foo;'
+
+ or
+
+echo '\x \\ SELECT * FROM foo;' | psql
+
+ (\\ is the separator meta-command.)
+
+ Each SQL command string passed
+ to -c is sent to the server as a single request.
+ Because of this, the server executes it as a single transaction even
+ if the string contains multiple SQL commands,
+ unless there are explicit BEGIN/COMMIT
+ commands included in the string to divide it into multiple
+ transactions. (See Section 55.2.2.1
+ for more details about how the server handles multi-query strings.)
+
+ If having several commands executed in one transaction is not desired,
+ use repeated -c commands or feed multiple commands to
+ psql's standard input,
+ either using echo as illustrated above, or
+ via a shell here-document, for example:
+
+ Specifies the name of the database to connect to. This is
+ equivalent to specifying dbname as the first non-option
+ argument on the command line. The dbname
+ can be a connection string.
+ If so, connection string parameters will override any conflicting
+ command line options.
+
+ Echo the actual queries generated by \d and other backslash
+ commands. You can use this to study psql's
+ internal operations. This is equivalent to
+ setting the variable ECHO_HIDDEN to on.
+
+ Read commands from the
+ file filename,
+ rather than standard input.
+ This option can be repeated and combined in any order with
+ the -c option. When either -c
+ or -f is specified, psql
+ does not read commands from standard input; instead it terminates
+ after processing all the -c and -f
+ options in sequence.
+ Except for that, this option is largely equivalent to the
+ meta-command \i.
+
+ If filename is -
+ (hyphen), then standard input is read until an EOF indication
+ or \q meta-command. This can be used to intersperse
+ interactive input with input from files. Note however that Readline
+ is not used in this case (much as if -n had been
+ specified).
+
+ Using this option is subtly different from writing psql
+ < filename. In general,
+ both will do what you expect, but using -f
+ enables some nice features such as error messages with line
+ numbers. There is also a slight chance that using this option will
+ reduce the start-up overhead. On the other hand, the variant using
+ the shell's input redirection is (in theory) guaranteed to yield
+ exactly the same output you would have received had you entered
+ everything by hand.
+
+ Specifies the host name of the machine on which the
+ server is running. If the value begins
+ with a slash, it is used as the directory for the Unix-domain
+ socket.
+
+ List all available databases, then exit. Other non-connection
+ options are ignored. This is similar to the meta-command
+ \list.
+
+ When this option is used, psql will connect
+ to the database postgres, unless a different database
+ is named on the command line (option -d or non-option
+ argument, possibly via a service entry, but not via an environment
+ variable).
+
+ Specifies the TCP port or the local Unix-domain
+ socket file extension on which the server is listening for
+ connections. Defaults to the value of the PGPORT
+ environment variable or, if not set, to the port specified at
+ compile time, usually 5432.
+
+ Specifies printing options, in the style of
+ \pset. Note that here you
+ have to separate name and value with an equal sign instead of a
+ space. For example, to set the output format to LaTeX, you could write
+ -P format=latex.
+
+ Specifies that psql should do its work
+ quietly. By default, it prints welcome messages and various
+ informational output. If this option is used, none of this
+ happens. This is useful with the -c option.
+ This is equivalent to setting the variable QUIET
+ to on.
+
+ Run in single-step mode. That means the user is prompted before
+ each command is sent to the server, with the option to cancel
+ execution as well. Use this to debug scripts.
+
+ Runs in single-line mode where a newline terminates an SQL command, as a
+ semicolon does.
+
Note
+ This mode is provided for those who insist on it, but you are not
+ necessarily encouraged to use it. In particular, if you mix
+ SQL and meta-commands on a line the order of
+ execution might not always be clear to the inexperienced user.
+
+ Perform a variable assignment, like the \set
+ meta-command. Note that you must separate name and value, if
+ any, by an equal sign on the command line. To unset a variable,
+ leave off the equal sign. To set a variable with an empty value,
+ use the equal sign but leave off the value. These assignments are
+ done during command line processing, so variables that reflect
+ connection state will get overwritten later.
+
+ Never issue a password prompt. If the server requires password
+ authentication and a password is not available from other sources
+ such as a .pgpass file, the connection
+ attempt will fail. This option can be useful in batch jobs and
+ scripts where no user is present to enter a password.
+
+ Note that this option will remain set for the entire session,
+ and so it affects uses of the meta-command
+ \connect as well as the initial connection attempt.
+
+ Force psql to prompt for a
+ password before connecting to a database, even if the password will
+ not be used.
+
+ If the server requires password authentication and a password is not
+ available from other sources such as a .pgpass
+ file, psql will prompt for a
+ password in any case. However, psql
+ will waste a connection attempt finding out that the server wants a
+ password. In some cases it is worth typing -W to avoid
+ the extra connection attempt.
+
+ Note that this option will remain set for the entire session,
+ and so it affects uses of the meta-command
+ \connect as well as the initial connection attempt.
+
+ Set the record separator for unaligned output to a zero byte. This is
+ useful for interfacing, for example, with xargs -0.
+ This is equivalent to \pset recordsep_zero.
+
+ This option can only be used in combination with one or more
+ -c and/or -f options. It causes
+ psql to issue a BEGIN command
+ before the first such option and a COMMIT command after
+ the last one, thereby wrapping all the commands into a single
+ transaction. If any of the commands fails and the variable
+ ON_ERROR_STOP was set, a
+ ROLLBACK command is sent instead. This ensures that
+ either all the commands complete successfully, or no changes are
+ applied.
+
+ If the commands themselves
+ contain BEGIN, COMMIT,
+ or ROLLBACK, this option will not have the desired
+ effects. Also, if an individual command cannot be executed inside a
+ transaction block, specifying this option will cause the whole
+ transaction to fail.
+
+ Show help about psql and exit. The optional
+ topic parameter (defaulting
+ to options) selects which part of psql is
+ explained: commands describes psql's
+ backslash commands; options describes the command-line
+ options that can be passed to psql;
+ and variables shows help about psql configuration
+ variables.
+
Exit Status
+ psql returns 0 to the shell if it
+ finished normally, 1 if a fatal error of its own occurs (e.g., out of memory,
+ file not found), 2 if the connection to the server went bad
+ and the session was not interactive, and 3 if an error occurred in a
+ script and the variable ON_ERROR_STOP was set.
+
Usage
Connecting to a Database
+ psql is a regular
+ PostgreSQL client application. In order
+ to connect to a database you need to know the name of your target
+ database, the host name and port number of the server, and what
+ database user name you want to connect as. psql
+ can be told about those parameters via command line options, namely
+ -d, -h, -p, and
+ -U respectively. If an argument is found that does
+ not belong to any option it will be interpreted as the database name
+ (or the database user name, if the database name is already given). Not all
+ of these options are required; there are useful defaults. If you omit the host
+ name, psql will connect via a Unix-domain socket
+ to a server on the local host, or via TCP/IP to localhost on
+ Windows. The default port number is
+ determined at compile time.
+ Since the database server uses the same default, you will not have
+ to specify the port in most cases. The default database user name is your
+ operating-system user name. Once the database user name is determined, it
+ is used as the default database name.
+ Note that you cannot
+ just connect to any database under any database user name. Your database
+ administrator should have informed you about your access rights.
+
+ When the defaults aren't quite right, you can save yourself
+ some typing by setting the environment variables
+ PGDATABASE, PGHOST,
+ PGPORT and/or PGUSER to appropriate
+ values. (For additional environment variables, see Section 34.15.) It is also convenient to have a
+ ~/.pgpass file to avoid regularly having to type in
+ passwords. See Section 34.16 for more information.
+
+ An alternative way to specify connection parameters is in a
+ conninfo string or
+ a URI, which is used instead of a database
+ name. This mechanism give you very wide control over the
+ connection. For example:
+
+ This way you can also use LDAP for connection
+ parameter lookup as described in Section 34.18.
+ See Section 34.1.2 for more information on all the
+ available connection options.
+
+ If the connection could not be made for any reason (e.g., insufficient
+ privileges, server is not running on the targeted host, etc.),
+ psql will return an error and terminate.
+
+ If both standard input and standard output are a
+ terminal, then psql sets the client
+ encoding to “auto”, which will detect the
+ appropriate client encoding from the locale settings
+ (LC_CTYPE environment variable on Unix systems).
+ If this doesn't work out as expected, the client encoding can be
+ overridden using the environment
+ variable PGCLIENTENCODING.
+
Entering SQL Commands
+ In normal operation, psql provides a
+ prompt with the name of the database to which
+ psql is currently connected, followed by
+ the string =>. For example:
+
+ At the prompt, the user can type in SQL commands.
+ Ordinarily, input lines are sent to the server when a
+ command-terminating semicolon is reached. An end of line does not
+ terminate a command. Thus commands can be spread over several lines for
+ clarity. If the command was sent and executed without error, the results
+ of the command are displayed on the screen.
+
+ If untrusted users have access to a database that has not adopted a
+ secure schema usage pattern,
+ begin your session by removing publicly-writable schemas
+ from search_path. One can
+ add options=-csearch_path= to the connection string or
+ issue SELECT pg_catalog.set_config('search_path', '',
+ false) before other SQL commands. This consideration is not
+ specific to psql; it applies to every interface
+ for executing arbitrary SQL commands.
+
+ Whenever a command is executed, psql also polls
+ for asynchronous notification events generated by
+ LISTEN and
+ NOTIFY.
+
+ While C-style block comments are passed to the server for
+ processing and removal, SQL-standard comments are removed by
+ psql.
+
Meta-Commands
+ Anything you enter in psql that begins
+ with an unquoted backslash is a psql
+ meta-command that is processed by psql
+ itself. These commands make
+ psql more useful for administration or
+ scripting. Meta-commands are often called slash or backslash commands.
+
+ The format of a psql command is the backslash,
+ followed immediately by a command verb, then any arguments. The arguments
+ are separated from the command verb and each other by any number of
+ whitespace characters.
+
+ To include whitespace in an argument you can quote it with
+ single quotes. To include a single quote in an argument,
+ write two single quotes within single-quoted text.
+ Anything contained in single quotes is
+ furthermore subject to C-like substitutions for
+ \n (new line), \t (tab),
+ \b (backspace), \r (carriage return),
+ \f (form feed),
+ \digits (octal), and
+ \xdigits (hexadecimal).
+ A backslash preceding any other character within single-quoted text
+ quotes that single character, whatever it is.
+
+ If an unquoted colon (:) followed by a
+ psql variable name appears within an argument, it is
+ replaced by the variable's value, as described in SQL Interpolation below.
+ The forms :'variable_name' and
+ :"variable_name" described there
+ work as well.
+ The :{?variable_name} syntax allows
+ testing whether a variable is defined. It is substituted by
+ TRUE or FALSE.
+ Escaping the colon with a backslash protects it from substitution.
+
+ Within an argument, text that is enclosed in backquotes
+ (`) is taken as a command line that is passed to the
+ shell. The output of the command (with any trailing newline removed)
+ replaces the backquoted text. Within the text enclosed in backquotes,
+ no special quoting or other processing occurs, except that appearances
+ of :variable_name where
+ variable_name is a psql variable name
+ are replaced by the variable's value. Also, appearances of
+ :'variable_name' are replaced by the
+ variable's value suitably quoted to become a single shell command
+ argument. (The latter form is almost always preferable, unless you are
+ very sure of what is in the variable.) Because carriage return and line
+ feed characters cannot be safely quoted on all platforms, the
+ :'variable_name' form prints an
+ error message and does not substitute the variable value when such
+ characters appear in the value.
+
+ Some commands take an SQL identifier (such as a
+ table name) as argument. These arguments follow the syntax rules
+ of SQL: Unquoted letters are forced to
+ lowercase, while double quotes (") protect letters
+ from case conversion and allow incorporation of whitespace into
+ the identifier. Within double quotes, paired double quotes reduce
+ to a single double quote in the resulting name. For example,
+ FOO"BAR"BAZ is interpreted as fooBARbaz,
+ and "A weird"" name" becomes A weird"
+ name.
+
+ Parsing for arguments stops at the end of the line, or when another
+ unquoted backslash is found. An unquoted backslash
+ is taken as the beginning of a new meta-command. The special
+ sequence \\ (two backslashes) marks the end of
+ arguments and continues parsing SQL commands, if
+ any. That way SQL and
+ psql commands can be freely mixed on a
+ line. But in any case, the arguments of a meta-command cannot
+ continue beyond the end of the line.
+
+ Many of the meta-commands act on the current query buffer.
+ This is simply a buffer holding whatever SQL command text has been typed
+ but not yet sent to the server for execution. This will include previous
+ input lines as well as any text appearing before the meta-command on the
+ same line.
+
+ If the current table output format is unaligned, it is switched to aligned.
+ If it is not unaligned, it is set to unaligned. This command is
+ kept for backwards compatibility. See \pset for a
+ more general solution.
+
+ This also works for query-execution commands besides
+ \g, such as \gx and
+ \gset.
+
+ This command causes the extended query protocol (see Section 55.1.2) to be used, unlike normal
+ psql operation, which uses the simple
+ query protocol. So this command can be useful to test the extended
+ query protocol from psql. (The extended query protocol is used even
+ if the query has no parameters and this command specifies zero
+ parameters.) This command affects only the next query executed; all
+ subsequent queries will use the simple query protocol by default.
+
\c or \connect [ -reuse-previous=on|off ] [ dbname [ username ] [ host ] [ port ] | conninfo ]#
+ Establishes a new connection to a PostgreSQL
+ server. The connection parameters to use can be specified either
+ using a positional syntax (one or more of database name, user,
+ host, and port), or using a conninfo
+ connection string as detailed in
+ Section 34.1.1. If no arguments are given, a
+ new connection is made using the same parameters as before.
+
+ Specifying any
+ of dbname,
+ username,
+ host or
+ port
+ as - is equivalent to omitting that parameter.
+
+ The new connection can re-use connection parameters from the previous
+ connection; not only database name, user, host, and port, but other
+ settings such as sslmode. By default,
+ parameters are re-used in the positional syntax, but not when
+ a conninfo string is given. Passing a
+ first argument of -reuse-previous=on
+ or -reuse-previous=off overrides that default. If
+ parameters are re-used, then any parameter not explicitly specified as
+ a positional parameter or in the conninfo
+ string is taken from the existing connection's parameters. An
+ exception is that if the host setting
+ is changed from its previous value using the positional syntax,
+ any hostaddr setting present in the
+ existing connection's parameters is dropped.
+ Also, any password used for the existing connection will be re-used
+ only if the user, host, and port settings are not changed.
+ When the command neither specifies nor reuses a particular parameter,
+ the libpq default is used.
+
+ If the new connection is successfully made, the previous
+ connection is closed.
+ If the connection attempt fails (wrong user name, access
+ denied, etc.), the previous connection will be kept if
+ psql is in interactive mode. But when
+ executing a non-interactive script, the old connection is closed
+ and an error is reported. That may or may not terminate the
+ script; if it does not, all database-accessing commands will fail
+ until another \connect command is successfully
+ executed. This distinction was chosen as
+ a user convenience against typos on the one hand, and a safety
+ mechanism that scripts are not accidentally acting on the
+ wrong database on the other hand.
+ Note that whenever a \connect command attempts
+ to re-use parameters, the values re-used are those of the last
+ successful connection, not of any failed attempts made subsequently.
+ However, in the case of a
+ non-interactive \connect failure, no parameters
+ are allowed to be re-used later, since the script would likely be
+ expecting the values from the failed \connect
+ to be re-used.
+
+ Sets the title of any tables being printed as the result of a
+ query or unset any such title. This command is equivalent to
+ \pset title title. (The name of
+ this command derives from “caption”, as it was
+ previously only used to set the caption in an
+ HTML table.)
+
+ Performs a frontend (client) copy. This is an operation that
+ runs an SQL COPY
+ command, but instead of the server
+ reading or writing the specified file,
+ psql reads or writes the file and
+ routes the data between the server and the local file system.
+ This means that file accessibility and privileges are those of
+ the local user, not the server, and no SQL superuser
+ privileges are required.
+
+ When program is specified,
+ command is
+ executed by psql and the data passed from
+ or to command is
+ routed between the server and the client.
+ Again, the execution privileges are those of
+ the local user, not the server, and no SQL superuser
+ privileges are required.
+
+ For \copy ... from stdin, data rows are read from the same
+ source that issued the command, continuing until \.
+ is read or the stream reaches EOF. This option is useful
+ for populating tables in-line within an SQL script file.
+ For \copy ... to stdout, output is sent to the same place
+ as psql command output, and
+ the COPY count command status is
+ not printed (since it might be confused with a data row).
+ To read/write psql's standard input or
+ output regardless of the current command source or \o
+ option, write from pstdin or to pstdout.
+
+ The syntax of this command is similar to that of the
+ SQL COPY
+ command. All options other than the data source/destination are
+ as specified for COPY.
+ Because of this, special parsing rules apply to the \copy
+ meta-command. Unlike most other meta-commands, the entire remainder
+ of the line is always taken to be the arguments of \copy,
+ and neither variable interpolation nor backquote expansion are
+ performed in the arguments.
+
Tip
+ Another way to obtain the same result as \copy
+ ... to is to use the SQL COPY
+ ... TO STDOUT command and terminate it
+ with \g filename
+ or \g |program.
+ Unlike \copy, this method allows the command to
+ span multiple lines; also, variable interpolation and backquote
+ expansion can be used.
+
Tip
+ These operations are not as efficient as the SQL
+ COPY command with a file or program data source or
+ destination, because all data must pass through the client/server
+ connection. For large amounts of data the SQL
+ command might be preferable.
+ Also, because of this pass-through method, \copy
+ ... from in CSV mode will erroneously
+ treat a \. data value alone on a line as an
+ end-of-input marker.
+
+ Executes the current query buffer (like \g) and
+ shows the results in a crosstab grid.
+ The query must return at least three columns.
+ The output column identified by colV
+ becomes a vertical header and the output column identified by
+ colH
+ becomes a horizontal header.
+ colD identifies
+ the output column to display within the grid.
+ sortcolH identifies
+ an optional sort column for the horizontal header.
+
+ Each column specification can be a column number (starting at 1) or
+ a column name. The usual SQL case folding and quoting rules apply to
+ column names. If omitted,
+ colV is taken as column 1
+ and colH as column 2.
+ colH must differ from
+ colV.
+ If colD is not
+ specified, then there must be exactly three columns in the query
+ result, and the column that is neither
+ colV nor
+ colH
+ is taken to be colD.
+
+ The vertical header, displayed as the leftmost column, contains the
+ values found in column colV, in the
+ same order as in the query results, but with duplicates removed.
+
+ The horizontal header, displayed as the first row, contains the values
+ found in column colH,
+ with duplicates removed. By default, these appear in the same order
+ as in the query results. But if the
+ optional sortcolH argument is given,
+ it identifies a column whose values must be integer numbers, and the
+ values from colH will
+ appear in the horizontal header sorted according to the
+ corresponding sortcolH values.
+
+ Inside the crosstab grid, for each distinct value x
+ of colH and each distinct
+ value y
+ of colV, the cell located
+ at the intersection (x,y) contains the value of
+ the colD column in the query result row for which
+ the value of colH
+ is x and the value
+ of colV
+ is y. If there is no such row, the cell is empty. If
+ there are multiple such rows, an error is reported.
+
+ For each relation (table, view, materialized view, index, sequence,
+ or foreign table)
+ or composite type matching the
+ pattern, show all
+ columns, their types, the tablespace (if not the default) and any
+ special attributes such as NOT NULL or defaults.
+ Associated indexes, constraints, rules, and triggers are
+ also shown. For foreign tables, the associated foreign
+ server is shown as well.
+ (“Matching the pattern” is defined in
+ Patterns below.)
+
+ For some types of relation, \d shows additional information
+ for each column: column values for sequences, indexed expressions for
+ indexes, and foreign data wrapper options for foreign tables.
+
+ The command form \d+ is identical, except that
+ more information is displayed: any comments associated with the
+ columns of the table are shown, as is the presence of OIDs in the
+ table, the view definition if the relation is a view, a non-default
+ replica
+ identity setting and the
+ access method name
+ if the relation has an access method.
+
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+
Note
+ If \d is used without a
+ pattern argument, it is
+ equivalent to \dtvmsE which will show a list of
+ all visible tables, views, materialized views, sequences and
+ foreign tables.
+ This is purely a convenience measure.
+
+ Lists aggregate functions, together with their
+ return type and the data types they operate on. If pattern
+ is specified, only aggregates whose names match the pattern are shown.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+
+ Lists access methods. If pattern is specified, only access
+ methods whose names match the pattern are shown. If
+ + is appended to the command name, each access
+ method is listed with its associated handler function and description.
+
+ Lists operator classes
+ (see Section 38.16.1).
+ If access-method-pattern
+ is specified, only operator classes associated with access methods whose
+ names match that pattern are listed.
+ If input-type-pattern
+ is specified, only operator classes associated with input types whose
+ names match that pattern are listed.
+ If + is appended to the command name, each operator
+ class is listed with its associated operator family and owner.
+
+ Lists operator families
+ (see Section 38.16.5).
+ If access-method-pattern
+ is specified, only operator families associated with access methods whose
+ names match that pattern are listed.
+ If input-type-pattern
+ is specified, only operator families associated with input types whose
+ names match that pattern are listed.
+ If + is appended to the command name, each operator
+ family is listed with its owner.
+
+ Lists operators associated with operator families
+ (see Section 38.16.2).
+ If access-method-pattern
+ is specified, only members of operator families associated with access
+ methods whose names match that pattern are listed.
+ If operator-family-pattern
+ is specified, only members of operator families whose names match that
+ pattern are listed.
+ If + is appended to the command name, each operator
+ is listed with its sort operator family (if it is an ordering operator).
+
+ Lists support functions associated with operator families
+ (see Section 38.16.3).
+ If access-method-pattern
+ is specified, only functions of operator families associated with
+ access methods whose names match that pattern are listed.
+ If operator-family-pattern
+ is specified, only functions of operator families whose names match
+ that pattern are listed.
+ If + is appended to the command name, functions are
+ displayed verbosely, with their actual parameter lists.
+
+ Lists tablespaces. If pattern
+ is specified, only tablespaces whose names match the pattern are shown.
+ If + is appended to the command name, each tablespace
+ is listed with its associated options, on-disk size, permissions and
+ description.
+
+ Lists conversions between character-set encodings.
+ If pattern
+ is specified, only conversions whose names match the pattern are
+ listed.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+ If + is appended to the command name, each object
+ is listed with its associated description.
+
+ Lists server configuration parameters and their values.
+ If pattern is specified,
+ only parameters whose names match the pattern are listed. Without
+ a pattern, only
+ parameters that are set to non-default values are listed.
+ (Use \dconfig * to see all parameters.)
+ If + is appended to the command name, each
+ parameter is listed with its data type, context in which the
+ parameter can be set, and access privileges (if non-default access
+ privileges have been granted).
+
+ Lists type casts.
+ If pattern
+ is specified, only casts whose source or target types match the
+ pattern are listed.
+ If + is appended to the command name, each object
+ is listed with its associated description.
+
+ Shows the descriptions of objects of type constraint,
+ operator class, operator family,
+ rule, and trigger. All
+ other comments may be viewed by the respective backslash commands for
+ those object types.
+
\dd displays descriptions for objects matching the
+ pattern, or of visible
+ objects of the appropriate type if no argument is given. But in either
+ case, only objects that have a description are listed.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+
+ Descriptions for objects can be created with the COMMENT
+ SQL command.
+
+ Lists domains. If pattern
+ is specified, only domains whose names match the pattern are shown.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+ If + is appended to the command name, each object
+ is listed with its associated permissions and description.
+
+ Lists default access privilege settings. An entry is shown for
+ each role (and schema, if applicable) for which the default
+ privilege settings have been changed from the built-in defaults.
+ If pattern is
+ specified, only entries whose role name or schema name matches
+ the pattern are listed.
+
+ The ALTER DEFAULT
+ PRIVILEGES command is used to set default access
+ privileges. The meaning of the privilege display is explained in
+ Section 5.7.
+
+ In this group of commands, the letters E,
+ i, m, s,
+ t, and v
+ stand for foreign table, index, materialized view,
+ sequence, table, and view,
+ respectively.
+ You can specify any or all of
+ these letters, in any order, to obtain a listing of objects
+ of these types. For example, \dti lists
+ tables and indexes. If + is
+ appended to the command name, each object is listed with its
+ persistence status (permanent, temporary, or unlogged),
+ physical size on disk, and associated description if any.
+ If pattern is
+ specified, only objects whose names match the pattern are listed.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+
+ Lists foreign servers (mnemonic: “external
+ servers”).
+ If pattern is
+ specified, only those servers whose name matches the pattern
+ are listed. If the form \des+ is used, a
+ full description of each server is shown, including the
+ server's access privileges, type, version, options, and description.
+
+ Lists foreign tables (mnemonic: “external tables”).
+ If pattern is
+ specified, only entries whose table name or schema name matches
+ the pattern are listed. If the form \det+
+ is used, generic options and the foreign table description
+ are also displayed.
+
+ Lists user mappings (mnemonic: “external
+ users”).
+ If pattern is
+ specified, only those mappings whose user names match the
+ pattern are listed. If the form \deu+ is
+ used, additional information about each mapping is shown.
+
Caution
+ \deu+ might also display the user name and
+ password of the remote user, so care should be taken not to
+ disclose them.
+
+ Lists foreign-data wrappers (mnemonic: “external
+ wrappers”).
+ If pattern is
+ specified, only those foreign-data wrappers whose name matches
+ the pattern are listed. If the form \dew+
+ is used, the access privileges, options, and description of the
+ foreign-data wrapper are also shown.
+
+ Lists functions, together with their result data types, argument data
+ types, and function types, which are classified as “agg”
+ (aggregate), “normal”, “procedure”, “trigger”, or “window”.
+ To display only functions
+ of specific type(s), add the corresponding letters a,
+ n, p, t, or w to the command.
+ If pattern is specified, only
+ functions whose names match the pattern are shown.
+ Any additional arguments are type-name patterns, which are matched
+ to the type names of the first, second, and so on arguments of the
+ function. (Matching functions can have more arguments than what
+ you specify. To prevent that, write a dash - as
+ the last arg_pattern.)
+ By default, only user-created
+ objects are shown; supply a pattern or the S
+ modifier to include system objects.
+ If the form \df+ is used, additional information
+ about each function is shown, including volatility,
+ parallel safety, owner, security classification, access privileges,
+ language, internal name (for C and internal functions only),
+ and description.
+ Source code for a specific function can be seen
+ using \sf.
+
+ Lists text search configurations.
+ If pattern is specified,
+ only configurations whose names match the pattern are shown.
+ If the form \dF+ is used, a full description of
+ each configuration is shown, including the underlying text search
+ parser and the dictionary list for each parser token type.
+
+ Lists text search dictionaries.
+ If pattern is specified,
+ only dictionaries whose names match the pattern are shown.
+ If the form \dFd+ is used, additional information
+ is shown about each selected dictionary, including the underlying
+ text search template and the option values.
+
+ Lists text search parsers.
+ If pattern is specified,
+ only parsers whose names match the pattern are shown.
+ If the form \dFp+ is used, a full description of
+ each parser is shown, including the underlying functions and the
+ list of recognized token types.
+
+ Lists text search templates.
+ If pattern is specified,
+ only templates whose names match the pattern are shown.
+ If the form \dFt+ is used, additional information
+ is shown about each template, including the underlying function names.
+
+ Lists database roles.
+ (Since the concepts of “users” and “groups” have been
+ unified into “roles”, this command is now equivalent to
+ \du.)
+ By default, only user-created roles are shown; supply the
+ S modifier to include system roles.
+ If pattern is specified,
+ only those roles whose names match the pattern are listed.
+ If the form \dg+ is used, additional information
+ is shown about each role; currently this adds the comment for each
+ role.
+
+ This is an alias for \lo_list, which shows a
+ list of large objects.
+ If + is appended to the command name,
+ each large object is listed with its associated permissions,
+ if any.
+
+ Lists procedural languages. If pattern
+ is specified, only languages whose names match the pattern are listed.
+ By default, only user-created languages
+ are shown; supply the S modifier to include system
+ objects. If + is appended to the command name, each
+ language is listed with its call handler, validator, access privileges,
+ and whether it is a system object.
+
+ Lists schemas (namespaces). If pattern
+ is specified, only schemas whose names match the pattern are listed.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system objects.
+ If + is appended to the command name, each object
+ is listed with its associated permissions and description, if any.
+
+ Lists operators with their operand and result types.
+ If pattern is
+ specified, only operators whose names match the pattern are listed.
+ If one arg_pattern is
+ specified, only prefix operators whose right argument's type name
+ matches that pattern are listed.
+ If two arg_patterns
+ are specified, only binary operators whose argument type names match
+ those patterns are listed. (Alternatively, write -
+ for the unused argument of a unary operator.)
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+ If + is appended to the command name,
+ additional information about each operator is shown, currently just
+ the name of the underlying function.
+
+ Lists collations.
+ If pattern is
+ specified, only collations whose names match the pattern are
+ listed. By default, only user-created objects are shown;
+ supply a pattern or the S modifier to
+ include system objects. If + is appended
+ to the command name, each collation is listed with its associated
+ description, if any.
+ Note that only collations usable with the current database's encoding
+ are shown, so the results may vary in different databases of the
+ same installation.
+
+ Lists tables, views and sequences with their
+ associated access privileges.
+ If pattern is
+ specified, only tables, views and sequences whose names match the
+ pattern are listed. By default only user-created objects are shown;
+ supply a pattern or the S modifier to include
+ system objects.
+
+ The GRANT and
+ REVOKE
+ commands are used to set access privileges. The meaning of the
+ privilege display is explained in
+ Section 5.7.
+
+ Lists partitioned relations.
+ If pattern
+ is specified, only entries whose name matches the pattern are listed.
+ The modifiers t (tables) and i
+ (indexes) can be appended to the command, filtering the kind of
+ relations to list. By default, partitioned tables and indexes are
+ listed.
+
+ If the modifier n (“nested”) is used,
+ or a pattern is specified, then non-root partitioned relations are
+ included, and a column is shown displaying the parent of each
+ partitioned relation.
+
+ If + is appended to the command name, the sum of the
+ sizes of each relation's partitions is also displayed, along with the
+ relation's description.
+ If n is combined with +, two
+ sizes are shown: one including the total size of directly-attached
+ leaf partitions, and another showing the total size of all partitions,
+ including indirectly attached sub-partitions.
+
+ Lists defined configuration settings. These settings can be
+ role-specific, database-specific, or both.
+ role-pattern and
+ database-pattern are used to select
+ specific roles and databases to list, respectively. If omitted, or if
+ * is specified, all settings are listed, including those
+ not role-specific or database-specific, respectively.
+
+ The ALTER ROLE and
+ ALTER DATABASE
+ commands are used to define per-role and per-database configuration
+ settings.
+
+ Lists information about each granted role membership, including
+ assigned options (ADMIN,
+ INHERIT and/or SET) and grantor.
+ See the GRANT
+ command for information about role memberships.
+
+ By default, only grants to user-created roles are shown; supply the
+ S modifier to include system roles.
+ If pattern is specified,
+ only grants to those roles whose names match the pattern are listed.
+
+ Lists replication publications.
+ If pattern is
+ specified, only those publications whose names match the pattern are
+ listed.
+ If + is appended to the command name, the tables and
+ schemas associated with each publication are shown as well.
+
+ Lists replication subscriptions.
+ If pattern is
+ specified, only those subscriptions whose names match the pattern are
+ listed.
+ If + is appended to the command name, additional
+ properties of the subscriptions are shown.
+
+ Lists data types.
+ If pattern is
+ specified, only types whose names match the pattern are listed.
+ If + is appended to the command name, each type is
+ listed with its internal name and size, its allowed values
+ if it is an enum type, and its associated permissions.
+ By default, only user-created objects are shown; supply a
+ pattern or the S modifier to include system
+ objects.
+
+ Lists database roles.
+ (Since the concepts of “users” and “groups” have been
+ unified into “roles”, this command is now equivalent to
+ \dg.)
+ By default, only user-created roles are shown; supply the
+ S modifier to include system roles.
+ If pattern is specified,
+ only those roles whose names match the pattern are listed.
+ If the form \du+ is used, additional information
+ is shown about each role; currently this adds the comment for each
+ role.
+
+ Lists installed extensions.
+ If pattern
+ is specified, only those extensions whose names match the pattern
+ are listed.
+ If the form \dx+ is used, all the objects belonging
+ to each matching extension are listed.
+
+ Lists extended statistics.
+ If pattern
+ is specified, only those extended statistics whose names match the
+ pattern are listed.
+
+ The status of each kind of extended statistics is shown in a column
+ named after its statistic kind (e.g. Ndistinct).
+ defined means that it was requested when creating
+ the statistics, and NULL means it wasn't requested.
+ You can use pg_stats_ext if you'd like to
+ know whether ANALYZE
+ was run and statistics are available to the planner.
+
+ Lists event triggers.
+ If pattern
+ is specified, only those event triggers whose names match the pattern
+ are listed.
+ If + is appended to the command name, each object
+ is listed with its associated description.
+
+ If filename is
+ specified, the file is edited; after the editor exits, the file's
+ content is copied into the current query buffer. If no filename is given, the current query
+ buffer is copied to a temporary file which is then edited in the same
+ fashion. Or, if the current query buffer is empty, the most recently
+ executed query is copied to a temporary file and edited in the same
+ fashion.
+
+ If you edit a file or the previous query, and you quit the editor without
+ modifying the file, the query buffer is cleared.
+ Otherwise, the new contents of the query buffer are re-parsed according to
+ the normal rules of psql, treating the
+ whole buffer as a single line. Any complete queries are immediately
+ executed; that is, if the query buffer contains or ends with a
+ semicolon, everything up to that point is executed and removed from
+ the query buffer. Whatever remains in the query buffer is
+ redisplayed. Type semicolon or \g to send it,
+ or \r to cancel it by clearing the query buffer.
+
+ Treating the buffer as a single line primarily affects meta-commands:
+ whatever is in the buffer after a meta-command will be taken as
+ argument(s) to the meta-command, even if it spans multiple lines.
+ (Thus you cannot make meta-command-using scripts this way.
+ Use \i for that.)
+
+ If a line number is specified, psql will
+ position the cursor on the specified line of the file or query buffer.
+ Note that if a single all-digits argument is given,
+ psql assumes it is a line number,
+ not a file name.
+
Tip
+ See Environment, below, for how to
+ configure and customize your editor.
+
+ Prints the evaluated arguments to standard output, separated by
+ spaces and followed by a newline. This can be useful to
+ intersperse information in the output of scripts. For example:
+
+=> \echo `date`
+Tue Oct 26 21:40:57 CEST 1999
+
+ If the first argument is an unquoted -n the trailing
+ newline is not written (nor is the first argument).
+
Tip
+ If you use the \o command to redirect your
+ query output you might wish to use \qecho
+ instead of this command. See also \warn.
+
+ This command fetches and edits the definition of the named function or procedure,
+ in the form of a CREATE OR REPLACE FUNCTION or
+ CREATE OR REPLACE PROCEDURE command.
+ Editing is done in the same way as for \edit.
+ If you quit the editor without saving, the statement is discarded.
+ If you save and exit the editor, the updated command is executed immediately
+ if you added a semicolon to it. Otherwise it is redisplayed;
+ type semicolon or \g to send it, or \r
+ to cancel.
+
+ The target function can be specified by name alone, or by name
+ and arguments, for example foo(integer, text).
+ The argument types must be given if there is more
+ than one function of the same name.
+
+ If no function is specified, a blank CREATE FUNCTION
+ template is presented for editing.
+
+ If a line number is specified, psql will
+ position the cursor on the specified line of the function body.
+ (Note that the function body typically does not begin on the first
+ line of the file.)
+
+ Unlike most other meta-commands, the entire remainder of the line is
+ always taken to be the argument(s) of \ef, and neither
+ variable interpolation nor backquote expansion are performed in the
+ arguments.
+
Tip
+ See Environment, below, for how to
+ configure and customize your editor.
+
+ Repeats the most recent server error message at maximum
+ verbosity, as though VERBOSITY were set
+ to verbose and SHOW_CONTEXT were
+ set to always.
+
+ This command fetches and edits the definition of the named view,
+ in the form of a CREATE OR REPLACE VIEW command.
+ Editing is done in the same way as for \edit.
+ If you quit the editor without saving, the statement is discarded.
+ If you save and exit the editor, the updated command is executed immediately
+ if you added a semicolon to it. Otherwise it is redisplayed;
+ type semicolon or \g to send it, or \r
+ to cancel.
+
+ If no view is specified, a blank CREATE VIEW
+ template is presented for editing.
+
+ If a line number is specified, psql will
+ position the cursor on the specified line of the view definition.
+
+ Unlike most other meta-commands, the entire remainder of the line is
+ always taken to be the argument(s) of \ev, and neither
+ variable interpolation nor backquote expansion are performed in the
+ arguments.
+
+ Sends the current query buffer to the server for execution.
+
+ If parentheses appear after \g, they surround a
+ space-separated list
+ of option=value
+ formatting-option clauses, which are interpreted in the same way
+ as \pset
+ option
+ value commands, but take
+ effect only for the duration of this query. In this list, spaces are
+ not allowed around = signs, but are required
+ between option clauses.
+ If =value
+ is omitted, the
+ named option is changed
+ in the same way as for
+ \psetoption
+ with no explicit value.
+
+ If a filename
+ or |command
+ argument is given, the query's output is written to the named
+ file or piped to the given shell command, instead of displaying it as
+ usual. The file or command is written to only if the query
+ successfully returns zero or more tuples, not if the query fails or
+ is a non-data-returning SQL command.
+
+ If the current query buffer is empty, the most recently sent query is
+ re-executed instead. Except for that behavior, \g
+ without any arguments is essentially equivalent to a semicolon.
+ With arguments, \g provides
+ a “one-shot” alternative to the \o
+ command, and additionally allows one-shot adjustments of the
+ output formatting options normally set by \pset.
+
+ When the last argument begins with |, the entire
+ remainder of the line is taken to be
+ the command to execute,
+ and neither variable interpolation nor backquote expansion are
+ performed in it. The rest of the line is simply passed literally to
+ the shell.
+
+ Shows the description (that is, the column names and data types)
+ of the result of the current query buffer. The query is not
+ actually executed; however, if it contains some type of syntax
+ error, that error will be reported in the normal way.
+
+ If the current query buffer is empty, the most recently sent query
+ is described instead.
+
+ Gets the value of the environment
+ variable env_var
+ and assigns it to the psql
+ variable psql_var.
+ If env_var is
+ not defined in the psql process's
+ environment, psql_var
+ is not changed. Example:
+
+=> \getenv home HOME
+=> \echo :home
+/home/postgres
+
+ Sends the current query buffer to the server, then treats
+ each column of each row of the query's output (if any) as an SQL
+ statement to be executed. For example, to create an index on each
+ column of my_table:
+
+=> SELECT format('create index on my_table(%I)', attname)
+-> FROM pg_attribute
+-> WHERE attrelid = 'my_table'::regclass AND attnum > 0
+-> ORDER BY attnum
+-> \gexec
+CREATE INDEX
+CREATE INDEX
+CREATE INDEX
+CREATE INDEX
+
+
+ The generated queries are executed in the order in which the rows
+ are returned, and left-to-right within each row if there is more
+ than one column. NULL fields are ignored. The generated queries
+ are sent literally to the server for processing, so they cannot be
+ psql meta-commands nor contain psql
+ variable references. If any individual query fails, execution of
+ the remaining queries continues
+ unless ON_ERROR_STOP is set. Execution of each
+ query is subject to ECHO processing.
+ (Setting ECHO to all
+ or queries is often advisable when
+ using \gexec.) Query logging, single-step mode,
+ timing, and other query execution features apply to each generated
+ query as well.
+
+ If the current query buffer is empty, the most recently sent query
+ is re-executed instead.
+
+ Sends the current query buffer to the server and stores the
+ query's output into psql variables
+ (see Variables below).
+ The query to be executed must return exactly one row. Each column of
+ the row is stored into a separate variable, named the same as the
+ column. For example:
+
+=> SELECT 'hello' AS var1, 10 AS var2
+-> \gset
+=> \echo :var1 :var2
+hello 10
+
+
+ If you specify a prefix,
+ that string is prepended to the query's column names to create the
+ variable names to use:
+
+=> SELECT 'hello' AS var1, 10 AS var2
+-> \gset result_
+=> \echo :result_var1 :result_var2
+hello 10
+
+
+ If a column result is NULL, the corresponding variable is unset
+ rather than being set.
+
+ If the query fails or does not return one row,
+ no variables are changed.
+
+ If the current query buffer is empty, the most recently sent query
+ is re-executed instead.
+
+ \gx is equivalent to \g, except
+ that it forces expanded output mode for this query, as
+ if expanded=on were included in the list of
+ \pset options. See also \x.
+
+ Gives syntax help on the specified SQL
+ command. If command
+ is not specified, then psql will list
+ all the commands for which syntax help is available. If
+ command is an
+ asterisk (*), then syntax help on all
+ SQL commands is shown.
+
+ Unlike most other meta-commands, the entire remainder of the line is
+ always taken to be the argument(s) of \help, and neither
+ variable interpolation nor backquote expansion are performed in the
+ arguments.
+
Note
+ To simplify typing, commands that consists of several words do
+ not have to be quoted. Thus it is fine to type \help
+ alter table.
+
+ Turns on HTML query output format. If the
+ HTML format is already on, it is switched
+ back to the default aligned text format. This command is for
+ compatibility and convenience, but see \pset
+ about setting other output options.
+
+ Reads input from the file filename and executes it as
+ though it had been typed on the keyboard.
+
+ If filename is -
+ (hyphen), then standard input is read until an EOF indication
+ or \q meta-command. This can be used to intersperse
+ interactive input with input from files. Note that Readline behavior
+ will be used only if it is active at the outermost level.
+
Note
+ If you want to see the lines on the screen as they are read you
+ must set the variable ECHO to
+ all.
+
+ This group of commands implements nestable conditional blocks.
+ A conditional block must begin with an \if and end
+ with an \endif. In between there may be any number
+ of \elif clauses, which may optionally be followed
+ by a single \else clause. Ordinary queries and
+ other types of backslash commands may (and usually do) appear between
+ the commands forming a conditional block.
+
+ The \if and \elif commands read
+ their argument(s) and evaluate them as a Boolean expression. If the
+ expression yields true then processing continues
+ normally; otherwise, lines are skipped until a
+ matching \elif, \else,
+ or \endif is reached. Once
+ an \if or \elif test has
+ succeeded, the arguments of later \elif commands in
+ the same block are not evaluated but are treated as false. Lines
+ following an \else are processed only if no earlier
+ matching \if or \elif succeeded.
+
+ The expression argument
+ of an \if or \elif command
+ is subject to variable interpolation and backquote expansion, just
+ like any other backslash command argument. After that it is evaluated
+ like the value of an on/off option variable. So a valid value
+ is any unambiguous case-insensitive match for one of:
+ true, false, 1,
+ 0, on, off,
+ yes, no. For example,
+ t, T, and tR
+ will all be considered to be true.
+
+ Expressions that do not properly evaluate to true or false will
+ generate a warning and be treated as false.
+
+ Lines being skipped are parsed normally to identify queries and
+ backslash commands, but queries are not sent to the server, and
+ backslash commands other than conditionals
+ (\if, \elif,
+ \else, \endif) are
+ ignored. Conditional commands are checked only for valid nesting.
+ Variable references in skipped lines are not expanded, and backquote
+ expansion is not performed either.
+
+ All the backslash commands of a given conditional block must appear in
+ the same source file. If EOF is reached on the main input file or an
+ \include-ed file before all local
+ \if-blocks have been closed,
+ then psql will raise an error.
+
+ Here is an example:
+
+-- check for the existence of two separate records in the database and store
+-- the results in separate psql variables
+SELECT
+ EXISTS(SELECT 1 FROM customer WHERE customer_id = 123) as is_customer,
+ EXISTS(SELECT 1 FROM employee WHERE employee_id = 456) as is_employee
+\gset
+\if :is_customer
+ SELECT * FROM customer WHERE customer_id = 123;
+\elif :is_employee
+ \echo 'is not a customer but is an employee'
+ SELECT * FROM employee WHERE employee_id = 456;
+\else
+ \if yes
+ \echo 'not a customer or employee'
+ \else
+ \echo 'this will never print'
+ \endif
+\endif
+
+ The \ir command is similar to \i, but resolves
+ relative file names differently. When executing in interactive mode,
+ the two commands behave identically. However, when invoked from a
+ script, \ir interprets file names relative to the
+ directory in which the script is located, rather than the current
+ working directory.
+
+ List the databases in the server and show their names, owners,
+ character set encodings, and access privileges.
+ If pattern is specified,
+ only databases whose names match the pattern are listed.
+ If + is appended to the command name, database
+ sizes, default tablespaces, and descriptions are also displayed.
+ (Size information is only available for databases that the current
+ user can connect to.)
+
+ Reads the large object with OID loid from the database and
+ writes it to filename. Note that this is
+ subtly different from the server function
+ lo_export, which acts with the permissions
+ of the user that the database server runs as and on the server's
+ file system.
+
Tip
+ Use \lo_list to find out the large object's
+ OID.
+
+ Stores the file into a PostgreSQL
+ large object. Optionally, it associates the given
+ comment with the object. Example:
+
+foo=> \lo_import '/home/peter/pictures/photo.xcf' 'a picture of me'
+lo_import 152801
+
+ The response indicates that the large object received object
+ ID 152801, which can be used to access the newly-created large
+ object in the future. For the sake of readability, it is
+ recommended to always associate a human-readable comment with
+ every object. Both OIDs and comments can be viewed with the
+ \lo_list command.
+
+ Note that this command is subtly different from the server-side
+ lo_import because it acts as the local user
+ on the local file system, rather than the server's user and file
+ system.
+
+ Shows a list of all PostgreSQL
+ large objects currently stored in the database,
+ along with any comments provided for them.
+ If + is appended to the command name,
+ each large object is listed with its associated permissions,
+ if any.
+
+ Arranges to save future query results to the file filename or pipe future results
+ to the shell command command. If no argument is
+ specified, the query output is reset to the standard output.
+
+ If the argument begins with |, then the entire remainder
+ of the line is taken to be
+ the command to execute,
+ and neither variable interpolation nor backquote expansion are
+ performed in it. The rest of the line is simply passed literally to
+ the shell.
+
+ “Query results” includes all tables, command
+ responses, and notices obtained from the database server, as
+ well as output of various backslash commands that query the
+ database (such as \d); but not error
+ messages.
+
Tip
+ To intersperse text output in between query results, use
+ \qecho.
+
+ Print the current query buffer to the standard output.
+ If the current query buffer is empty, the most recently executed query
+ is printed instead.
+
+ Changes the password of the specified user (by default, the current
+ user). This command prompts for the new password, encrypts it, and
+ sends it to the server as an ALTER ROLE command. This
+ makes sure that the new password does not appear in cleartext in the
+ command history, the server log, or elsewhere.
+
+ Prompts the user to supply text, which is assigned to the variable
+ name.
+ An optional prompt string, text, can be specified. (For multiword
+ prompts, surround the text with single quotes.)
+
+ By default, \prompt uses the terminal for input and
+ output. However, if the -f command line switch was
+ used, \prompt uses standard input and standard output.
+
+ This command sets options affecting the output of query result tables.
+ option
+ indicates which option is to be set. The semantics of
+ value vary depending
+ on the selected option. For some options, omitting value causes the option to be toggled
+ or unset, as described under the particular option. If no such
+ behavior is mentioned, then omitting
+ value just results in
+ the current setting being displayed.
+
+ \pset without any arguments displays the current status
+ of all printing options.
+
+ The value must be a
+ number. In general, the higher
+ the number the more borders and lines the tables will have,
+ but details depend on the particular format.
+ In HTML format, this will translate directly
+ into the border=... attribute.
+ In most other formats only values 0 (no border), 1 (internal
+ dividing lines), and 2 (table frame) make sense, and values above 2
+ will be treated the same as border = 2.
+ The latex and latex-longtable
+ formats additionally allow a value of 3 to add dividing lines
+ between data rows.
+
+ Sets the target width for the wrapped format, and also
+ the width limit for determining whether output is wide enough to
+ require the pager or switch to the vertical display in expanded auto
+ mode.
+ Zero (the default) causes the target width to be controlled by the
+ environment variable COLUMNS, or the detected screen width
+ if COLUMNS is not set.
+ In addition, if columns is zero then the
+ wrapped format only affects screen output.
+ If columns is nonzero then file and pipe output is
+ wrapped to that width as well.
+
+ Specifies the field separator to be used in
+ CSV output format. If the separator character
+ appears in a field's value, that field is output within double
+ quotes, following standard CSV rules.
+ The default is a comma.
+
+ If value is specified it
+ must be either on or off, which
+ will enable or disable expanded mode, or auto.
+ If value is omitted the
+ command toggles between the on and off settings. When expanded mode
+ is enabled, query results are displayed in two columns, with the
+ column name on the left and the data on the right. This mode is
+ useful if the data wouldn't fit on the screen in the
+ normal “horizontal” mode. In the auto setting, the
+ expanded mode is used whenever the query output has more than one
+ column and is wider than the screen; otherwise, the regular mode is
+ used. The auto setting is only
+ effective in the aligned and wrapped formats. In other formats, it
+ always behaves as if the expanded mode is off.
+
+ Specifies the field separator to be used in unaligned output
+ format. That way one can create, for example, tab-separated
+ output, which other programs might prefer. To
+ set a tab as field separator, type \pset fieldsep
+ '\t'. The default field separator is
+ '|' (a vertical bar).
+
+ If value is specified
+ it must be either on or off
+ which will enable or disable display of the table footer
+ (the (n rows) count).
+ If value is omitted the
+ command toggles footer display on or off.
+
+ Sets the output format to one of aligned,
+ asciidoc,
+ csv,
+ html,
+ latex,
+ latex-longtable, troff-ms,
+ unaligned, or wrapped.
+ Unique abbreviations are allowed.
+
aligned format is the standard,
+ human-readable, nicely formatted text output; this is the default.
+
unaligned format writes all columns of a row on one
+ line, separated by the currently active field separator. This
+ is useful for creating output that might be intended to be read
+ in by other programs, for example, tab-separated or comma-separated
+ format. However, the field separator character is not treated
+ specially if it appears in a column's value;
+ so CSV format may be better suited for such
+ purposes.
+
csv format
+
+ writes column values separated by commas, applying the quoting
+ rules described in
+ RFC 4180.
+ This output is compatible with the CSV format of the server's
+ COPY command.
+ A header line with column names is generated unless
+ the tuples_only parameter is
+ on. Titles and footers are not printed.
+ Each row is terminated by the system-dependent end-of-line character,
+ which is typically a single newline (\n) for
+ Unix-like systems or a carriage return and newline sequence
+ (\r\n) for Microsoft Windows.
+ Field separator characters other than comma can be selected with
+ \pset csv_fieldsep.
+
wrapped format is like aligned but wraps
+ wide data values across lines to make the output fit in the target
+ column width. The target width is determined as described under
+ the columns option. Note that psql will
+ not attempt to wrap column header titles; therefore,
+ wrapped format behaves the same as aligned
+ if the total width needed for column headers exceeds the target.
+
+ The asciidoc, html,
+ latex, latex-longtable, and
+ troff-ms formats put out tables that are intended
+ to be included in documents using the respective mark-up
+ language. They are not complete documents! This might not be
+ necessary in HTML, but in
+ LaTeX you must have a complete
+ document wrapper.
+ The latex format
+ uses LaTeX's tabular
+ environment.
+ The latex-longtable format
+ requires the LaTeX
+ longtable and booktabs packages.
+
+ Sets the border line drawing style to one
+ of ascii, old-ascii,
+ or unicode.
+ Unique abbreviations are allowed. (That would mean one
+ letter is enough.)
+ The default setting is ascii.
+ This option only affects the aligned and
+ wrapped output formats.
+
ascii style uses plain ASCII
+ characters. Newlines in data are shown using
+ a + symbol in the right-hand margin.
+ When the wrapped format wraps data from
+ one line to the next without a newline character, a dot
+ (.) is shown in the right-hand margin of the first line,
+ and again in the left-hand margin of the following line.
+
old-ascii style uses plain ASCII
+ characters, using the formatting style used
+ in PostgreSQL 8.4 and earlier.
+ Newlines in data are shown using a :
+ symbol in place of the left-hand column separator.
+ When the data is wrapped from one line
+ to the next without a newline character, a ;
+ symbol is used in place of the left-hand column separator.
+
unicode style uses Unicode box-drawing characters.
+ Newlines in data are shown using a carriage return symbol
+ in the right-hand margin. When the data is wrapped from one line
+ to the next without a newline character, an ellipsis symbol
+ is shown in the right-hand margin of the first line, and
+ again in the left-hand margin of the following line.
+
+ When the border setting is greater than zero,
+ the linestyle option also determines the
+ characters with which the border lines are drawn.
+ Plain ASCII characters work everywhere, but
+ Unicode characters look nicer on displays that recognize them.
+
+ Sets the string to be printed in place of a null value.
+ The default is to print nothing, which can easily be mistaken for
+ an empty string. For example, one might prefer \pset null
+ '(null)'.
+
+ If value is specified
+ it must be either on or off
+ which will enable or disable display of a locale-specific character
+ to separate groups of digits to the left of the decimal marker.
+ If value is omitted the
+ command toggles between regular and locale-specific numeric output.
+
+ Controls use of a pager program for query and psql
+ help output.
+ When the pager option is off, the pager
+ program is not used. When the pager option is
+ on, the pager is used when appropriate, i.e., when the
+ output is to a terminal and will not fit on the screen.
+ The pager option can also be set to always,
+ which causes the pager to be used for all terminal output regardless
+ of whether it fits on the screen. \pset pager
+ without a value
+ toggles pager use on and off.
+
+ If the environment variable PSQL_PAGER
+ or PAGER is set, output to be paged is piped to the
+ specified program. Otherwise a platform-dependent default program
+ (such as more) is used.
+
+ When using the \watch command to execute a query
+ repeatedly, the environment variable PSQL_WATCH_PAGER
+ is used to find the pager program instead, on Unix systems. This is
+ configured separately because it may confuse traditional pagers, but
+ can be used to send output to tools that understand
+ psql's output format (such as
+ pspg --stream).
+
+ If pager_min_lines is set to a number greater than the
+ page height, the pager program will not be called unless there are
+ at least this many lines of output to show. The default setting
+ is 0.
+
+ In HTML format, this specifies attributes
+ to be placed inside the table tag. This
+ could for example be cellpadding or
+ bgcolor. Note that you probably don't want
+ to specify border here, as that is already
+ taken care of by \pset border.
+ If no
+ value is given,
+ the table attributes are unset.
+
+ In latex-longtable format, this controls
+ the proportional width of each column containing a left-aligned
+ data type. It is specified as a whitespace-separated list of values,
+ e.g., '0.2 0.2 0.6'. Unspecified output columns
+ use the last specified value.
+
+ Sets the table title for any subsequently printed tables. This
+ can be used to give your output descriptive tags. If no
+ value is given,
+ the title is unset.
+
+ If value is specified
+ it must be either on or off
+ which will enable or disable tuples-only mode.
+ If value is omitted the
+ command toggles between regular and tuples-only output.
+ Regular output includes extra information such
+ as column headers, titles, and various footers. In tuples-only
+ mode, only actual table data is shown.
+
+ Print psql's command line history
+ to filename.
+ If filename is omitted,
+ the history is written to the standard output (using the pager if
+ appropriate). This command is not available
+ if psql was built
+ without Readline support.
+
+ Sets the psql variable name to value, or if more than one value
+ is given, to the concatenation of all of them. If only one
+ argument is given, the variable is set to an empty-string value. To
+ unset a variable, use the \unset command.
+
\set without any arguments displays the names and values
+ of all currently-set psql variables.
+
+ Valid variable names can contain letters, digits, and
+ underscores. See Variables below for details.
+ Variable names are case-sensitive.
+
+ Certain variables are special, in that they
+ control psql's behavior or are
+ automatically set to reflect connection state. These variables are
+ documented in Variables, below.
+
Note
+ This command is unrelated to the SQL
+ command SET.
+
+ This command fetches and shows the definition of the named function or procedure,
+ in the form of a CREATE OR REPLACE FUNCTION or
+ CREATE OR REPLACE PROCEDURE command.
+ The definition is printed to the current query output channel,
+ as set by \o.
+
+ The target function can be specified by name alone, or by name
+ and arguments, for example foo(integer, text).
+ The argument types must be given if there is more
+ than one function of the same name.
+
+ If + is appended to the command name, then the
+ output lines are numbered, with the first line of the function body
+ being line 1.
+
+ Unlike most other meta-commands, the entire remainder of the line is
+ always taken to be the argument(s) of \sf, and neither
+ variable interpolation nor backquote expansion are performed in the
+ arguments.
+
+ This command fetches and shows the definition of the named view,
+ in the form of a CREATE OR REPLACE VIEW command.
+ The definition is printed to the current query output channel,
+ as set by \o.
+
+ If + is appended to the command name, then the
+ output lines are numbered from 1.
+
+ Unlike most other meta-commands, the entire remainder of the line is
+ always taken to be the argument(s) of \sv, and neither
+ variable interpolation nor backquote expansion are performed in the
+ arguments.
+
+ Toggles the display of output column name headings and row count
+ footer. This command is equivalent to \pset
+ tuples_only and is provided for convenience.
+
+ With a parameter, turns displaying of how long each SQL statement
+ takes on or off. Without a parameter, toggles the display between
+ on and off. The display is in milliseconds; intervals longer than
+ 1 second are also shown in minutes:seconds format, with hours and
+ days fields added if needed.
+
+ Most variables that control psql's behavior
+ cannot be unset; instead, an \unset command is interpreted
+ as setting them to their default values.
+ See Variables below.
+
+ Writes the current query buffer to the file filename or pipes it to the shell
+ command command.
+ If the current query buffer is empty, the most recently executed query
+ is written instead.
+
+ If the argument begins with |, then the entire remainder
+ of the line is taken to be
+ the command to execute,
+ and neither variable interpolation nor backquote expansion are
+ performed in it. The rest of the line is simply passed literally to
+ the shell.
+
+ Repeatedly execute the current query buffer (as \g does)
+ until interrupted, or the query fails, or the execution count limit
+ (if given) is reached. Wait the specified number of
+ seconds (default 2) between executions. For backwards compatibility,
+ seconds can be specified
+ with or without an interval= prefix.
+ Each query result is
+ displayed with a header that includes the \pset title
+ string (if any), the time as of query start, and the delay interval.
+
+ If the current query buffer is empty, the most recently sent query
+ is re-executed instead.
+
+ Lists tables, views and sequences with their
+ associated access privileges.
+ If a pattern is
+ specified, only tables, views and sequences whose names match the
+ pattern are listed. By default only user-created objects are shown;
+ supply a pattern or the S modifier to include
+ system objects.
+
+ This is an alias for \dp (“display
+ privileges”).
+
+ With no argument, escapes to a sub-shell; psql
+ resumes when the sub-shell exits. With an argument, executes the
+ shell command command.
+
+ Unlike most other meta-commands, the entire remainder of the line is
+ always taken to be the argument(s) of \!, and neither
+ variable interpolation nor backquote expansion are performed in the
+ arguments. The rest of the line is simply passed literally to the
+ shell.
+
+ Shows help information. The optional
+ topic parameter
+ (defaulting to commands) selects which part of psql is
+ explained: commands describes psql's
+ backslash commands; options describes the command-line
+ options that can be passed to psql;
+ and variables shows help about psql configuration
+ variables.
+
+ Backslash-semicolon is not a meta-command in the same way as the
+ preceding commands; rather, it simply causes a semicolon to be
+ added to the query buffer without any further processing.
+
+ Normally, psql will dispatch an SQL command to the
+ server as soon as it reaches the command-ending semicolon, even if
+ more input remains on the current line. Thus for example entering
+
+select 1; select 2; select 3;
+
+ will result in the three SQL commands being individually sent to
+ the server, with each one's results being displayed before
+ continuing to the next command. However, a semicolon entered
+ as \; will not trigger command processing, so that the
+ command before it and the one after are effectively combined and
+ sent to the server in one request. So for example
+
+select 1\; select 2\; select 3;
+
+ results in sending the three SQL commands to the server in a single
+ request, when the non-backslashed semicolon is reached.
+ The server executes such a request as a single transaction,
+ unless there are explicit BEGIN/COMMIT
+ commands included in the string to divide it into multiple
+ transactions. (See Section 55.2.2.1
+ for more details about how the server handles multi-query strings.)
+
+
Patterns
+ The various \d commands accept a pattern parameter to specify the
+ object name(s) to be displayed. In the simplest case, a pattern
+ is just the exact name of the object. The characters within a
+ pattern are normally folded to lower case, just as in SQL names;
+ for example, \dt FOO will display the table named
+ foo. As in SQL names, placing double quotes around
+ a pattern stops folding to lower case. Should you need to include
+ an actual double quote character in a pattern, write it as a pair
+ of double quotes within a double-quote sequence; again this is in
+ accord with the rules for SQL quoted identifiers. For example,
+ \dt "FOO""BAR" will display the table named
+ FOO"BAR (not foo"bar). Unlike the normal
+ rules for SQL names, you can put double quotes around just part
+ of a pattern, for instance \dt FOO"FOO"BAR will display
+ the table named fooFOObar.
+
+ Whenever the pattern parameter
+ is omitted completely, the \d commands display all objects
+ that are visible in the current schema search path — this is
+ equivalent to using * as the pattern.
+ (An object is said to be visible if its
+ containing schema is in the search path and no object of the same
+ kind and name appears earlier in the search path. This is equivalent to the
+ statement that the object can be referenced by name without explicit
+ schema qualification.)
+ To see all objects in the database regardless of visibility,
+ use *.* as the pattern.
+
+ Within a pattern, * matches any sequence of characters
+ (including no characters) and ? matches any single character.
+ (This notation is comparable to Unix shell file name patterns.)
+ For example, \dt int* displays tables whose names
+ begin with int. But within double quotes, *
+ and ? lose these special meanings and are just matched
+ literally.
+
+ A relation pattern that contains a dot (.) is interpreted as a schema
+ name pattern followed by an object name pattern. For example,
+ \dt foo*.*bar* displays all tables whose table name
+ includes bar that are in schemas whose schema name
+ starts with foo. When no dot appears, then the pattern
+ matches only objects that are visible in the current schema search path.
+ Again, a dot within double quotes loses its special meaning and is matched
+ literally. A relation pattern that contains two dots (.)
+ is interpreted as a database name followed by a schema name pattern followed
+ by an object name pattern. The database name portion will not be treated as
+ a pattern and must match the name of the currently connected database, else
+ an error will be raised.
+
+ A schema pattern that contains a dot (.) is interpreted
+ as a database name followed by a schema name pattern. For example,
+ \dn mydb.*foo* displays all schemas whose schema name
+ includes foo. The database name portion will not be
+ treated as a pattern and must match the name of the currently connected
+ database, else an error will be raised.
+
+ Advanced users can use regular-expression notations such as character
+ classes, for example [0-9] to match any digit. All regular
+ expression special characters work as specified in
+ Section 9.7.3, except for . which
+ is taken as a separator as mentioned above, * which is
+ translated to the regular-expression notation .*,
+ ? which is translated to ., and
+ $ which is matched literally. You can emulate
+ these pattern characters at need by writing
+ ? for .,
+ (R+|) for
+ R*, or
+ (R|) for
+ R?.
+ $ is not needed as a regular-expression character since
+ the pattern must match the whole name, unlike the usual
+ interpretation of regular expressions (in other words, $
+ is automatically appended to your pattern). Write * at the
+ beginning and/or end if you don't wish the pattern to be anchored.
+ Note that within double quotes, all regular expression special characters
+ lose their special meanings and are matched literally. Also, the regular
+ expression special characters are matched literally in operator name
+ patterns (i.e., the argument of \do).
+
Advanced Features
Variables
+ psql provides variable substitution
+ features similar to common Unix command shells.
+ Variables are simply name/value pairs, where the value
+ can be any string of any length. The name must consist of letters
+ (including non-Latin letters), digits, and underscores.
+
+ To set a variable, use the psql meta-command
+ \set. For example,
+
+testdb=> \set foo bar
+
+ sets the variable foo to the value
+ bar. To retrieve the content of the variable, precede
+ the name with a colon, for example:
+
+testdb=> \echo :foo
+bar
+
+ This works in both regular SQL commands and meta-commands; there is
+ more detail in SQL Interpolation, below.
+
+ If you call \set without a second argument, the
+ variable is set to an empty-string value. To unset (i.e., delete)
+ a variable, use the command \unset. To show the
+ values of all variables, call \set without any argument.
+
Note
+ The arguments of \set are subject to the same
+ substitution rules as with other commands. Thus you can construct
+ interesting references such as \set :foo
+ 'something' and get “soft links” or
+ “variable variables” of Perl
+ or PHP fame,
+ respectively. Unfortunately (or fortunately?), there is no way to do
+ anything useful with these constructs. On the other hand,
+ \set bar :foo is a perfectly valid way to copy a
+ variable.
+
+ A number of these variables are treated specially
+ by psql. They represent certain option
+ settings that can be changed at run time by altering the value of
+ the variable, or in some cases represent changeable state of
+ psql.
+ By convention, all specially treated variables' names
+ consist of all upper-case ASCII letters (and possibly digits and
+ underscores). To ensure maximum compatibility in the future, avoid
+ using such variable names for your own purposes.
+
+ Variables that control psql's behavior
+ generally cannot be unset or set to invalid values. An \unset
+ command is allowed but is interpreted as setting the variable to its
+ default value. A \set command without a second argument is
+ interpreted as setting the variable to on, for control
+ variables that accept that value, and is rejected for others. Also,
+ control variables that accept the values on
+ and off will also accept other common spellings of Boolean
+ values, such as true and false.
+
+ When on (the default), each SQL command is automatically
+ committed upon successful completion. To postpone commit in this
+ mode, you must enter a BEGIN or START
+ TRANSACTION SQL command. When off or unset, SQL
+ commands are not committed until you explicitly issue
+ COMMIT or END. The autocommit-off
+ mode works by issuing an implicit BEGIN for you, just
+ before any command that is not already in a transaction block and
+ is not itself a BEGIN or other transaction-control
+ command, nor a command that cannot be executed inside a transaction
+ block (such as VACUUM).
+
Note
+ In autocommit-off mode, you must explicitly abandon any failed
+ transaction by entering ABORT or ROLLBACK.
+ Also keep in mind that if you exit the session
+ without committing, your work will be lost.
+
Note
+ The autocommit-on mode is PostgreSQL's traditional
+ behavior, but autocommit-off is closer to the SQL spec. If you
+ prefer autocommit-off, you might wish to set it in the system-wide
+ psqlrc file or your
+ ~/.psqlrc file.
+
+ Determines which letter case to use when completing an SQL key word.
+ If set to lower or upper, the
+ completed word will be in lower or upper case, respectively. If set
+ to preserve-lower
+ or preserve-upper (the default), the completed word
+ will be in the case of the word already entered, but words being
+ completed without anything entered will be in lower or upper case,
+ respectively.
+
+ The name of the database you are currently connected to. This is
+ set every time you connect to a database (including program
+ start-up), but can be changed or unset.
+
+ If set to all, all nonempty input lines are printed
+ to standard output as they are read. (This does not apply to lines
+ read interactively.) To select this behavior on program
+ start-up, use the switch -a. If set to
+ queries,
+ psql prints each query to standard output
+ as it is sent to the server. The switch to select this behavior is
+ -e. If set to errors, then only
+ failed queries are displayed on standard error output. The switch
+ for this behavior is -b. If set to
+ none (the default), then no queries are displayed.
+
+ When this variable is set to on and a backslash command
+ queries the database, the query is first shown.
+ This feature helps you to study
+ PostgreSQL internals and provide
+ similar functionality in your own programs. (To select this behavior
+ on program start-up, use the switch -E.) If you set
+ this variable to the value noexec, the queries are
+ just shown but are not actually sent to the server and executed.
+ The default value is off.
+
+ The current client character set encoding.
+ This is set every time you connect to a database (including
+ program start-up), and when you change the encoding
+ with \encoding, but it can be changed or unset.
+
+ If this variable is set to an integer value greater than zero,
+ the results of SELECT queries are fetched
+ and displayed in groups of that many rows, rather than the
+ default behavior of collecting the entire result set before
+ display. Therefore only a
+ limited amount of memory is used, regardless of the size of
+ the result set. Settings of 100 to 1000 are commonly used
+ when enabling this feature.
+ Keep in mind that when using this feature, a query might
+ fail after having already displayed some rows.
+
Tip
+ Although you can use any output format with this feature,
+ the default aligned format tends to look bad
+ because each group of FETCH_COUNT rows
+ will be formatted separately, leading to varying column
+ widths across the row groups. The other output formats work better.
+
+ If this variable is set to ignorespace,
+ lines which begin with a space are not entered into the history
+ list. If set to a value of ignoredups, lines
+ matching the previous history line are not entered. A value of
+ ignoreboth combines the two options. If
+ set to none (the default), all lines
+ read in interactive mode are saved on the history list.
+
Note
+ This feature was shamelessly plagiarized from
+ Bash.
+
+ The file name that will be used to store the history list. If unset,
+ the file name is taken from the PSQL_HISTORY
+ environment variable. If that is not set either, the default
+ is ~/.psql_history,
+ or %APPDATA%\postgresql\psql_history on Windows.
+ For example, putting:
+
+\set HISTFILE ~/.psql_history-:DBNAME
+
+ in ~/.psqlrc will cause
+ psql to maintain a separate history for
+ each database.
+
Note
+ This feature was shamelessly plagiarized from
+ Bash.
+
+ The database server host you are currently connected to. This is
+ set every time you connect to a database (including program
+ start-up), but can be changed or unset.
+
+ If set to 1 or less, sending an EOF character (usually
+ Control+D)
+ to an interactive session of psql
+ will terminate the application. If set to a larger numeric value,
+ that many consecutive EOF characters must be typed to
+ make an interactive session terminate. If the variable is set to a
+ non-numeric value, it is interpreted as 10. The default is 0.
+
Note
+ This feature was shamelessly plagiarized from
+ Bash.
+
+ The value of the last affected OID, as returned from an
+ INSERT or \lo_import
+ command. This variable is only guaranteed to be valid until
+ after the result of the next SQL command has
+ been displayed.
+ PostgreSQL servers since version 12 do not
+ support OID system columns anymore, thus LASTOID will always be 0
+ following INSERT when targeting such servers.
+
+ The primary error message and associated SQLSTATE code for the most
+ recent failed query in the current psql session, or
+ an empty string and 00000 if no error has occurred in
+ the current session.
+
+ When set to on, if a statement in a transaction block
+ generates an error, the error is ignored and the transaction
+ continues. When set to interactive, such errors are only
+ ignored in interactive sessions, and not when reading script
+ files. When set to off (the default), a statement in a
+ transaction block that generates an error aborts the entire
+ transaction. The error rollback mode works by issuing an
+ implicit SAVEPOINT for you, just before each command
+ that is in a transaction block, and then rolling back to the
+ savepoint if the command fails.
+
+ By default, command processing continues after an error. When this
+ variable is set to on, processing will instead stop
+ immediately. In interactive mode,
+ psql will return to the command prompt;
+ otherwise, psql will exit, returning
+ error code 3 to distinguish this case from fatal error
+ conditions, which are reported using error code 1. In either case,
+ any currently running scripts (the top-level script, if any, and any
+ other scripts which it may have in invoked) will be terminated
+ immediately. If the top-level command string contained multiple SQL
+ commands, processing will stop with the current command.
+
+ The database server port to which you are currently connected.
+ This is set every time you connect to a database (including
+ program start-up), but can be changed or unset.
+
+ The server's version number as a string, for
+ example 9.6.2, 10.1 or 11beta1,
+ and in numeric form, for
+ example 90602 or 100001.
+ These are set every time you connect to a database
+ (including program start-up), but can be changed or unset.
+
+ true if the last shell command
+ failed, false if it succeeded.
+ This applies to shell commands invoked via the \!,
+ \g, \o, \w,
+ and \copy meta-commands, as well as backquote
+ (`) expansion. Note that
+ for \o, this variable is updated when the output
+ pipe is closed by the next \o command.
+ See also SHELL_EXIT_CODE.
+
+ The exit status returned by the last shell command.
+ 0–127 represent program exit codes, 128–255
+ indicate termination by a signal, and -1 indicates failure
+ to launch a program or to collect its exit status.
+ This applies to shell commands invoked via the \!,
+ \g, \o, \w,
+ and \copy meta-commands, as well as backquote
+ (`) expansion. Note that
+ for \o, this variable is updated when the output
+ pipe is closed by the next \o command.
+ See also SHELL_ERROR.
+
+ When this variable is set to off, only the last
+ result of a combined query (\;) is shown instead of
+ all of them. The default is on. The off behavior
+ is for compatibility with older versions of psql.
+
+ This variable can be set to the
+ values never, errors, or always
+ to control whether CONTEXT fields are displayed in
+ messages from the server. The default is errors (meaning
+ that context will be shown in error messages, but not in notice or
+ warning messages). This setting has no effect
+ when VERBOSITY is set to terse
+ or sqlstate.
+ (See also \errverbose, for use when you want a verbose
+ version of the error you just got.)
+
+ The database user you are currently connected as. This is set
+ every time you connect to a database (including program
+ start-up), but can be changed or unset.
+
+ This variable can be set to the values default,
+ verbose, terse,
+ or sqlstate to control the verbosity of error
+ reports.
+ (See also \errverbose, for use when you want a verbose
+ version of the error you just got.)
+
+ These variables are set at program start-up to reflect
+ psql's version, respectively as a verbose string,
+ a short string (e.g., 9.6.2, 10.1,
+ or 11beta1), and a number (e.g., 90602
+ or 100001). They can be changed or unset.
+
SQL Interpolation
+ A key feature of psql
+ variables is that you can substitute (“interpolate”)
+ them into regular SQL statements, as well as the
+ arguments of meta-commands. Furthermore,
+ psql provides facilities for
+ ensuring that variable values used as SQL literals and identifiers are
+ properly quoted. The syntax for interpolating a value without
+ any quoting is to prepend the variable name with a colon
+ (:). For example,
+
+testdb=> \set foo 'my_table'
+testdb=> SELECT * FROM :foo;
+
+ would query the table my_table. Note that this
+ may be unsafe: the value of the variable is copied literally, so it can
+ contain unbalanced quotes, or even backslash commands. You must make sure
+ that it makes sense where you put it.
+
+ When a value is to be used as an SQL literal or identifier, it is
+ safest to arrange for it to be quoted. To quote the value of
+ a variable as an SQL literal, write a colon followed by the variable
+ name in single quotes. To quote the value as an SQL identifier, write
+ a colon followed by the variable name in double quotes.
+ These constructs deal correctly with quotes and other special
+ characters embedded within the variable value.
+ The previous example would be more safely written this way:
+
+testdb=> \set foo 'my_table'
+testdb=> SELECT * FROM :"foo";
+
+
+ Variable interpolation will not be performed within quoted
+ SQL literals and identifiers. Therefore, a
+ construction such as ':foo' doesn't work to produce a quoted
+ literal from a variable's value (and it would be unsafe if it did work,
+ since it wouldn't correctly handle quotes embedded in the value).
+
+ One example use of this mechanism is to
+ copy the contents of a file into a table column.
+ First load the file into a variable and then interpolate the variable's
+ value as a quoted string:
+
+ (Note that this still won't work if my_file.txt contains NUL bytes.
+ psql does not support embedded NUL bytes in variable values.)
+
+ Since colons can legally appear in SQL commands, an apparent attempt
+ at interpolation (that is, :name,
+ :'name', or :"name") is not
+ replaced unless the named variable is currently set. In any case, you
+ can escape a colon with a backslash to protect it from substitution.
+
+ The :{?name} special syntax returns TRUE
+ or FALSE depending on whether the variable exists or not, and is thus
+ always substituted, unless the colon is backslash-escaped.
+
+ The colon syntax for variables is standard SQL for
+ embedded query languages, such as ECPG.
+ The colon syntaxes for array slices and type casts are
+ PostgreSQL extensions, which can sometimes
+ conflict with the standard usage. The colon-quote syntax for escaping a
+ variable's value as an SQL literal or identifier is a
+ psql extension.
+
Prompting
+ The prompts psql issues can be customized
+ to your preference. The three variables PROMPT1,
+ PROMPT2, and PROMPT3 contain strings
+ and special escape sequences that describe the appearance of the
+ prompt. Prompt 1 is the normal prompt that is issued when
+ psql requests a new command. Prompt 2 is
+ issued when more input is expected during command entry, for example
+ because the command was not terminated with a semicolon or a quote
+ was not closed.
+ Prompt 3 is issued when you are running an SQL
+ COPY FROM STDIN command and you need to type in
+ a row value on the terminal.
+
+ The value of the selected prompt variable is printed literally,
+ except where a percent sign (%) is encountered.
+ Depending on the next character, certain other text is substituted
+ instead. Defined substitutions are:
+
+
+ The full host name (with domain name) of the database server,
+ or [local] if the connection is over a Unix
+ domain socket, or
+ [local:/dir/name],
+ if the Unix domain socket is not at the compiled in default
+ location.
+
+ The database session user name. (The expansion of this
+ value might change during a database session as the result
+ of the command SET SESSION
+ AUTHORIZATION.)
+
+ If the session user is a database superuser, then a
+ #, otherwise a >.
+ (The expansion of this value might change during a database
+ session as the result of the command SET SESSION
+ AUTHORIZATION.)
+
+ In prompt 1 normally =,
+ but @ if the session is in an inactive branch of a
+ conditional block, or ^ if in single-line mode,
+ or ! if the session is disconnected from the
+ database (which can happen if \connect fails).
+ In prompt 2 %R is replaced by a character that
+ depends on why psql expects more input:
+ - if the command simply wasn't terminated yet,
+ but * if there is an unfinished
+ /* ... */ comment,
+ a single quote if there is an unfinished quoted string,
+ a double quote if there is an unfinished quoted identifier,
+ a dollar sign if there is an unfinished dollar-quoted string,
+ or ( if there is an unmatched left parenthesis.
+ In prompt 3 %R doesn't produce anything.
+
+ Transaction status: an empty string when not in a transaction
+ block, or * when in a transaction block, or
+ ! when in a failed transaction block, or ?
+ when the transaction state is indeterminate (for example, because
+ there is no connection).
+
+ Prompts can contain terminal control characters which, for
+ example, change the color, background, or style of the prompt
+ text, or change the title of the terminal window. In order for
+ the line editing features of Readline to work properly, these
+ non-printing control characters must be designated as invisible
+ by surrounding them with %[ and
+ %]. Multiple pairs of these can occur within
+ the prompt. For example:
+
+ Whitespace of the same width as the most recent output of
+ PROMPT1. This can be used as a
+ PROMPT2 setting, so that multi-line statements are
+ aligned with the first line, but there is no visible secondary prompt.
+
+
+ To insert a percent sign into your prompt, write
+ %%. The default prompts are
+ '%/%R%x%# ' for prompts 1 and 2, and
+ '>> ' for prompt 3.
+
Note
+ This feature was shamelessly plagiarized from
+ tcsh.
+
Command-Line Editing
+ psql uses
+ the Readline
+ or libedit library, if available, for
+ convenient line editing and retrieval. The command history is
+ automatically saved when psql exits and is
+ reloaded when psql starts up. Type
+ up-arrow or control-P to retrieve previous lines.
+
+ You can also use tab completion to fill in partially-typed keywords
+ and SQL object names in many (by no means all) contexts. For example,
+ at the start of a command, typing ins and pressing
+ TAB will fill in insert into . Then, typing a few
+ characters of a table or schema name and pressing TAB
+ will fill in the unfinished name, or offer a menu of possible completions
+ when there's more than one. (Depending on the library in use, you may need to
+ press TAB more than once to get a menu.)
+
+ Tab completion for SQL object names requires sending queries to the
+ server to find possible matches. In some contexts this can interfere
+ with other operations. For example, after BEGIN
+ it will be too late to issue SET TRANSACTION ISOLATION
+ LEVEL if a tab-completion query is issued in between.
+ If you do not want tab completion at all, you
+ can turn it off permanently by putting this in a file named
+ .inputrc in your home directory:
+
+$if psql
+set disable-completion on
+$endif
+
+ (This is not a psql but a
+ Readline feature. Read its documentation
+ for further details.)
+
+ The -n (--no-readline) command line
+ option can also be useful to disable use
+ of Readline for a single run
+ of psql. This prevents tab completion,
+ use or recording of command line history, and editing of multi-line
+ commands. It is particularly useful when you need to copy-and-paste
+ text that contains TAB characters.
+
+ If \pset columns is zero, controls the
+ width for the wrapped format and width for determining
+ if wide output requires the pager or should be switched to the
+ vertical format in expanded auto mode.
+
+ Editor used by the \e, \ef,
+ and \ev commands.
+ These variables are examined in the order listed;
+ the first that is set is used.
+ If none of them is set, the default is to use vi
+ on Unix systems or notepad.exe on Windows systems.
+
+ When \e, \ef, or
+ \ev is used
+ with a line number argument, this variable specifies the
+ command-line argument used to pass the starting line number to
+ the user's editor. For editors such as Emacs or
+ vi, this is a plus sign. Include a trailing
+ space in the value of the variable if there needs to be space
+ between the option name and the line number. Examples:
+
+ The default is + on Unix systems
+ (corresponding to the default editor vi,
+ and useful for many other common editors); but there is no
+ default on Windows systems.
+
+ If a query's results do not fit on the screen, they are piped
+ through this command. Typical values are more
+ or less.
+ Use of the pager can be disabled by setting PSQL_PAGER
+ or PAGER to an empty string, or by adjusting the
+ pager-related options of the \pset command.
+ These variables are examined in the order listed;
+ the first that is set is used.
+ If neither of them is set, the default is to use more on most
+ platforms, but less on Cygwin.
+
+ When a query is executed repeatedly with the \watch
+ command, a pager is not used by default. This behavior can be changed
+ by setting PSQL_WATCH_PAGER to a pager command, on Unix
+ systems. The pspg pager (not part of
+ PostgreSQL but available in many open source
+ software distributions) can display the output of
+ \watch if started with the option
+ --stream.
+
+ Unless it is passed an -X option,
+ psql attempts to read and execute commands
+ from the system-wide startup file (psqlrc) and then
+ the user's personal startup file (~/.psqlrc), after
+ connecting to the database but before accepting normal commands.
+ These files can be used to set up the client and/or the server to taste,
+ typically with \set and SET
+ commands.
+
+ The system-wide startup file is named psqlrc.
+ By default it is
+ sought in the installation's “system configuration” directory,
+ which is most reliably identified by running pg_config
+ --sysconfdir.
+ Typically this directory will be ../etc/
+ relative to the directory containing
+ the PostgreSQL executables.
+ The directory to look in can be set explicitly via
+ the PGSYSCONFDIR environment variable.
+
+ The user's personal startup file is named .psqlrc
+ and is sought in the invoking user's home directory.
+ On Windows the personal startup file is instead named
+ %APPDATA%\postgresql\psqlrc.conf.
+ In either case, this default file path can be overridden by setting
+ the PSQLRC environment variable.
+
+ Both the system-wide startup file and the user's personal startup file
+ can be made psql-version-specific
+ by appending a dash and the PostgreSQL
+ major or minor release identifier to the file name,
+ for example ~/.psqlrc-16 or
+ ~/.psqlrc-16.3.
+ The most specific version-matching file will be read in preference
+ to a non-version-specific file.
+ These version suffixes are added after determining the file path
+ as explained above.
+
+ The command-line history is stored in the file
+ ~/.psql_history, or
+ %APPDATA%\postgresql\psql_history on Windows.
+
+ The location of the history file can be set explicitly via
+ the HISTFILEpsql variable or
+ the PSQL_HISTORY environment variable.
+
Notes
psql works best with servers of the same
+ or an older major version. Backslash commands are particularly likely
+ to fail if the server is of a newer version than psql
+ itself. However, backslash commands of the \d family should
+ work with servers of versions back to 9.2, though not necessarily with
+ servers newer than psql itself. The general
+ functionality of running SQL commands and displaying query results
+ should also work with servers of a newer major version, but this cannot
+ be guaranteed in all cases.
+
+ If you want to use psql to connect to several
+ servers of different major versions, it is recommended that you use the
+ newest version of psql. Alternatively, you
+ can keep around a copy of psql from each
+ major version and be sure to use the version that matches the
+ respective server. But in practice, this additional complication should
+ not be necessary.
+
+ Before PostgreSQL 9.6,
+ the -c option implied -X
+ (--no-psqlrc); this is no longer the case.
+
+ Before PostgreSQL 8.4,
+ psql allowed the
+ first argument of a single-letter backslash command to start
+ directly after the command, without intervening whitespace.
+ Now, some whitespace is required.
+
Notes for Windows Users
+ psql is built as a “console
+ application”. Since the Windows console windows use a different
+ encoding than the rest of the system, you must take special care
+ when using 8-bit characters within psql.
+ If psql detects a problematic
+ console code page, it will warn you at startup. To change the
+ console code page, two things are necessary:
+
+
+ Set the code page by entering cmd.exe /c chcp
+ 1252. (1252 is a code page that is appropriate for
+ German; replace it with your value.) If you are using Cygwin,
+ you can put this command in /etc/profile.
+
+ Set the console font to Lucida Console, because the
+ raster font does not work with the ANSI code page.
+
Examples
+ The first example shows how to spread a command over several lines of
+ input. Notice the changing prompt:
+
+testdb=> CREATE TABLE my_table (
+testdb(> first integer not null default 0,
+testdb(> second text)
+testdb-> ;
+CREATE TABLE
+
+ Now look at the table definition again:
+
+testdb=> \d my_table
+ Table "public.my_table"
+ Column | Type | Collation | Nullable | Default
+--------+---------+-----------+----------+---------
+ first | integer | | not null | 0
+ second | text | | |
+
+ Now we change the prompt to something more interesting:
+
+ Let's assume you have filled the table with data and want to take a
+ look at it:
+
+peter@localhost testdb=> SELECT * FROM my_table;
+ first | second
+-------+--------
+ 1 | one
+ 2 | two
+ 3 | three
+ 4 | four
+(4 rows)
+
+ You can display tables in different ways by using the
+ \pset command:
+
+peter@localhost testdb=> \pset border 2
+Border style is 2.
+peter@localhost testdb=> SELECT * FROM my_table;
++-------+--------+
+| first | second |
++-------+--------+
+| 1 | one |
+| 2 | two |
+| 3 | three |
+| 4 | four |
++-------+--------+
+(4 rows)
+
+peter@localhost testdb=> \pset border 0
+Border style is 0.
+peter@localhost testdb=> SELECT * FROM my_table;
+first second
+----- ------
+ 1 one
+ 2 two
+ 3 three
+ 4 four
+(4 rows)
+
+peter@localhost testdb=> \pset border 1
+Border style is 1.
+peter@localhost testdb=> \pset format csv
+Output format is csv.
+peter@localhost testdb=> \pset tuples_only
+Tuples only is on.
+peter@localhost testdb=> SELECT second, first FROM my_table;
+one,1
+two,2
+three,3
+four,4
+peter@localhost testdb=> \pset format unaligned
+Output format is unaligned.
+peter@localhost testdb=> \pset fieldsep '\t'
+Field separator is " ".
+peter@localhost testdb=> SELECT second, first FROM my_table;
+one 1
+two 2
+three 3
+four 4
+
+ Alternatively, use the short commands:
+
+peter@localhost testdb=> \a \t \x
+Output format is aligned.
+Tuples only is off.
+Expanded display is on.
+peter@localhost testdb=> SELECT * FROM my_table;
+-[ RECORD 1 ]-
+first | 1
+second | one
+-[ RECORD 2 ]-
+first | 2
+second | two
+-[ RECORD 3 ]-
+first | 3
+second | three
+-[ RECORD 4 ]-
+first | 4
+second | four
+
+
+ Also, these output format options can be set for just one query by using
+ \g:
+
+peter@localhost testdb=> SELECT * FROM my_table
+peter@localhost testdb-> \g (format=aligned tuples_only=off expanded=on)
+-[ RECORD 1 ]-
+first | 1
+second | one
+-[ RECORD 2 ]-
+first | 2
+second | two
+-[ RECORD 3 ]-
+first | 3
+second | three
+-[ RECORD 4 ]-
+first | 4
+second | four
+
+
+ Here is an example of using the \df command to
+ find only functions with names matching int*pl
+ and whose second argument is of type bigint:
+
+testdb=> \df int*pl * bigint
+ List of functions
+ Schema | Name | Result data type | Argument data types | Type
+------------+---------+------------------+---------------------+------
+ pg_catalog | int28pl | bigint | smallint, bigint | func
+ pg_catalog | int48pl | bigint | integer, bigint | func
+ pg_catalog | int8pl | bigint | bigint, bigint | func
+(3 rows)
+
+
+ When suitable, query results can be shown in a crosstab representation
+ with the \crosstabview command:
+
+testdb=> SELECT first, second, first > 2 AS gt2 FROM my_table;
+ first | second | gt2
+-------+--------+-----
+ 1 | one | f
+ 2 | two | f
+ 3 | three | t
+ 4 | four | t
+(4 rows)
+
+testdb=> \crosstabview first second
+ first | one | two | three | four
+-------+-----+-----+-------+------
+ 1 | f | | |
+ 2 | | f | |
+ 3 | | | t |
+ 4 | | | | t
+(4 rows)
+
+
+This second example shows a multiplication table with rows sorted in reverse
+numerical order and columns with an independent, ascending numerical order.
+
+testdb=> SELECT t1.first as "A", t2.first+100 AS "B", t1.first*(t2.first+100) as "AxB",
+testdb(> row_number() over(order by t2.first) AS ord
+testdb(> FROM my_table t1 CROSS JOIN my_table t2 ORDER BY 1 DESC
+testdb(> \crosstabview "A" "B" "AxB" ord
+ A | 101 | 102 | 103 | 104
+---+-----+-----+-----+-----
+ 4 | 404 | 408 | 412 | 416
+ 3 | 303 | 306 | 309 | 312
+ 2 | 202 | 204 | 206 | 208
+ 1 | 101 | 102 | 103 | 104
+(4 rows)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-reindexdb.html b/pgsql/doc/postgresql/html/app-reindexdb.html
new file mode 100644
index 0000000000000000000000000000000000000000..3e71ef42cf20a1c50f557fa3502cb5b75f4907ea
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-reindexdb.html
@@ -0,0 +1,164 @@
+
+reindexdb
+ reindexdb is a utility for rebuilding indexes
+ in a PostgreSQL database.
+
+ reindexdb is a wrapper around the SQL
+ command REINDEX.
+ There is no effective difference between reindexing databases via
+ this utility and via other methods for accessing the server.
+
Options
+ reindexdb accepts the following command-line arguments:
+
+
-a --all
+ Reindex all databases.
+
--concurrently
+ Use the CONCURRENTLY option. See
+ REINDEX, where all the caveats of this option
+ are explained in detail.
+
[-d] dbname [--dbname=]dbname
+ Specifies the name of the database to be reindexed,
+ when -a/--all is not used.
+ If this is not specified, the database name is read
+ from the environment variable PGDATABASE. If
+ that is not set, the user name specified for the connection is
+ used. The dbname can be a connection string. If so,
+ connection string parameters will override any conflicting command
+ line options.
+
-e --echo
+ Echo the commands that reindexdb generates
+ and sends to the server.
+
-i index --index=index
+ Recreate index only.
+ Multiple indexes can be recreated by writing multiple
+ -i switches.
+
-j njobs --jobs=njobs
+ Execute the reindex commands in parallel by running
+ njobs
+ commands simultaneously. This option may reduce the processing time
+ but it also increases the load on the database server.
+
+ reindexdb will open
+ njobs connections to the
+ database, so make sure your max_connections
+ setting is high enough to accommodate all connections.
+
+ Note that this option is incompatible with the --index
+ and --system options.
+
-q --quiet
+ Do not display progress messages.
+
-s --system
+ Reindex database's system catalogs only.
+
-S schema --schema=schema
+ Reindex schema only.
+ Multiple schemas can be reindexed by writing multiple
+ -S switches.
+
-t table --table=table
+ Reindex table only.
+ Multiple tables can be reindexed by writing multiple
+ -t switches.
+
--tablespace=tablespace
+ Specifies the tablespace where indexes are rebuilt. (This name is
+ processed as a double-quoted identifier.)
+
-v --verbose
+ Print detailed information during processing.
+
-V --version
+ Print the reindexdb version and exit.
+
-? --help
+ Show help about reindexdb command line
+ arguments, and exit.
+
+
+
+ reindexdb also accepts
+ the following command-line arguments for connection parameters:
+
+
-h host --host=host
+ Specifies the host name of the machine on which the server is
+ running. If the value begins with a slash, it is used as the
+ directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server
+ is listening for connections.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force reindexdb to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ reindexdb will automatically prompt
+ for a password if the server demands password authentication.
+ However, reindexdb will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--maintenance-db=dbname
+ Specifies the name of the database to connect to to discover which
+ databases should be reindexed,
+ when -a/--all is used.
+ If not specified, the postgres database will be used,
+ or if that does not exist, template1 will be used.
+ This can be a connection
+ string. If so, connection string parameters will override any
+ conflicting command line options. Also, connection string parameters
+ other than the database name itself will be re-used when connecting
+ to other databases.
+
+
Environment
PGDATABASE PGHOST PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see REINDEX
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Notes
+ reindexdb might need to connect several
+ times to the PostgreSQL server, asking
+ for a password each time. It is convenient to have a
+ ~/.pgpass file in such cases. See Section 34.16 for more information.
+
Examples
+ To reindex the database test:
+
+$ reindexdb test
+
+
+ To reindex the table foo and the index
+ bar in a database named abcd:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/app-vacuumdb.html b/pgsql/doc/postgresql/html/app-vacuumdb.html
new file mode 100644
index 0000000000000000000000000000000000000000..07e53fd1e280d9d673acb173afc1a983461b2798
--- /dev/null
+++ b/pgsql/doc/postgresql/html/app-vacuumdb.html
@@ -0,0 +1,252 @@
+
+vacuumdb
vacuumdb [connection-option...] [option...] -a | --all
Description
+ vacuumdb is a utility for cleaning a
+ PostgreSQL database.
+ vacuumdb will also generate internal statistics
+ used by the PostgreSQL query optimizer.
+
+ vacuumdb is a wrapper around the SQL
+ command VACUUM.
+ There is no effective difference between vacuuming and analyzing
+ databases via this utility and via other methods for accessing the
+ server.
+
Options
+ vacuumdb accepts the following command-line arguments:
+
-a --all
+ Vacuum all databases.
+
--buffer-usage-limit size
+ Specifies the
+ Buffer Access Strategy
+ ring buffer size for a given invocation of vacuumdb.
+ This size is used to calculate the number of shared buffers which will
+ be reused as part of this strategy. See VACUUM.
+
[-d] dbname [--dbname=]dbname
+ Specifies the name of the database to be cleaned or analyzed,
+ when -a/--all is not used.
+ If this is not specified, the database name is read
+ from the environment variable PGDATABASE. If
+ that is not set, the user name specified for the connection is
+ used. The dbname can be a connection string. If so,
+ connection string parameters will override any conflicting command
+ line options.
+
--disable-page-skipping
+ Disable skipping pages based on the contents of the visibility map.
+
-e --echo
+ Echo the commands that vacuumdb generates
+ and sends to the server.
+
-f --full
+ Perform “full” vacuuming.
+
-F --freeze
+ Aggressively “freeze” tuples.
+
--force-index-cleanup
+ Always remove index entries pointing to dead tuples.
+
-j njobs --jobs=njobs
+ Execute the vacuum or analyze commands in parallel by running
+ njobs
+ commands simultaneously. This option may reduce the processing time
+ but it also increases the load on the database server.
+
+ vacuumdb will open
+ njobs connections to the
+ database, so make sure your max_connections
+ setting is high enough to accommodate all connections.
+
+ Note that using this mode together with the -f
+ (FULL) option might cause deadlock failures if
+ certain system catalogs are processed in parallel.
+
--min-mxid-age mxid_age
+ Only execute the vacuum or analyze commands on tables with a multixact
+ ID age of at least mxid_age.
+ This setting is useful for prioritizing tables to process to prevent
+ multixact ID wraparound (see
+ Section 25.1.5.1).
+
+ For the purposes of this option, the multixact ID age of a relation is
+ the greatest of the ages of the main relation and its associated
+ TOAST table, if one exists. Since the commands
+ issued by vacuumdb will also process the
+ TOAST table for the relation if necessary, it does
+ not need to be considered separately.
+
--min-xid-age xid_age
+ Only execute the vacuum or analyze commands on tables with a
+ transaction ID age of at least
+ xid_age. This setting
+ is useful for prioritizing tables to process to prevent transaction
+ ID wraparound (see Section 25.1.5).
+
+ For the purposes of this option, the transaction ID age of a relation
+ is the greatest of the ages of the main relation and its associated
+ TOAST table, if one exists. Since the commands
+ issued by vacuumdb will also process the
+ TOAST table for the relation if necessary, it does
+ not need to be considered separately.
+
-n schema --schema=schema
+ Clean or analyze all tables in
+ schema only. Multiple
+ schemas can be vacuumed by writing multiple -n switches.
+
-N schema --exclude-schema=schema
+ Do not clean or analyze any tables in
+ schema. Multiple schemas
+ can be excluded by writing multiple -N switches.
+
--no-index-cleanup
+ Do not remove index entries pointing to dead tuples.
+
--no-process-main
+ Skip the main relation.
+
--no-process-toast
+ Skip the TOAST table associated with the table to vacuum, if any.
+
--no-truncate
+ Do not truncate empty pages at the end of the table.
+
-P parallel_workers --parallel=parallel_workers
+ Specify the number of parallel workers for parallel vacuum.
+ This allows the vacuum to leverage multiple CPUs to process indexes.
+ See VACUUM.
+
-q --quiet
+ Do not display progress messages.
+
--skip-locked
+ Skip relations that cannot be immediately locked for processing.
+
+ Clean or analyze table only.
+ Column names can be specified only in conjunction with
+ the --analyze or --analyze-only options.
+ Multiple tables can be vacuumed by writing multiple
+ -t switches.
+
Tip
+ If you specify columns, you probably have to escape the parentheses
+ from the shell. (See examples below.)
+
-v --verbose
+ Print detailed information during processing.
+
-V --version
+ Print the vacuumdb version and exit.
+
-z --analyze
+ Also calculate statistics for use by the optimizer.
+
-Z --analyze-only
+ Only calculate statistics for use by the optimizer (no vacuum).
+
--analyze-in-stages
+ Only calculate statistics for use by the optimizer (no vacuum),
+ like --analyze-only. Run three
+ stages of analyze; the first stage uses the lowest possible statistics
+ target (see default_statistics_target)
+ to produce usable statistics faster, and subsequent stages build the
+ full statistics.
+
+ This option is only useful to analyze a database that currently has
+ no statistics or has wholly incorrect ones, such as if it is newly
+ populated from a restored dump or by pg_upgrade.
+ Be aware that running with this option in a database with existing
+ statistics may cause the query optimizer choices to become
+ transiently worse due to the low statistics targets of the early
+ stages.
+
-? --help
+ Show help about vacuumdb command line
+ arguments, and exit.
+
+
+ vacuumdb also accepts
+ the following command-line arguments for connection parameters:
+
-h host --host=host
+ Specifies the host name of the machine on which the server
+ is running. If the value begins with a slash, it is used
+ as the directory for the Unix domain socket.
+
-p port --port=port
+ Specifies the TCP port or local Unix domain socket file
+ extension on which the server
+ is listening for connections.
+
-U username --username=username
+ User name to connect as.
+
-w --no-password
+ Never issue a password prompt. If the server requires
+ password authentication and a password is not available by
+ other means such as a .pgpass file, the
+ connection attempt will fail. This option can be useful in
+ batch jobs and scripts where no user is present to enter a
+ password.
+
-W --password
+ Force vacuumdb to prompt for a
+ password before connecting to a database.
+
+ This option is never essential, since
+ vacuumdb will automatically prompt
+ for a password if the server demands password authentication.
+ However, vacuumdb will waste a
+ connection attempt finding out that the server wants a password.
+ In some cases it is worth typing -W to avoid the extra
+ connection attempt.
+
--maintenance-db=dbname
+ Specifies the name of the database to connect to to discover which
+ databases should be vacuumed,
+ when -a/--all is used.
+ If not specified, the postgres database will be used,
+ or if that does not exist, template1 will be used.
+ This can be a connection
+ string. If so, connection string parameters will override any
+ conflicting command line options. Also, connection string parameters
+ other than the database name itself will be re-used when connecting
+ to other databases.
+
+
Environment
PGDATABASE PGHOST PGPORT PGUSER
+ Default connection parameters
+
PG_COLOR
+ Specifies whether to use color in diagnostic messages. Possible values
+ are always, auto and
+ never.
+
+ This utility, like most other PostgreSQL utilities,
+ also uses the environment variables supported by libpq
+ (see Section 34.15).
+
Diagnostics
+ In case of difficulty, see VACUUM
+ and psql for
+ discussions of potential problems and error messages.
+ The database server must be running at the
+ targeted host. Also, any default connection settings and environment
+ variables used by the libpq front-end
+ library will apply.
+
Notes
+ vacuumdb might need to connect several
+ times to the PostgreSQL server, asking
+ for a password each time. It is convenient to have a
+ ~/.pgpass file in such cases. See Section 34.16 for more information.
+
Examples
+ To clean the database test:
+
+$ vacuumdb test
+
+
+ To clean and analyze for the optimizer a database named
+ bigdb:
+
+$ vacuumdb --analyze bigdb
+
+
+ To clean a single table
+ foo in a database named
+ xyzzy, and analyze a single column
+ bar of the table for the optimizer:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/appendix-obsolete.html b/pgsql/doc/postgresql/html/appendix-obsolete.html
new file mode 100644
index 0000000000000000000000000000000000000000..c0cde26240631ab0c00345642904c2963e2cd8c6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/appendix-obsolete.html
@@ -0,0 +1,8 @@
+
+Appendix O. Obsolete or Renamed Features
+ Functionality is sometimes removed from PostgreSQL, feature, setting
+ and file names sometimes change, or documentation moves to different
+ places. This section directs users coming from old versions of the
+ documentation or from external links to the appropriate new location
+ for the information they need.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/appendixes.html b/pgsql/doc/postgresql/html/appendixes.html
new file mode 100644
index 0000000000000000000000000000000000000000..b8829f60b9fd9745059e078137967c00258852a4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/appendixes.html
@@ -0,0 +1,10 @@
+
+Part VIII. Appendixes
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/applevel-consistency.html b/pgsql/doc/postgresql/html/applevel-consistency.html
new file mode 100644
index 0000000000000000000000000000000000000000..9ffcf2fcc9dcd03c86a8a4f3f68d5a0c14f5dd3d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/applevel-consistency.html
@@ -0,0 +1,115 @@
+
+13.4. Data Consistency Checks at the Application Level
13.4. Data Consistency Checks at the Application Level
+ It is very difficult to enforce business rules regarding data integrity
+ using Read Committed transactions because the view of the data is
+ shifting with each statement, and even a single statement may not
+ restrict itself to the statement's snapshot if a write conflict occurs.
+
+ While a Repeatable Read transaction has a stable view of the data
+ throughout its execution, there is a subtle issue with using
+ MVCC snapshots for data consistency checks, involving
+ something known as read/write conflicts.
+ If one transaction writes data and a concurrent transaction attempts
+ to read the same data (whether before or after the write), it cannot
+ see the work of the other transaction. The reader then appears to have
+ executed first regardless of which started first or which committed
+ first. If that is as far as it goes, there is no problem, but
+ if the reader also writes data which is read by a concurrent transaction
+ there is now a transaction which appears to have run before either of
+ the previously mentioned transactions. If the transaction which appears
+ to have executed last actually commits first, it is very easy for a
+ cycle to appear in a graph of the order of execution of the transactions.
+ When such a cycle appears, integrity checks will not work correctly
+ without some help.
+
+ As mentioned in Section 13.2.3, Serializable
+ transactions are just Repeatable Read transactions which add
+ nonblocking monitoring for dangerous patterns of read/write conflicts.
+ When a pattern is detected which could cause a cycle in the apparent
+ order of execution, one of the transactions involved is rolled back to
+ break the cycle.
+
13.4.1. Enforcing Consistency with Serializable Transactions #
+ If the Serializable transaction isolation level is used for all writes
+ and for all reads which need a consistent view of the data, no other
+ effort is required to ensure consistency. Software from other
+ environments which is written to use serializable transactions to
+ ensure consistency should “just work” in this regard in
+ PostgreSQL.
+
+ When using this technique, it will avoid creating an unnecessary burden
+ for application programmers if the application software goes through a
+ framework which automatically retries transactions which are rolled
+ back with a serialization failure. It may be a good idea to set
+ default_transaction_isolation to serializable.
+ It would also be wise to take some action to ensure that no other
+ transaction isolation level is used, either inadvertently or to
+ subvert integrity checks, through checks of the transaction isolation
+ level in triggers.
+
Warning: Serializable Transactions and Data Replication
+ This level of integrity protection using Serializable transactions
+ does not yet extend to hot standby mode (Section 27.4)
+ or logical replicas.
+ Because of that, those using hot standby or logical replication
+ may want to use Repeatable Read and explicit locking on the primary.
+
13.4.2. Enforcing Consistency with Explicit Blocking Locks #
+ When non-serializable writes are possible,
+ to ensure the current validity of a row and protect it against
+ concurrent updates one must use SELECT FOR UPDATE,
+ SELECT FOR SHARE, or an appropriate LOCK
+ TABLE statement. (SELECT FOR UPDATE
+ and SELECT FOR SHARE lock just the
+ returned rows against concurrent updates, while LOCK
+ TABLE locks the whole table.) This should be taken into
+ account when porting applications to
+ PostgreSQL from other environments.
+
+ Also of note to those converting from other environments is the fact
+ that SELECT FOR UPDATE does not ensure that a
+ concurrent transaction will not update or delete a selected row.
+ To do that in PostgreSQL you must actually
+ update the row, even if no values need to be changed.
+ SELECT FOR UPDATEtemporarily blocks
+ other transactions from acquiring the same lock or executing an
+ UPDATE or DELETE which would
+ affect the locked row, but once the transaction holding this lock
+ commits or rolls back, a blocked transaction will proceed with the
+ conflicting operation unless an actual UPDATE of
+ the row was performed while the lock was held.
+
+ Global validity checks require extra thought under
+ non-serializable MVCC.
+ For example, a banking application might wish to check that the sum of
+ all credits in one table equals the sum of debits in another table,
+ when both tables are being actively updated. Comparing the results of two
+ successive SELECT sum(...) commands will not work reliably in
+ Read Committed mode, since the second query will likely include the results
+ of transactions not counted by the first. Doing the two sums in a
+ single repeatable read transaction will give an accurate picture of only the
+ effects of transactions that committed before the repeatable read transaction
+ started — but one might legitimately wonder whether the answer is still
+ relevant by the time it is delivered. If the repeatable read transaction
+ itself applied some changes before trying to make the consistency check,
+ the usefulness of the check becomes even more debatable, since now it
+ includes some but not all post-transaction-start changes. In such cases
+ a careful person might wish to lock all tables needed for the check,
+ in order to get an indisputable picture of current reality. A
+ SHARE mode (or higher) lock guarantees that there are no
+ uncommitted changes in the locked table, other than those of the current
+ transaction.
+
+ Note also that if one is relying on explicit locking to prevent concurrent
+ changes, one should either use Read Committed mode, or in Repeatable Read
+ mode be careful to obtain
+ locks before performing queries. A lock obtained by a
+ repeatable read transaction guarantees that no other transactions modifying
+ the table are still running, but if the snapshot seen by the
+ transaction predates obtaining the lock, it might predate some now-committed
+ changes in the table. A repeatable read transaction's snapshot is actually
+ frozen at the start of its first query or data-modification command
+ (SELECT, INSERT,
+ UPDATE, DELETE, or
+ MERGE), so it is possible to obtain locks explicitly
+ before the snapshot is frozen.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/archive-module-callbacks.html b/pgsql/doc/postgresql/html/archive-module-callbacks.html
new file mode 100644
index 0000000000000000000000000000000000000000..a4a6d8b20dde40e806f9bb0f5e37f0ab539f8572
--- /dev/null
+++ b/pgsql/doc/postgresql/html/archive-module-callbacks.html
@@ -0,0 +1,60 @@
+
+51.2. Archive Module Callbacks
+ The archive callbacks define the actual archiving behavior of the module.
+ The server will call them as required to process each individual WAL file.
+
+ The startup_cb callback is called shortly after the
+ module is loaded. This callback can be used to perform any additional
+ initialization required. If the archive module has any state, it can use
+ state->private_data to store it.
+
+
+ The check_configured_cb callback is called to determine
+ whether the module is fully configured and ready to accept WAL files (e.g.,
+ its configuration parameters are set to valid values). If no
+ check_configured_cb is defined, the server always
+ assumes the module is configured.
+
+
+
+ If true is returned, the server will proceed with
+ archiving the file by calling the archive_file_cb
+ callback. If false is returned, archiving will not
+ proceed, and the archiver will emit the following message to the server log:
+
+WARNING: archive_mode enabled, yet archiving is not configured
+
+ In the latter case, the server will periodically call this function, and
+ archiving will proceed only when it returns true.
+
+
+ If true is returned, the server proceeds as if the file
+ was successfully archived, which may include recycling or removing the
+ original WAL file. If false is returned, the server will
+ keep the original WAL file and retry archiving later.
+ file will contain just the file name of the WAL
+ file to archive, while path contains the full
+ path of the WAL file (including the file name).
+
+ The shutdown_cb callback is called when the archiver
+ process exits (e.g., after an error) or the value of
+ archive_library changes. If no
+ shutdown_cb is defined, no special action is taken in
+ these situations. If the archive module has any state, this callback should
+ free it to avoid leaks.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/archive-module-init.html b/pgsql/doc/postgresql/html/archive-module-init.html
new file mode 100644
index 0000000000000000000000000000000000000000..dc6d83decb254d3c430e3de417c90e5afd95ccd9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/archive-module-init.html
@@ -0,0 +1,28 @@
+
+51.1. Initialization Functions
+ An archive library is loaded by dynamically loading a shared library with the
+ archive_library's name as the library base name. The
+ normal library search path is used to locate the library. To provide the
+ required archive module callbacks and to indicate that the library is
+ actually an archive module, it needs to provide a function named
+ _PG_archive_module_init. The result of the function
+ must be a pointer to a struct of type
+ ArchiveModuleCallbacks, which contains everything
+ that the core code needs to know to make use of the archive module. The
+ return value needs to be of server lifetime, which is typically achieved by
+ defining it as a static const variable in global scope.
+
+
+
+ Only the archive_file_cb callback is required. The
+ others are optional.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/archive-modules.html b/pgsql/doc/postgresql/html/archive-modules.html
new file mode 100644
index 0000000000000000000000000000000000000000..56fe2ffe06e3c5ab0eed95954833656dcfc579ae
--- /dev/null
+++ b/pgsql/doc/postgresql/html/archive-modules.html
@@ -0,0 +1,24 @@
+
+Chapter 51. Archive Modules
+ PostgreSQL provides infrastructure to create custom modules for continuous
+ archiving (see Section 26.3). While archiving via
+ a shell command (i.e., archive_command) is much
+ simpler, a custom archive module will often be considerably more robust and
+ performant.
+
+ When a custom archive_library is configured, PostgreSQL
+ will submit completed WAL files to the module, and the server will avoid
+ recycling or removing these WAL files until the module indicates that the files
+ were successfully archived. It is ultimately up to the module to decide what
+ to do with each WAL file, but many recommendations are listed at
+ Section 26.3.1.
+
+ Archiving modules must at least consist of an initialization function (see
+ Section 51.1) and the required callbacks (see
+ Section 51.2). However, archive modules are
+ also permitted to do much more (e.g., declare GUCs and register background
+ workers).
+
+ The contrib/basic_archive module contains a working
+ example, which demonstrates some useful techniques.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/arrays.html b/pgsql/doc/postgresql/html/arrays.html
new file mode 100644
index 0000000000000000000000000000000000000000..75dca022399051435a390c812112da9239bee494
--- /dev/null
+++ b/pgsql/doc/postgresql/html/arrays.html
@@ -0,0 +1,647 @@
+
+8.15. Arrays
+ PostgreSQL allows columns of a table to be
+ defined as variable-length multidimensional arrays. Arrays of any
+ built-in or user-defined base type, enum type, composite type, range type,
+ or domain can be created.
+
+ As shown, an array data type is named by appending square brackets
+ ([]) to the data type name of the array elements. The
+ above command will create a table named
+ sal_emp with a column of type
+ text (name), a
+ one-dimensional array of type integer
+ (pay_by_quarter), which represents the
+ employee's salary by quarter, and a two-dimensional array of
+ text (schedule), which
+ represents the employee's weekly schedule.
+
+ The syntax for CREATE TABLE allows the exact size of
+ arrays to be specified, for example:
+
+
+
+ However, the current implementation ignores any supplied array size
+ limits, i.e., the behavior is the same as for arrays of unspecified
+ length.
+
+ The current implementation does not enforce the declared
+ number of dimensions either. Arrays of a particular element type are
+ all considered to be of the same type, regardless of size or number
+ of dimensions. So, declaring the array size or number of dimensions in
+ CREATE TABLE is simply documentation; it does not
+ affect run-time behavior.
+
+ An alternative syntax, which conforms to the SQL standard by using
+ the keyword ARRAY, can be used for one-dimensional arrays.
+ pay_by_quarter could have been defined
+ as:
+
+ pay_by_quarter integer ARRAY[4],
+
+ Or, if no array size is to be specified:
+
+ pay_by_quarter integer ARRAY,
+
+ As before, however, PostgreSQL does not enforce the
+ size restriction in any case.
+
+ To write an array value as a literal constant, enclose the element
+ values within curly braces and separate them by commas. (If you
+ know C, this is not unlike the C syntax for initializing
+ structures.) You can put double quotes around any element value,
+ and must do so if it contains commas or curly braces. (More
+ details appear below.) Thus, the general format of an array
+ constant is the following:
+
+'{ val1delimval2delim ... }'
+
+ where delim is the delimiter character
+ for the type, as recorded in its pg_type entry.
+ Among the standard data types provided in the
+ PostgreSQL distribution, all use a comma
+ (,), except for type box which uses a semicolon
+ (;). Each val is
+ either a constant of the array element type, or a subarray. An example
+ of an array constant is:
+
+'{{1,2,3},{4,5,6},{7,8,9}}'
+
+ This constant is a two-dimensional, 3-by-3 array consisting of
+ three subarrays of integers.
+
+ To set an element of an array constant to NULL, write NULL
+ for the element value. (Any upper- or lower-case variant of
+ NULL will do.) If you want an actual string value
+ “NULL”, you must put double quotes around it.
+
+ (These kinds of array constants are actually only a special case of
+ the generic type constants discussed in Section 4.1.2.7. The constant is initially
+ treated as a string and passed to the array input conversion
+ routine. An explicit type specification might be necessary.)
+
+ Notice that the array elements are ordinary SQL constants or
+ expressions; for instance, string literals are single quoted, instead of
+ double quoted as they would be in an array literal. The ARRAY
+ constructor syntax is discussed in more detail in
+ Section 4.2.12.
+
+ Now, we can run some queries on the table.
+ First, we show how to access a single element of an array.
+ This query retrieves the names of the employees whose pay changed in
+ the second quarter:
+
+
+SELECT name FROM sal_emp WHERE pay_by_quarter[1] <> pay_by_quarter[2];
+
+ name
+-------
+ Carol
+(1 row)
+
+
+ The array subscript numbers are written within square brackets.
+ By default PostgreSQL uses a
+ one-based numbering convention for arrays, that is,
+ an array of n elements starts with array[1] and
+ ends with array[n].
+
+ This query retrieves the third quarter pay of all employees:
+
+
+ We can also access arbitrary rectangular slices of an array, or
+ subarrays. An array slice is denoted by writing
+ lower-bound:upper-bound
+ for one or more array dimensions. For example, this query retrieves the first
+ item on Bill's schedule for the first two days of the week:
+
+
+SELECT schedule[1:2][1:1] FROM sal_emp WHERE name = 'Bill';
+
+ schedule
+------------------------
+ {{meeting},{training}}
+(1 row)
+
+
+ If any dimension is written as a slice, i.e., contains a colon, then all
+ dimensions are treated as slices. Any dimension that has only a single
+ number (no colon) is treated as being from 1
+ to the number specified. For example, [2] is treated as
+ [1:2], as in this example:
+
+
+SELECT schedule[1:2][2] FROM sal_emp WHERE name = 'Bill';
+
+ schedule
+-------------------------------------------
+ {{meeting,lunch},{training,presentation}}
+(1 row)
+
+
+ To avoid confusion with the non-slice case, it's best to use slice syntax
+ for all dimensions, e.g., [1:2][1:1], not [2][1:1].
+
+ It is possible to omit the lower-bound and/or
+ upper-bound of a slice specifier; the missing
+ bound is replaced by the lower or upper limit of the array's subscripts.
+ For example:
+
+
+SELECT schedule[:2][2:] FROM sal_emp WHERE name = 'Bill';
+
+ schedule
+------------------------
+ {{lunch},{presentation}}
+(1 row)
+
+SELECT schedule[:][1:1] FROM sal_emp WHERE name = 'Bill';
+
+ schedule
+------------------------
+ {{meeting},{training}}
+(1 row)
+
+
+ An array subscript expression will return null if either the array itself or
+ any of the subscript expressions are null. Also, null is returned if a
+ subscript is outside the array bounds (this case does not raise an error).
+ For example, if schedule
+ currently has the dimensions [1:3][1:2] then referencing
+ schedule[3][3] yields NULL. Similarly, an array reference
+ with the wrong number of subscripts yields a null rather than an error.
+
+ An array slice expression likewise yields null if the array itself or
+ any of the subscript expressions are null. However, in other
+ cases such as selecting an array slice that
+ is completely outside the current array bounds, a slice expression
+ yields an empty (zero-dimensional) array instead of null. (This
+ does not match non-slice behavior and is done for historical reasons.)
+ If the requested slice partially overlaps the array bounds, then it
+ is silently reduced to just the overlapping region instead of
+ returning null.
+
+ The current dimensions of any array value can be retrieved with the
+ array_dims function:
+
+
+SELECT array_dims(schedule) FROM sal_emp WHERE name = 'Carol';
+
+ array_dims
+------------
+ [1:2][1:2]
+(1 row)
+
+
+ array_dims produces a text result,
+ which is convenient for people to read but perhaps inconvenient
+ for programs. Dimensions can also be retrieved with
+ array_upper and array_lower,
+ which return the upper and lower bound of a
+ specified array dimension, respectively:
+
+
+SELECT array_upper(schedule, 1) FROM sal_emp WHERE name = 'Carol';
+
+ array_upper
+-------------
+ 2
+(1 row)
+
+
+ array_length will return the length of a specified
+ array dimension:
+
+
+SELECT array_length(schedule, 1) FROM sal_emp WHERE name = 'Carol';
+
+ array_length
+--------------
+ 2
+(1 row)
+
+
+ cardinality returns the total number of elements in an
+ array across all dimensions. It is effectively the number of rows a call to
+ unnest would yield:
+
+
+SELECT cardinality(schedule) FROM sal_emp WHERE name = 'Carol';
+
+ cardinality
+-------------
+ 4
+(1 row)
+
+UPDATE sal_emp SET pay_by_quarter = '{25000,25000,27000,27000}'
+ WHERE name = 'Carol';
+
+
+ or using the ARRAY expression syntax:
+
+
+UPDATE sal_emp SET pay_by_quarter = ARRAY[25000,25000,27000,27000]
+ WHERE name = 'Carol';
+
+
+ An array can also be updated at a single element:
+
+
+UPDATE sal_emp SET pay_by_quarter[4] = 15000
+ WHERE name = 'Bill';
+
+
+ or updated in a slice:
+
+
+UPDATE sal_emp SET pay_by_quarter[1:2] = '{27000,27000}'
+ WHERE name = 'Carol';
+
+
+ The slice syntaxes with omitted lower-bound and/or
+ upper-bound can be used too, but only when
+ updating an array value that is not NULL or zero-dimensional (otherwise,
+ there is no existing subscript limit to substitute).
+
+ A stored array value can be enlarged by assigning to elements not already
+ present. Any positions between those previously present and the newly
+ assigned elements will be filled with nulls. For example, if array
+ myarray currently has 4 elements, it will have six
+ elements after an update that assigns to myarray[6];
+ myarray[5] will contain null.
+ Currently, enlargement in this fashion is only allowed for one-dimensional
+ arrays, not multidimensional arrays.
+
+ Subscripted assignment allows creation of arrays that do not use one-based
+ subscripts. For example one might assign to myarray[-2:7] to
+ create an array with subscript values from -2 to 7.
+
+ New array values can also be constructed using the concatenation operator,
+ ||:
+
+ The concatenation operator allows a single element to be pushed onto the
+ beginning or end of a one-dimensional array. It also accepts two
+ N-dimensional arrays, or an N-dimensional
+ and an N+1-dimensional array.
+
+ When a single element is pushed onto either the beginning or end of a
+ one-dimensional array, the result is an array with the same lower bound
+ subscript as the array operand. For example:
+
+ When two arrays with an equal number of dimensions are concatenated, the
+ result retains the lower bound subscript of the left-hand operand's outer
+ dimension. The result is an array comprising every element of the left-hand
+ operand followed by every element of the right-hand operand. For example:
+
+ When an N-dimensional array is pushed onto the beginning
+ or end of an N+1-dimensional array, the result is
+ analogous to the element-array case above. Each N-dimensional
+ sub-array is essentially an element of the N+1-dimensional
+ array's outer dimension. For example:
+
+ An array can also be constructed by using the functions
+ array_prepend, array_append,
+ or array_cat. The first two only support one-dimensional
+ arrays, but array_cat supports multidimensional arrays.
+ Some examples:
+
+
+ In simple cases, the concatenation operator discussed above is preferred
+ over direct use of these functions. However, because the concatenation
+ operator is overloaded to serve all three cases, there are situations where
+ use of one of the functions is helpful to avoid ambiguity. For example
+ consider:
+
+
+SELECT ARRAY[1, 2] || '{3, 4}'; -- the untyped literal is taken as an array
+ ?column?
+-----------
+ {1,2,3,4}
+
+SELECT ARRAY[1, 2] || '7'; -- so is this one
+ERROR: malformed array literal: "7"
+
+SELECT ARRAY[1, 2] || NULL; -- so is an undecorated NULL
+ ?column?
+----------
+ {1,2}
+(1 row)
+
+SELECT array_append(ARRAY[1, 2], NULL); -- this might have been meant
+ array_append
+--------------
+ {1,2,NULL}
+
+
+ In the examples above, the parser sees an integer array on one side of the
+ concatenation operator, and a constant of undetermined type on the other.
+ The heuristic it uses to resolve the constant's type is to assume it's of
+ the same type as the operator's other input — in this case,
+ integer array. So the concatenation operator is presumed to
+ represent array_cat, not array_append. When
+ that's the wrong choice, it could be fixed by casting the constant to the
+ array's element type; but explicit use of array_append might
+ be a preferable solution.
+
+ To search for a value in an array, each value must be checked.
+ This can be done manually, if you know the size of the array.
+ For example:
+
+
+SELECT * FROM sal_emp WHERE pay_by_quarter[1] = 10000 OR
+ pay_by_quarter[2] = 10000 OR
+ pay_by_quarter[3] = 10000 OR
+ pay_by_quarter[4] = 10000;
+
+
+ However, this quickly becomes tedious for large arrays, and is not
+ helpful if the size of the array is unknown. An alternative method is
+ described in Section 9.24. The above
+ query could be replaced by:
+
+
+SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter);
+
+
+ In addition, you can find rows where the array has all values
+ equal to 10000 with:
+
+
+SELECT * FROM sal_emp WHERE 10000 = ALL (pay_by_quarter);
+
+
+
+ Alternatively, the generate_subscripts function can be used.
+ For example:
+
+
+SELECT * FROM
+ (SELECT pay_by_quarter,
+ generate_subscripts(pay_by_quarter, 1) AS s
+ FROM sal_emp) AS foo
+ WHERE pay_by_quarter[s] = 10000;
+
+ You can also search an array using the && operator,
+ which checks whether the left operand overlaps with the right operand.
+ For instance:
+
+
+SELECT * FROM sal_emp WHERE pay_by_quarter && ARRAY[10000];
+
+
+ This and other array operators are further described in
+ Section 9.19. It can be accelerated by an appropriate
+ index, as described in Section 11.2.
+
+ You can also search for specific values in an array using the array_position
+ and array_positions functions. The former returns the subscript of
+ the first occurrence of a value in an array; the latter returns an array with the
+ subscripts of all occurrences of the value in the array. For example:
+
+
+ Arrays are not sets; searching for specific array elements
+ can be a sign of database misdesign. Consider
+ using a separate table with a row for each item that would be an
+ array element. This will be easier to search, and is likely to
+ scale better for a large number of elements.
+
+ The external text representation of an array value consists of items that
+ are interpreted according to the I/O conversion rules for the array's
+ element type, plus decoration that indicates the array structure.
+ The decoration consists of curly braces ({ and })
+ around the array value plus delimiter characters between adjacent items.
+ The delimiter character is usually a comma (,) but can be
+ something else: it is determined by the typdelim setting
+ for the array's element type. Among the standard data types provided
+ in the PostgreSQL distribution, all use a comma,
+ except for type box, which uses a semicolon (;).
+ In a multidimensional array, each dimension (row, plane,
+ cube, etc.) gets its own level of curly braces, and delimiters
+ must be written between adjacent curly-braced entities of the same level.
+
+ The array output routine will put double quotes around element values
+ if they are empty strings, contain curly braces, delimiter characters,
+ double quotes, backslashes, or white space, or match the word
+ NULL. Double quotes and backslashes
+ embedded in element values will be backslash-escaped. For numeric
+ data types it is safe to assume that double quotes will never appear, but
+ for textual data types one should be prepared to cope with either the presence
+ or absence of quotes.
+
+ By default, the lower bound index value of an array's dimensions is
+ set to one. To represent arrays with other lower bounds, the array
+ subscript ranges can be specified explicitly before writing the
+ array contents.
+ This decoration consists of square brackets ([])
+ around each array dimension's lower and upper bounds, with
+ a colon (:) delimiter character in between. The
+ array dimension decoration is followed by an equal sign (=).
+ For example:
+
+SELECT f1[1][-2][3] AS e1, f1[1][-1][5] AS e2
+ FROM (SELECT '[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'::int[] AS f1) AS ss;
+
+ e1 | e2
+----+----
+ 1 | 6
+(1 row)
+
+ The array output routine will include explicit dimensions in its result
+ only when there are one or more lower bounds different from one.
+
+ If the value written for an element is NULL (in any case
+ variant), the element is taken to be NULL. The presence of any quotes
+ or backslashes disables this and allows the literal string value
+ “NULL” to be entered. Also, for backward compatibility with
+ pre-8.2 versions of PostgreSQL, the array_nulls configuration parameter can be turned
+ off to suppress recognition of NULL as a NULL.
+
+ As shown previously, when writing an array value you can use double
+ quotes around any individual array element. You must do so
+ if the element value would otherwise confuse the array-value parser.
+ For example, elements containing curly braces, commas (or the data type's
+ delimiter character), double quotes, backslashes, or leading or trailing
+ whitespace must be double-quoted. Empty strings and strings matching the
+ word NULL must be quoted, too. To put a double
+ quote or backslash in a quoted array element value, precede it
+ with a backslash. Alternatively, you can avoid quotes and use
+ backslash-escaping to protect all data characters that would otherwise
+ be taken as array syntax.
+
+ You can add whitespace before a left brace or after a right
+ brace. You can also add whitespace before or after any individual item
+ string. In all of these cases the whitespace will be ignored. However,
+ whitespace within double-quoted elements, or surrounded on both sides by
+ non-whitespace characters of an element, is not ignored.
+
Tip
+ The ARRAY constructor syntax (see
+ Section 4.2.12) is often easier to work
+ with than the array-literal syntax when writing array values in SQL
+ commands. In ARRAY, individual element values are written the
+ same way they would be written when not members of an array.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-bsd.html b/pgsql/doc/postgresql/html/auth-bsd.html
new file mode 100644
index 0000000000000000000000000000000000000000..37c2e96166f78d52eef564be2e54242786b59ce5
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-bsd.html
@@ -0,0 +1,21 @@
+
+21.14. BSD Authentication
+ This authentication method operates similarly to
+ password except that it uses BSD Authentication
+ to verify the password. BSD Authentication is used only
+ to validate user name/password pairs. Therefore the user's role must
+ already exist in the database before BSD Authentication can be used
+ for authentication. The BSD Authentication framework is currently
+ only available on OpenBSD.
+
+ BSD Authentication in PostgreSQL uses
+ the auth-postgresql login type and authenticates with
+ the postgresql login class if that's defined
+ in login.conf. By default that login class does not
+ exist, and PostgreSQL will use the default login class.
+
Note
+ To use BSD Authentication, the PostgreSQL user account (that is, the
+ operating system user running the server) must first be added to
+ the auth group. The auth group
+ exists by default on OpenBSD systems.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-cert.html b/pgsql/doc/postgresql/html/auth-cert.html
new file mode 100644
index 0000000000000000000000000000000000000000..e92eaf54e791e605af53a09eedbaf476f8df118a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-cert.html
@@ -0,0 +1,25 @@
+
+21.12. Certificate Authentication
+ This authentication method uses SSL client certificates to perform
+ authentication. It is therefore only available for SSL connections;
+ see Section 19.9.2 for SSL configuration instructions.
+ When using this authentication method, the server will require that
+ the client provide a valid, trusted certificate. No password prompt
+ will be sent to the client. The cn (Common Name)
+ attribute of the certificate
+ will be compared to the requested database user name, and if they match
+ the login will be allowed. User name mapping can be used to allow
+ cn to be different from the database user name.
+
+ The following configuration options are supported for SSL certificate
+ authentication:
+
map
+ Allows for mapping between system and database user names. See
+ Section 21.2 for details.
+
+
+ It is redundant to use the clientcert option with
+ cert authentication because cert
+ authentication is effectively trust authentication
+ with clientcert=verify-full.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-delay.html b/pgsql/doc/postgresql/html/auth-delay.html
new file mode 100644
index 0000000000000000000000000000000000000000..33d005c5dfb465d251ac59cd1b5012717991624c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-delay.html
@@ -0,0 +1,28 @@
+
+F.3. auth_delay — pause on authentication failure
+ auth_delay causes the server to pause briefly before
+ reporting authentication failure, to make brute-force attacks on database
+ passwords more difficult. Note that it does nothing to prevent
+ denial-of-service attacks, and may even exacerbate them, since processes
+ that are waiting before reporting authentication failure will still consume
+ connection slots.
+
+ In order to function, this module must be loaded via
+ shared_preload_libraries in postgresql.conf.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-ident.html b/pgsql/doc/postgresql/html/auth-ident.html
new file mode 100644
index 0000000000000000000000000000000000000000..a1a025245ba9536415fc93a4fae2e570b0542cd9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-ident.html
@@ -0,0 +1,52 @@
+
+21.8. Ident Authentication
+ The ident authentication method works by obtaining the client's
+ operating system user name from an ident server and using it as
+ the allowed database user name (with an optional user name mapping).
+ This is only supported on TCP/IP connections.
+
Note
+ When ident is specified for a local (non-TCP/IP) connection,
+ peer authentication (see Section 21.9) will be
+ used instead.
+
+ The following configuration options are supported for ident:
+
map
+ Allows for mapping between system and database user names. See
+ Section 21.2 for details.
+
+
+ The “Identification Protocol” is described in
+ RFC 1413.
+ Virtually every Unix-like
+ operating system ships with an ident server that listens on TCP
+ port 113 by default. The basic functionality of an ident server
+ is to answer questions like “What user initiated the
+ connection that goes out of your port X
+ and connects to my port Y?”.
+ Since PostgreSQL knows both X and
+ Y when a physical connection is established, it
+ can interrogate the ident server on the host of the connecting
+ client and can theoretically determine the operating system user
+ for any given connection.
+
+ The drawback of this procedure is that it depends on the integrity
+ of the client: if the client machine is untrusted or compromised,
+ an attacker could run just about any program on port 113 and
+ return any user name they choose. This authentication method is
+ therefore only appropriate for closed networks where each client
+ machine is under tight control and where the database and system
+ administrators operate in close contact. In other words, you must
+ trust the machine running the ident server.
+ Heed the warning:
+
+ The Identification Protocol is not intended as an authorization
+ or access control protocol.
+
--RFC 1413
+
+ Some ident servers have a nonstandard option that causes the returned
+ user name to be encrypted, using a key that only the originating
+ machine's administrator knows. This option must not be
+ used when using the ident server with PostgreSQL,
+ since PostgreSQL does not have any way to decrypt the
+ returned string to determine the actual user name.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-ldap.html b/pgsql/doc/postgresql/html/auth-ldap.html
new file mode 100644
index 0000000000000000000000000000000000000000..5d7ce54256806151c33c9c4e31536b3fd9d1ba55
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-ldap.html
@@ -0,0 +1,190 @@
+
+21.10. LDAP Authentication
+ This authentication method operates similarly to
+ password except that it uses LDAP
+ as the password verification method. LDAP is used only to validate
+ the user name/password pairs. Therefore the user must already
+ exist in the database before LDAP can be used for
+ authentication.
+
+ LDAP authentication can operate in two modes. In the first mode,
+ which we will call the simple bind mode,
+ the server will bind to the distinguished name constructed as
+ prefixusernamesuffix.
+ Typically, the prefix parameter is used to specify
+ cn=, or DOMAIN\ in an Active
+ Directory environment. suffix is used to specify the
+ remaining part of the DN in a non-Active Directory environment.
+
+ In the second mode, which we will call the search+bind mode,
+ the server first binds to the LDAP directory with
+ a fixed user name and password, specified with ldapbinddn
+ and ldapbindpasswd, and performs a search for the user trying
+ to log in to the database. If no user and password is configured, an
+ anonymous bind will be attempted to the directory. The search will be
+ performed over the subtree at ldapbasedn, and will try to
+ do an exact match of the attribute specified in
+ ldapsearchattribute.
+ Once the user has been found in
+ this search, the server disconnects and re-binds to the directory as
+ this user, using the password specified by the client, to verify that the
+ login is correct. This mode is the same as that used by LDAP authentication
+ schemes in other software, such as Apache mod_authnz_ldap and pam_ldap.
+ This method allows for significantly more flexibility
+ in where the user objects are located in the directory, but will cause
+ two separate connections to the LDAP server to be made.
+
+ The following configuration options are used in both modes:
+
ldapserver
+ Names or IP addresses of LDAP servers to connect to. Multiple
+ servers may be specified, separated by spaces.
+
ldapport
+ Port number on LDAP server to connect to. If no port is specified,
+ the LDAP library's default port setting will be used.
+
ldapscheme
+ Set to ldaps to use LDAPS. This is a non-standard
+ way of using LDAP over SSL, supported by some LDAP server
+ implementations. See also the ldaptls option for
+ an alternative.
+
ldaptls
+ Set to 1 to make the connection between PostgreSQL and the LDAP server
+ use TLS encryption. This uses the StartTLS
+ operation per RFC 4513.
+ See also the ldapscheme option for an alternative.
+
+
+ Note that using ldapscheme or
+ ldaptls only encrypts the traffic between the
+ PostgreSQL server and the LDAP server. The connection between the
+ PostgreSQL server and the PostgreSQL client will still be unencrypted
+ unless SSL is used there as well.
+
+ The following options are used in simple bind mode only:
+
ldapprefix
+ String to prepend to the user name when forming the DN to bind as,
+ when doing simple bind authentication.
+
ldapsuffix
+ String to append to the user name when forming the DN to bind as,
+ when doing simple bind authentication.
+
+
+ The following options are used in search+bind mode only:
+
ldapbasedn
+ Root DN to begin the search for the user in, when doing search+bind
+ authentication.
+
ldapbinddn
+ DN of user to bind to the directory with to perform the search when
+ doing search+bind authentication.
+
ldapbindpasswd
+ Password for user to bind to the directory with to perform the search
+ when doing search+bind authentication.
+
ldapsearchattribute
+ Attribute to match against the user name in the search when doing
+ search+bind authentication. If no attribute is specified, the
+ uid attribute will be used.
+
ldapsearchfilter
+ The search filter to use when doing search+bind authentication.
+ Occurrences of $username will be replaced with the
+ user name. This allows for more flexible search filters than
+ ldapsearchattribute.
+
ldapurl
+ An RFC 4516
+ LDAP URL. This is an alternative way to write some of the
+ other LDAP options in a more compact and standard form. The format is
+
+ scope must be one
+ of base, one, sub,
+ typically the last. (The default is base, which
+ is normally not useful in this application.) attribute can
+ nominate a single attribute, in which case it is used as a value for
+ ldapsearchattribute. If
+ attribute is empty then
+ filter can be used as a value for
+ ldapsearchfilter.
+
+ The URL scheme ldaps chooses the LDAPS method for
+ making LDAP connections over SSL, equivalent to using
+ ldapscheme=ldaps. To use encrypted LDAP
+ connections using the StartTLS operation, use the
+ normal URL scheme ldap and specify the
+ ldaptls option in addition to
+ ldapurl.
+
+ For non-anonymous binds, ldapbinddn
+ and ldapbindpasswd must be specified as separate
+ options.
+
+ LDAP URLs are currently only supported with
+ OpenLDAP, not on Windows.
+
+
+ It is an error to mix configuration options for simple bind with options
+ for search+bind.
+
+ When using search+bind mode, the search can be performed using a single
+ attribute specified with ldapsearchattribute, or using
+ a custom search filter specified with
+ ldapsearchfilter.
+ Specifying ldapsearchattribute=foo is equivalent to
+ specifying ldapsearchfilter="(foo=$username)". If neither
+ option is specified the default is
+ ldapsearchattribute=uid.
+
+ If PostgreSQL was compiled with
+ OpenLDAP as the LDAP client library, the
+ ldapserver setting may be omitted. In that case, a
+ list of host names and ports is looked up via
+ RFC 2782 DNS SRV records.
+ The name _ldap._tcp.DOMAIN is looked up, where
+ DOMAIN is extracted from ldapbasedn.
+
+ Here is an example for a simple-bind LDAP configuration:
+
+ When a connection to the database server as database
+ user someuser is requested, PostgreSQL will attempt to
+ bind to the LDAP server using the DN cn=someuser, dc=example,
+ dc=net and the password provided by the client. If that connection
+ succeeds, the database access is granted.
+
+ Here is an example for a search+bind configuration:
+
+ When a connection to the database server as database
+ user someuser is requested, PostgreSQL will attempt to
+ bind anonymously (since ldapbinddn was not specified) to
+ the LDAP server, perform a search for (uid=someuser)
+ under the specified base DN. If an entry is found, it will then attempt to
+ bind using that found information and the password supplied by the client.
+ If that second connection succeeds, the database access is granted.
+
+ Here is the same search+bind configuration written as a URL:
+
+ Some other software that supports authentication against LDAP uses the
+ same URL format, so it will be easier to share the configuration.
+
+ Here is an example for a search+bind configuration that uses
+ ldapsearchfilter instead of
+ ldapsearchattribute to allow authentication by
+ user ID or email address:
+
+ Here is an example for a search+bind configuration that uses DNS SRV
+ discovery to find the host name(s) and port(s) for the LDAP service for the
+ domain name example.net:
+
+host ... ldap ldapbasedn="dc=example,dc=net"
+
+
Tip
+ Since LDAP often uses commas and spaces to separate the different
+ parts of a DN, it is often necessary to use double-quoted parameter
+ values when configuring LDAP options, as shown in the examples.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-methods.html b/pgsql/doc/postgresql/html/auth-methods.html
new file mode 100644
index 0000000000000000000000000000000000000000..e51fc2eeceafe3ddf3e7628286b489e65294aa3f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-methods.html
@@ -0,0 +1,59 @@
+
+21.3. Authentication Methods
+ GSSAPI authentication, which
+ relies on a GSSAPI-compatible security library. Typically this is
+ used to access an authentication server such as a Kerberos or
+ Microsoft Active Directory server.
+
+ SSPI authentication, which
+ uses a Windows-specific protocol similar to GSSAPI.
+
+ Ident authentication, which
+ relies on an “Identification Protocol”
+ (RFC 1413)
+ service on the client's machine. (On local Unix-socket connections,
+ this is treated as peer authentication.)
+
+ Peer authentication, which
+ relies on operating system facilities to identify the process at the
+ other end of a local connection. This is not supported for remote
+ connections.
+
+ Certificate authentication, which
+ requires an SSL connection and authenticates users by checking the
+ SSL certificate they send.
+
+ PAM authentication, which
+ relies on a PAM (Pluggable Authentication Modules) library.
+
+ BSD authentication, which
+ relies on the BSD Authentication framework (currently available
+ only on OpenBSD).
+
+
+ Peer authentication is usually recommendable for local connections,
+ though trust authentication might be sufficient in some circumstances.
+ Password authentication is the easiest choice for remote connections.
+ All the other options require some kind of external security
+ infrastructure (usually an authentication server or a certificate
+ authority for issuing SSL certificates), or are platform-specific.
+
+ The following sections describe each of these authentication methods
+ in more detail.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-pam.html b/pgsql/doc/postgresql/html/auth-pam.html
new file mode 100644
index 0000000000000000000000000000000000000000..c89292140453a80f4e3c18a9504e6d942e4644c9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-pam.html
@@ -0,0 +1,31 @@
+
+21.13. PAM Authentication
+ This authentication method operates similarly to
+ password except that it uses PAM (Pluggable
+ Authentication Modules) as the authentication mechanism. The
+ default PAM service name is postgresql.
+ PAM is used only to validate user name/password pairs and optionally the
+ connected remote host name or IP address. Therefore the user must already
+ exist in the database before PAM can be used for authentication. For more
+ information about PAM, please read the
+
+ Linux-PAM Page.
+
+ The following configuration options are supported for PAM:
+
pamservice
+ PAM service name.
+
pam_use_hostname
+ Determines whether the remote IP address or the host name is provided
+ to PAM modules through the PAM_RHOST item. By
+ default, the IP address is used. Set this option to 1 to use the
+ resolved host name instead. Host name resolution can lead to login
+ delays. (Most PAM configurations don't use this information, so it is
+ only necessary to consider this setting if a PAM configuration was
+ specifically created to make use of it.)
+
+
Note
+ If PAM is set up to read /etc/shadow, authentication
+ will fail because the PostgreSQL server is started by a non-root
+ user. However, this is not an issue when PAM is configured to use
+ LDAP or other authentication methods.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-password.html b/pgsql/doc/postgresql/html/auth-password.html
new file mode 100644
index 0000000000000000000000000000000000000000..71b0f26e671e0f2adbbb3f70054dafc488b042fd
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-password.html
@@ -0,0 +1,80 @@
+
+21.5. Password Authentication
+ There are several password-based authentication methods. These methods
+ operate similarly but differ in how the users' passwords are stored on the
+ server and how the password provided by a client is sent across the
+ connection.
+
scram-sha-256
+ The method scram-sha-256 performs SCRAM-SHA-256
+ authentication, as described in
+ RFC 7677. It
+ is a challenge-response scheme that prevents password sniffing on
+ untrusted connections and supports storing passwords on the server in a
+ cryptographically hashed form that is thought to be secure.
+
+ This is the most secure of the currently provided methods, but it is
+ not supported by older client libraries.
+
md5
+ The method md5 uses a custom less secure challenge-response
+ mechanism. It prevents password sniffing and avoids storing passwords
+ on the server in plain text but provides no protection if an attacker
+ manages to steal the password hash from the server. Also, the MD5 hash
+ algorithm is nowadays no longer considered secure against determined
+ attacks.
+
+ The md5 method cannot be used with
+ the db_user_namespace feature.
+
+ To ease transition from the md5 method to the newer
+ SCRAM method, if md5 is specified as a method
+ in pg_hba.conf but the user's password on the
+ server is encrypted for SCRAM (see below), then SCRAM-based
+ authentication will automatically be chosen instead.
+
password
+ The method password sends the password in clear-text and is
+ therefore vulnerable to password “sniffing” attacks. It should
+ always be avoided if possible. If the connection is protected by SSL
+ encryption then password can be used safely, though.
+ (Though SSL certificate authentication might be a better choice if one
+ is depending on using SSL).
+
+ PostgreSQL database passwords are
+ separate from operating system user passwords. The password for
+ each database user is stored in the pg_authid system
+ catalog. Passwords can be managed with the SQL commands
+ CREATE ROLE and
+ ALTER ROLE,
+ e.g., CREATE ROLE foo WITH LOGIN PASSWORD 'secret',
+ or the psql
+ command \password.
+ If no password has been set up for a user, the stored password
+ is null and password authentication will always fail for that user.
+
+ The availability of the different password-based authentication methods
+ depends on how a user's password on the server is encrypted (or hashed,
+ more accurately). This is controlled by the configuration
+ parameter password_encryption at the time the
+ password is set. If a password was encrypted using
+ the scram-sha-256 setting, then it can be used for the
+ authentication methods scram-sha-256
+ and password (but password transmission will be in
+ plain text in the latter case). The authentication method
+ specification md5 will automatically switch to using
+ the scram-sha-256 method in this case, as explained
+ above, so it will also work. If a password was encrypted using
+ the md5 setting, then it can be used only for
+ the md5 and password authentication
+ method specifications (again, with the password transmitted in plain text
+ in the latter case). (Previous PostgreSQL releases supported storing the
+ password on the server in plain text. This is no longer possible.) To
+ check the currently stored password hashes, see the system
+ catalog pg_authid.
+
+ To upgrade an existing installation from md5
+ to scram-sha-256, after having ensured that all client
+ libraries in use are new enough to support SCRAM,
+ set password_encryption = 'scram-sha-256'
+ in postgresql.conf, make all users set new passwords,
+ and change the authentication method specifications
+ in pg_hba.conf to scram-sha-256.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-peer.html b/pgsql/doc/postgresql/html/auth-peer.html
new file mode 100644
index 0000000000000000000000000000000000000000..1b0977709f95317eac4ba2e1282dc79b0121d61f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-peer.html
@@ -0,0 +1,21 @@
+
+21.9. Peer Authentication
+ The peer authentication method works by obtaining the client's
+ operating system user name from the kernel and using it as the
+ allowed database user name (with optional user name mapping). This
+ method is only supported on local connections.
+
+ The following configuration options are supported for peer:
+
map
+ Allows for mapping between system and database user names. See
+ Section 21.2 for details.
+
+
+ Peer authentication is only available on operating systems providing
+ the getpeereid() function, the SO_PEERCRED
+ socket parameter, or similar mechanisms. Currently that includes
+ Linux,
+ most flavors of BSD including
+ macOS,
+ and Solaris.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-pg-hba-conf.html b/pgsql/doc/postgresql/html/auth-pg-hba-conf.html
new file mode 100644
index 0000000000000000000000000000000000000000..51465b6339098b83f31afe0c305a4d2376029a1a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-pg-hba-conf.html
@@ -0,0 +1,542 @@
+
+21.1. The pg_hba.conf File
+ Client authentication is controlled by a configuration file,
+ which traditionally is named
+ pg_hba.conf and is stored in the database
+ cluster's data directory.
+ (HBA stands for host-based authentication.) A default
+ pg_hba.conf file is installed when the data
+ directory is initialized by initdb. It is
+ possible to place the authentication configuration file elsewhere,
+ however; see the hba_file configuration parameter.
+
+ The general format of the pg_hba.conf file is
+ a set of records, one per line. Blank lines are ignored, as is any
+ text after the # comment character.
+ A record can be continued onto the next line by ending the line with
+ a backslash. (Backslashes are not special except at the end of a line.)
+ A record is made
+ up of a number of fields which are separated by spaces and/or tabs.
+ Fields can contain white space if the field value is double-quoted.
+ Quoting one of the keywords in a database, user, or address field (e.g.,
+ all or replication) makes the word lose its special
+ meaning, and just match a database, user, or host with that name.
+ Backslash line continuation applies even within quoted text or comments.
+
+ Each authentication record specifies a connection type, a client IP address
+ range (if relevant for the connection type), a database name, a user name,
+ and the authentication method to be used for connections matching
+ these parameters. The first record with a matching connection type,
+ client address, requested database, and user name is used to perform
+ authentication. There is no “fall-through” or
+ “backup”: if one record is chosen and the authentication
+ fails, subsequent records are not considered. If no record matches,
+ access is denied.
+
+ Each record can be an include directive or an authentication record.
+ Include directives specify files that can be included, that contain
+ additional records. The records will be inserted in place of the
+ include directives. Include directives only contain two fields:
+ include, include_if_exists or
+ include_dir directive and the file or directory to be
+ included. The file or directory can be a relative or absolute path, and can
+ be double-quoted. For the include_dir form, all files
+ not starting with a . and ending with
+ .conf will be included. Multiple files within an include
+ directory are processed in file name order (according to C locale rules,
+ i.e., numbers before letters, and uppercase letters before lowercase ones).
+
+ This record matches connection attempts using Unix-domain
+ sockets. Without a record of this type, Unix-domain socket
+ connections are disallowed.
+
host
+ This record matches connection attempts made using TCP/IP.
+ host records match
+ SSL or non-SSL connection
+ attempts as well as GSSAPI encrypted or
+ non-GSSAPI encrypted connection attempts.
+
Note
+ Remote TCP/IP connections will not be possible unless
+ the server is started with an appropriate value for the
+ listen_addresses configuration parameter,
+ since the default behavior is to listen for TCP/IP connections
+ only on the local loopback address localhost.
+
hostssl
+ This record matches connection attempts made using TCP/IP,
+ but only when the connection is made with SSL
+ encryption.
+
+ To make use of this option the server must be built with
+ SSL support. Furthermore,
+ SSL must be enabled
+ by setting the ssl configuration parameter (see
+ Section 19.9 for more information).
+ Otherwise, the hostssl record is ignored except for
+ logging a warning that it cannot match any connections.
+
hostnossl
+ This record type has the opposite behavior of hostssl;
+ it only matches connection attempts made over
+ TCP/IP that do not use SSL.
+
hostgssenc
+ This record matches connection attempts made using TCP/IP,
+ but only when the connection is made with GSSAPI
+ encryption.
+
+ To make use of this option the server must be built with
+ GSSAPI support. Otherwise,
+ the hostgssenc record is ignored except for logging
+ a warning that it cannot match any connections.
+
hostnogssenc
+ This record type has the opposite behavior of hostgssenc;
+ it only matches connection attempts made over
+ TCP/IP that do not use GSSAPI encryption.
+
database
+ Specifies which database name(s) this record matches. The value
+ all specifies that it matches all databases.
+ The value sameuser specifies that the record
+ matches if the requested database has the same name as the
+ requested user. The value samerole specifies that
+ the requested user must be a member of the role with the same
+ name as the requested database. (samegroup is an
+ obsolete but still accepted spelling of samerole.)
+ Superusers are not considered to be members of a role for the
+ purposes of samerole unless they are explicitly
+ members of the role, directly or indirectly, and not just by
+ virtue of being a superuser.
+ The value replication specifies that the record
+ matches if a physical replication connection is requested, however, it
+ doesn't match with logical replication connections. Note that physical
+ replication connections do not specify any particular database whereas
+ logical replication connections do specify it.
+ Otherwise, this is the name of a specific
+ PostgreSQL database or a regular expression.
+ Multiple database names and/or regular expressions can be supplied by
+ separating them with commas.
+
+ If the database name starts with a slash (/), the
+ remainder of the name is treated as a regular expression.
+ (See Section 9.7.3.1 for details of
+ PostgreSQL's regular expression syntax.)
+
+ A separate file containing database names and/or regular expressions
+ can be specified by preceding the file name with @.
+
user
+ Specifies which database user name(s) this record
+ matches. The value all specifies that it
+ matches all users. Otherwise, this is either the name of a specific
+ database user, a regular expression (when starting with a slash
+ (/), or a group name preceded by +.
+ (Recall that there is no real distinction between users and groups
+ in PostgreSQL; a + mark really means
+ “match any of the roles that are directly or indirectly members
+ of this role”, while a name without a + mark matches
+ only that specific role.) For this purpose, a superuser is only
+ considered to be a member of a role if they are explicitly a member
+ of the role, directly or indirectly, and not just by virtue of
+ being a superuser.
+ Multiple user names and/or regular expressions can be supplied by
+ separating them with commas.
+
+ If the user name starts with a slash (/), the
+ remainder of the name is treated as a regular expression.
+ (See Section 9.7.3.1 for details of
+ PostgreSQL's regular expression syntax.)
+
+ A separate file containing user names and/or regular expressions can
+ be specified by preceding the file name with @.
+
address
+ Specifies the client machine address(es) that this record
+ matches. This field can contain either a host name, an IP
+ address range, or one of the special key words mentioned below.
+
+ An IP address range is specified using standard numeric notation
+ for the range's starting address, then a slash (/)
+ and a CIDR mask length. The mask
+ length indicates the number of high-order bits of the client
+ IP address that must match. Bits to the right of this should
+ be zero in the given IP address.
+ There must not be any white space between the IP address, the
+ /, and the CIDR mask length.
+
+ Typical examples of an IPv4 address range specified this way are
+ 172.20.143.89/32 for a single host, or
+ 172.20.143.0/24 for a small network, or
+ 10.6.0.0/16 for a larger one.
+ An IPv6 address range might look like ::1/128
+ for a single host (in this case the IPv6 loopback address) or
+ fe80::7a31:c1ff:0000:0000/96 for a small
+ network.
+ 0.0.0.0/0 represents all
+ IPv4 addresses, and ::0/0 represents
+ all IPv6 addresses.
+ To specify a single host, use a mask length of 32 for IPv4 or
+ 128 for IPv6. In a network address, do not omit trailing zeroes.
+
+ An entry given in IPv4 format will match only IPv4 connections,
+ and an entry given in IPv6 format will match only IPv6 connections,
+ even if the represented address is in the IPv4-in-IPv6 range.
+
+ You can also write all to match any IP address,
+ samehost to match any of the server's own IP
+ addresses, or samenet to match any address in any
+ subnet that the server is directly connected to.
+
+ If a host name is specified (anything that is not an IP address
+ range or a special key word is treated as a host name),
+ that name is compared with the result of a reverse name
+ resolution of the client's IP address (e.g., reverse DNS
+ lookup, if DNS is used). Host name comparisons are case
+ insensitive. If there is a match, then a forward name
+ resolution (e.g., forward DNS lookup) is performed on the host
+ name to check whether any of the addresses it resolves to are
+ equal to the client's IP address. If both directions match,
+ then the entry is considered to match. (The host name that is
+ used in pg_hba.conf should be the one that
+ address-to-name resolution of the client's IP address returns,
+ otherwise the line won't be matched. Some host name databases
+ allow associating an IP address with multiple host names, but
+ the operating system will only return one host name when asked
+ to resolve an IP address.)
+
+ A host name specification that starts with a dot
+ (.) matches a suffix of the actual host
+ name. So .example.com would match
+ foo.example.com (but not just
+ example.com).
+
+ When host names are specified
+ in pg_hba.conf, you should make sure that
+ name resolution is reasonably fast. It can be of advantage to
+ set up a local name resolution cache such
+ as nscd. Also, you may wish to enable the
+ configuration parameter log_hostname to see
+ the client's host name instead of the IP address in the log.
+
+ These fields do not apply to local records.
+
Note
+ Users sometimes wonder why host names are handled
+ in this seemingly complicated way, with two name resolutions
+ including a reverse lookup of the client's IP address. This
+ complicates use of the feature in case the client's reverse DNS
+ entry is not set up or yields some undesirable host name.
+ It is done primarily for efficiency: this way, a connection attempt
+ requires at most two resolver lookups, one reverse and one forward.
+ If there is a resolver problem with some address, it becomes only
+ that client's problem. A hypothetical alternative
+ implementation that only did forward lookups would have to
+ resolve every host name mentioned in
+ pg_hba.conf during every connection attempt.
+ That could be quite slow if many names are listed.
+ And if there is a resolver problem with one of the host names,
+ it becomes everyone's problem.
+
+ Also, a reverse lookup is necessary to implement the suffix
+ matching feature, because the actual client host name needs to
+ be known in order to match it against the pattern.
+
+ Note that this behavior is consistent with other popular
+ implementations of host name-based access control, such as the
+ Apache HTTP Server and TCP Wrappers.
+
IP-address IP-mask
+ These two fields can be used as an alternative to the
+ IP-address/mask-length
+ notation. Instead of
+ specifying the mask length, the actual mask is specified in a
+ separate column. For example, 255.0.0.0 represents an IPv4
+ CIDR mask length of 8, and 255.255.255.255 represents a
+ CIDR mask length of 32.
+
+ These fields do not apply to local records.
+
auth-method
+ Specifies the authentication method to use when a connection matches
+ this record. The possible choices are summarized here; details
+ are in Section 21.3. All the options
+ are lower case and treated case sensitively, so even acronyms like
+ ldap must be specified as lower case.
+
+
trust
+ Allow the connection unconditionally. This method
+ allows anyone that can connect to the
+ PostgreSQL database server to login as
+ any PostgreSQL user they wish,
+ without the need for a password or any other authentication. See Section 21.4 for details.
+
reject
+ Reject the connection unconditionally. This is useful for
+ “filtering out” certain hosts from a group, for example a
+ reject line could block a specific host from connecting,
+ while a later line allows the remaining hosts in a specific
+ network to connect.
+
scram-sha-256
+ Perform SCRAM-SHA-256 authentication to verify the user's
+ password. See Section 21.5 for details.
+
md5
+ Perform SCRAM-SHA-256 or MD5 authentication to verify the
+ user's password. See Section 21.5
+ for details.
+
password
+ Require the client to supply an unencrypted password for
+ authentication.
+ Since the password is sent in clear text over the
+ network, this should not be used on untrusted networks.
+ See Section 21.5 for details.
+
gss
+ Use GSSAPI to authenticate the user. This is only
+ available for TCP/IP connections. See Section 21.6 for details. It can be used in conjunction
+ with GSSAPI encryption.
+
sspi
+ Use SSPI to authenticate the user. This is only
+ available on Windows. See Section 21.7 for details.
+
ident
+ Obtain the operating system user name of the client
+ by contacting the ident server on the client
+ and check if it matches the requested database user name.
+ Ident authentication can only be used on TCP/IP
+ connections. When specified for local connections, peer
+ authentication will be used instead.
+ See Section 21.8 for details.
+
peer
+ Obtain the client's operating system user name from the operating
+ system and check if it matches the requested database user name.
+ This is only available for local connections.
+ See Section 21.9 for details.
+
ldap
+ Authenticate using an LDAP server. See Section 21.10 for details.
+
radius
+ Authenticate using a RADIUS server. See Section 21.11 for details.
+
cert
+ Authenticate using SSL client certificates. See
+ Section 21.12 for details.
+
pam
+ Authenticate using the Pluggable Authentication Modules
+ (PAM) service provided by the operating system. See Section 21.13 for details.
+
bsd
+ Authenticate using the BSD Authentication service provided by the
+ operating system. See Section 21.14 for details.
+
+
+
auth-options
+ After the auth-method field, there can be field(s) of
+ the form name=value that
+ specify options for the authentication method. Details about which
+ options are available for which authentication methods appear below.
+
+ In addition to the method-specific options listed below, there is a
+ method-independent authentication option clientcert, which
+ can be specified in any hostssl record.
+ This option can be set to verify-ca or
+ verify-full. Both options require the client
+ to present a valid (trusted) SSL certificate, while
+ verify-full additionally enforces that the
+ cn (Common Name) in the certificate matches
+ the username or an applicable mapping.
+ This behavior is similar to the cert authentication
+ method (see Section 21.12) but enables pairing
+ the verification of client certificates with any authentication
+ method that supports hostssl entries.
+
+ On any record using client certificate authentication (i.e. one
+ using the cert authentication method or one
+ using the clientcert option), you can specify
+ which part of the client certificate credentials to match using
+ the clientname option. This option can have one
+ of two values. If you specify clientname=CN, which
+ is the default, the username is matched against the certificate's
+ Common Name (CN). If instead you specify
+ clientname=DN the username is matched against the
+ entire Distinguished Name (DN) of the certificate.
+ This option is probably best used in conjunction with a username map.
+ The comparison is done with the DN in
+ RFC 2253
+ format. To see the DN of a client certificate
+ in this format, do
+
+ Care needs to be taken when using this option, especially when using
+ regular expression matching against the DN.
+
include
+ This line will be replaced by the contents of the given file.
+
include_if_exists
+ This line will be replaced by the content of the given file if the
+ file exists. Otherwise, a message is logged to indicate that the file
+ has been skipped.
+
include_dir
+ This line will be replaced by the contents of all the files found in
+ the directory, if they don't start with a . and end
+ with .conf, processed in file name order (according
+ to C locale rules, i.e., numbers before letters, and uppercase letters
+ before lowercase ones).
+
+
+ Files included by @ constructs are read as lists of names,
+ which can be separated by either whitespace or commas. Comments are
+ introduced by #, just as in
+ pg_hba.conf, and nested @ constructs are
+ allowed. Unless the file name following @ is an absolute
+ path, it is taken to be relative to the directory containing the
+ referencing file.
+
+ Since the pg_hba.conf records are examined
+ sequentially for each connection attempt, the order of the records is
+ significant. Typically, earlier records will have tight connection
+ match parameters and weaker authentication methods, while later
+ records will have looser match parameters and stronger authentication
+ methods. For example, one might wish to use trust
+ authentication for local TCP/IP connections but require a password for
+ remote TCP/IP connections. In this case a record specifying
+ trust authentication for connections from 127.0.0.1 would
+ appear before a record specifying password authentication for a wider
+ range of allowed client IP addresses.
+
+ The pg_hba.conf file is read on start-up and when
+ the main server process receives a
+ SIGHUP
+ signal. If you edit the file on an
+ active system, you will need to signal the postmaster
+ (using pg_ctl reload, calling the SQL function
+ pg_reload_conf(), or using kill
+ -HUP) to make it re-read the file.
+
Note
+ The preceding statement is not true on Microsoft Windows: there, any
+ changes in the pg_hba.conf file are immediately
+ applied by subsequent new connections.
+
+ The system view
+ pg_hba_file_rules
+ can be helpful for pre-testing changes to the pg_hba.conf
+ file, or for diagnosing problems if loading of the file did not have the
+ desired effects. Rows in the view with
+ non-null error fields indicate problems in the
+ corresponding lines of the file.
+
Tip
+ To connect to a particular database, a user must not only pass the
+ pg_hba.conf checks, but must have the
+ CONNECT privilege for the database. If you wish to
+ restrict which users can connect to which databases, it's usually
+ easier to control this by granting/revoking CONNECT privilege
+ than to put the rules in pg_hba.conf entries.
+
+ Some examples of pg_hba.conf entries are shown in
+ Example 21.1. See the next section for details on the
+ different authentication methods.
+
Example 21.1. Example pg_hba.conf Entries
+# Allow any user on the local system to connect to any database with
+# any database user name using Unix-domain sockets (the default for local
+# connections).
+#
+# TYPE DATABASE USER ADDRESS METHOD
+local all all trust
+
+# The same using local loopback TCP/IP connections.
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host all all 127.0.0.1/32 trust
+
+# The same as the previous line, but using a separate netmask column
+#
+# TYPE DATABASE USER IP-ADDRESS IP-MASK METHOD
+host all all 127.0.0.1 255.255.255.255 trust
+
+# The same over IPv6.
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host all all ::1/128 trust
+
+# The same using a host name (would typically cover both IPv4 and IPv6).
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host all all localhost trust
+
+# The same using a regular expression for DATABASE, that allows connection
+# to the database db1, db2 and any databases with a name beginning with "db"
+# and finishing with a number using two to four digits (like "db1234" or
+# "db12").
+#
+# TYPE DATABASE USER ADDRESS METHOD
+local db1,"/^db\d{2,4}$",db2 all localhost trust
+
+# Allow any user from any host with IP address 192.168.93.x to connect
+# to database "postgres" as the same user name that ident reports for
+# the connection (typically the operating system user name).
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host postgres all 192.168.93.0/24 ident
+
+# Allow any user from host 192.168.12.10 to connect to database
+# "postgres" if the user's password is correctly supplied.
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host postgres all 192.168.12.10/32 scram-sha-256
+
+# Allow any user from hosts in the example.com domain to connect to
+# any database if the user's password is correctly supplied.
+#
+# Require SCRAM authentication for most users, but make an exception
+# for user 'mike', who uses an older client that doesn't support SCRAM
+# authentication.
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host all mike .example.com md5
+host all all .example.com scram-sha-256
+
+# In the absence of preceding "host" lines, these three lines will
+# reject all connections from 192.168.54.1 (since that entry will be
+# matched first), but allow GSSAPI-encrypted connections from anywhere else
+# on the Internet. The zero mask causes no bits of the host IP address to
+# be considered, so it matches any host. Unencrypted GSSAPI connections
+# (which "fall through" to the third line since "hostgssenc" only matches
+# encrypted GSSAPI connections) are allowed, but only from 192.168.12.10.
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host all all 192.168.54.1/32 reject
+hostgssenc all all 0.0.0.0/0 gss
+host all all 192.168.12.10/32 gss
+
+# Allow users from 192.168.x.x hosts to connect to any database, if
+# they pass the ident check. If, for example, ident says the user is
+# "bryanh" and he requests to connect as PostgreSQL user "guest1", the
+# connection is allowed if there is an entry in pg_ident.conf for map
+# "omicron" that says "bryanh" is allowed to connect as "guest1".
+#
+# TYPE DATABASE USER ADDRESS METHOD
+host all all 192.168.0.0/16 ident map=omicron
+
+# If these are the only four lines for local connections, they will
+# allow local users to connect only to their own databases (databases
+# with the same name as their database user name) except for users whose
+# name end with "helpdesk", administrators and members of role "support",
+# who can connect to all databases. The file $PGDATA/admins contains a
+# list of names of administrators. Passwords are required in all cases.
+#
+# TYPE DATABASE USER ADDRESS METHOD
+local sameuser all md5
+local all /^.*helpdesk$ md5
+local all @admins md5
+local all +support md5
+
+# The last two lines above can be combined into a single line:
+local all @admins,+support md5
+
+# The database column can also use lists and file names:
+local db1,db2,@demodbs all md5
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-radius.html b/pgsql/doc/postgresql/html/auth-radius.html
new file mode 100644
index 0000000000000000000000000000000000000000..b11fc73b0e6f0081d96c7de7dbb0f8a4907c0dc5
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-radius.html
@@ -0,0 +1,65 @@
+
+21.11. RADIUS Authentication
+ This authentication method operates similarly to
+ password except that it uses RADIUS
+ as the password verification method. RADIUS is used only to validate
+ the user name/password pairs. Therefore the user must already
+ exist in the database before RADIUS can be used for
+ authentication.
+
+ When using RADIUS authentication, an Access Request message will be sent
+ to the configured RADIUS server. This request will be of type
+ Authenticate Only, and include parameters for
+ user name, password (encrypted) and
+ NAS Identifier. The request will be encrypted using
+ a secret shared with the server. The RADIUS server will respond to
+ this request with either Access Accept or
+ Access Reject. There is no support for RADIUS accounting.
+
+ Multiple RADIUS servers can be specified, in which case they will
+ be tried sequentially. If a negative response is received from
+ a server, the authentication will fail. If no response is received,
+ the next server in the list will be tried. To specify multiple
+ servers, separate the server names with commas and surround the list
+ with double quotes. If multiple servers are specified, the other
+ RADIUS options can also be given as comma-separated lists, to provide
+ individual values for each server. They can also be specified as
+ a single value, in which case that value will apply to all servers.
+
+ The following configuration options are supported for RADIUS:
+
radiusservers
+ The DNS names or IP addresses of the RADIUS servers to connect to.
+ This parameter is required.
+
radiussecrets
+ The shared secrets used when talking securely to the RADIUS
+ servers. This must have exactly the same value on the PostgreSQL
+ and RADIUS servers. It is recommended that this be a string of
+ at least 16 characters. This parameter is required.
+
Note
+ The encryption vector used will only be cryptographically
+ strong if PostgreSQL is built with support for
+ OpenSSL. In other cases, the transmission to the
+ RADIUS server should only be considered obfuscated, not secured, and
+ external security measures should be applied if necessary.
+
+
radiusports
+ The port numbers to connect to on the RADIUS servers. If no port
+ is specified, the default RADIUS port (1812)
+ will be used.
+
radiusidentifiers
+ The strings to be used as NAS Identifier in the
+ RADIUS requests. This parameter can be used, for example, to
+ identify which database cluster the user is attempting to connect
+ to, which can be useful for policy matching on
+ the RADIUS server. If no identifier is specified, the default
+ postgresql will be used.
+
+
+ If it is necessary to have a comma or whitespace in a RADIUS parameter
+ value, that can be done by putting double quotes around the value, but
+ it is tedious because two layers of double-quoting are now required.
+ An example of putting whitespace into RADIUS secret strings is:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-trust.html b/pgsql/doc/postgresql/html/auth-trust.html
new file mode 100644
index 0000000000000000000000000000000000000000..bc05d5f639c6fb5451c845865effdee09cfada46
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-trust.html
@@ -0,0 +1,37 @@
+
+21.4. Trust Authentication
+ When trust authentication is specified,
+ PostgreSQL assumes that anyone who can
+ connect to the server is authorized to access the database with
+ whatever database user name they specify (even superuser names).
+ Of course, restrictions made in the database and
+ user columns still apply.
+ This method should only be used when there is adequate
+ operating-system-level protection on connections to the server.
+
+ trust authentication is appropriate and very
+ convenient for local connections on a single-user workstation. It
+ is usually not appropriate by itself on a multiuser
+ machine. However, you might be able to use trust even
+ on a multiuser machine, if you restrict access to the server's
+ Unix-domain socket file using file-system permissions. To do this, set the
+ unix_socket_permissions (and possibly
+ unix_socket_group) configuration parameters as
+ described in Section 20.3. Or you
+ could set the unix_socket_directories
+ configuration parameter to place the socket file in a suitably
+ restricted directory.
+
+ Setting file-system permissions only helps for Unix-socket connections.
+ Local TCP/IP connections are not restricted by file-system permissions.
+ Therefore, if you want to use file-system permissions for local security,
+ remove the host ... 127.0.0.1 ... line from
+ pg_hba.conf, or change it to a
+ non-trust authentication method.
+
+ trust authentication is only suitable for TCP/IP connections
+ if you trust every user on every machine that is allowed to connect
+ to the server by the pg_hba.conf lines that specify
+ trust. It is seldom reasonable to use trust
+ for any TCP/IP connections other than those from localhost (127.0.0.1).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auth-username-maps.html b/pgsql/doc/postgresql/html/auth-username-maps.html
new file mode 100644
index 0000000000000000000000000000000000000000..f496fc763c928090ba95f9dbd231f7089e6ec5f2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auth-username-maps.html
@@ -0,0 +1,134 @@
+
+21.2. User Name Maps
+ When using an external authentication system such as Ident or GSSAPI,
+ the name of the operating system user that initiated the connection
+ might not be the same as the database user (role) that is to be used.
+ In this case, a user name map can be applied to map the operating system
+ user name to a database user. To use user name mapping, specify
+ map=map-name
+ in the options field in pg_hba.conf. This option is
+ supported for all authentication methods that receive external user names.
+ Since different mappings might be needed for different connections,
+ the name of the map to be used is specified in the
+ map-name parameter in pg_hba.conf
+ to indicate which map to use for each individual connection.
+
+ User name maps are defined in the ident map file, which by default is named
+ pg_ident.conf
+ and is stored in the
+ cluster's data directory. (It is possible to place the map file
+ elsewhere, however; see the ident_file
+ configuration parameter.)
+ The ident map file contains lines of the general forms:
+
+ Comments, whitespace and line continuations are handled in the same way as in
+ pg_hba.conf. The
+ map-name is an arbitrary name that will be used to
+ refer to this mapping in pg_hba.conf. The other
+ two fields specify an operating system user name and a matching
+ database user name. The same map-name can be
+ used repeatedly to specify multiple user-mappings within a single map.
+
+ As for pg_hba.conf, the lines in this file can
+ be include directives, following the same rules.
+
+ There is no restriction regarding how many database users a given
+ operating system user can correspond to, nor vice versa. Thus, entries
+ in a map should be thought of as meaning “this operating system
+ user is allowed to connect as this database user”, rather than
+ implying that they are equivalent. The connection will be allowed if
+ there is any map entry that pairs the user name obtained from the
+ external authentication system with the database user name that the
+ user has requested to connect as. The value all
+ can be used as the database-username to specify
+ that if the system-username matches, then this
+ user is allowed to log in as any of the existing database users. Quoting
+ all makes the keyword lose its special meaning.
+
+ If the database-username begins with a
+ + character, then the operating system user can login as
+ any user belonging to that role, similarly to how user names beginning with
+ + are treated in pg_hba.conf.
+ Thus, a + mark means “match any of the roles that
+ are directly or indirectly members of this role”, while a name
+ without a + mark matches only that specific role. Quoting
+ a username starting with a + makes the
+ + lose its special meaning.
+
+ If the system-username field starts with a slash (/),
+ the remainder of the field is treated as a regular expression.
+ (See Section 9.7.3.1 for details of
+ PostgreSQL's regular expression syntax.) The regular
+ expression can include a single capture, or parenthesized subexpression,
+ which can then be referenced in the database-username
+ field as \1 (backslash-one). This allows the mapping of
+ multiple user names in a single line, which is particularly useful for
+ simple syntax substitutions. For example, these entries
+
+ will remove the domain part for users with system user names that end with
+ @mydomain.com, and allow any user whose system name ends with
+ @otherdomain.com to log in as guest.
+ Quoting a database-username containing
+ \1does not make
+ \1 lose its special meaning.
+
+ If the database-username field starts with
+ a slash (/), the remainder of the field is treated
+ as a regular expression (see Section 9.7.3.1
+ for details of PostgreSQL's regular
+ expression syntax). It is not possible to use \1
+ to use a capture from regular expression on
+ system-username for a regular expression
+ on database-username.
+
Tip
+ Keep in mind that by default, a regular expression can match just part of
+ a string. It's usually wise to use ^ and $, as
+ shown in the above example, to force the match to be to the entire
+ system user name.
+
+ The pg_ident.conf file is read on start-up and
+ when the main server process receives a
+ SIGHUP
+ signal. If you edit the file on an
+ active system, you will need to signal the postmaster
+ (using pg_ctl reload, calling the SQL function
+ pg_reload_conf(), or using kill
+ -HUP) to make it re-read the file.
+
+ The system view
+ pg_ident_file_mappings
+ can be helpful for pre-testing changes to the
+ pg_ident.conf file, or for diagnosing problems if
+ loading of the file did not have the desired effects. Rows in the view with
+ non-null error fields indicate problems in the
+ corresponding lines of the file.
+
+ A pg_ident.conf file that could be used in
+ conjunction with the pg_hba.conf file in Example 21.1 is shown in Example 21.2. In this example, anyone
+ logged in to a machine on the 192.168 network that does not have the
+ operating system user name bryanh, ann, or
+ robert would not be granted access. Unix user
+ robert would only be allowed access when he tries to
+ connect as PostgreSQL user bob, not
+ as robert or anyone else. ann would
+ only be allowed to connect as ann. User
+ bryanh would be allowed to connect as either
+ bryanh or as guest1.
+
Example 21.2. An Example pg_ident.conf File
+# MAPNAME SYSTEM-USERNAME PG-USERNAME
+
+omicron bryanh bryanh
+omicron ann ann
+# bob has user name robert on these machines
+omicron robert bob
+# bryanh can also connect as guest1
+omicron bryanh guest1
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/auto-explain.html b/pgsql/doc/postgresql/html/auto-explain.html
new file mode 100644
index 0000000000000000000000000000000000000000..e53796fd27d800887ea580058d674a0452bfa6b6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/auto-explain.html
@@ -0,0 +1,199 @@
+
+F.4. auto_explain — log execution plans of slow queries
F.4. auto_explain — log execution plans of slow queries
+ The auto_explain module provides a means for
+ logging execution plans of slow statements automatically, without
+ having to run EXPLAIN
+ by hand. This is especially helpful for tracking down un-optimized queries
+ in large applications.
+
+ The module provides no SQL-accessible functions. To use it, simply
+ load it into the server. You can load it into an individual session:
+
+
+LOAD 'auto_explain';
+
+
+ (You must be superuser to do that.) More typical usage is to preload
+ it into some or all sessions by including auto_explain in
+ session_preload_libraries or
+ shared_preload_libraries in
+ postgresql.conf. Then you can track unexpectedly slow queries
+ no matter when they happen. Of course there is a price in overhead for
+ that.
+
+ There are several configuration parameters that control the behavior of
+ auto_explain. Note that the default behavior is
+ to do nothing, so you must set at least
+ auto_explain.log_min_duration if you want any results.
+
+ auto_explain.log_min_duration is the minimum statement
+ execution time, in milliseconds, that will cause the statement's plan to
+ be logged. Setting this to 0 logs all plans.
+ -1 (the default) disables logging of plans. For
+ example, if you set it to 250ms then all statements
+ that run 250ms or longer will be logged. Only superusers can change this
+ setting.
+
+ auto_explain.log_parameter_max_length controls the
+ logging of query parameter values. A value of -1 (the
+ default) logs the parameter values in full. 0 disables
+ logging of parameter values. A value greater than zero truncates each
+ parameter value to that many bytes. Only superusers can change this
+ setting.
+
+ auto_explain.log_analyze causes EXPLAIN ANALYZE
+ output, rather than just EXPLAIN output, to be printed
+ when an execution plan is logged. This parameter is off by default.
+ Only superusers can change this setting.
+
Note
+ When this parameter is on, per-plan-node timing occurs for all
+ statements executed, whether or not they run long enough to actually
+ get logged. This can have an extremely negative impact on performance.
+ Turning off auto_explain.log_timing ameliorates the
+ performance cost, at the price of obtaining less information.
+
+ auto_explain.log_buffers controls whether buffer
+ usage statistics are printed when an execution plan is logged; it's
+ equivalent to the BUFFERS option of EXPLAIN.
+ This parameter has no effect
+ unless auto_explain.log_analyze is enabled.
+ This parameter is off by default.
+ Only superusers can change this setting.
+
+ auto_explain.log_wal controls whether WAL
+ usage statistics are printed when an execution plan is logged; it's
+ equivalent to the WAL option of EXPLAIN.
+ This parameter has no effect
+ unless auto_explain.log_analyze is enabled.
+ This parameter is off by default.
+ Only superusers can change this setting.
+
+ auto_explain.log_timing controls whether per-node
+ timing information is printed when an execution plan is logged; it's
+ equivalent to the TIMING option of EXPLAIN.
+ The overhead of repeatedly reading the system clock can slow down
+ queries significantly on some systems, so it may be useful to set this
+ parameter to off when only actual row counts, and not exact times, are
+ needed.
+ This parameter has no effect
+ unless auto_explain.log_analyze is enabled.
+ This parameter is on by default.
+ Only superusers can change this setting.
+
+ auto_explain.log_triggers causes trigger
+ execution statistics to be included when an execution plan is logged.
+ This parameter has no effect
+ unless auto_explain.log_analyze is enabled.
+ This parameter is off by default.
+ Only superusers can change this setting.
+
+ auto_explain.log_verbose controls whether verbose
+ details are printed when an execution plan is logged; it's
+ equivalent to the VERBOSE option of EXPLAIN.
+ This parameter is off by default.
+ Only superusers can change this setting.
+
+ auto_explain.log_settings controls whether information
+ about modified configuration options is printed when an execution plan is logged.
+ Only options affecting query planning with value different from the built-in
+ default value are included in the output. This parameter is off by default.
+ Only superusers can change this setting.
+
+ auto_explain.log_format selects the
+ EXPLAIN output format to be used.
+ The allowed values are text, xml,
+ json, and yaml. The default is text.
+ Only superusers can change this setting.
+
+ auto_explain.log_level selects the log level at which
+ auto_explain will log the query plan.
+ Valid values are DEBUG5, DEBUG4,
+ DEBUG3, DEBUG2,
+ DEBUG1, INFO,
+ NOTICE, WARNING,
+ and LOG. The default is LOG.
+ Only superusers can change this setting.
+
+ auto_explain.log_nested_statements causes nested
+ statements (statements executed inside a function) to be considered
+ for logging. When it is off, only top-level query plans are logged. This
+ parameter is off by default. Only superusers can change this setting.
+
+ auto_explain.sample_rate causes auto_explain to only
+ explain a fraction of the statements in each session. The default is 1,
+ meaning explain all the queries. In case of nested statements, either all
+ will be explained or none. Only superusers can change this setting.
+
+ In ordinary usage, these parameters are set
+ in postgresql.conf, although superusers can alter them
+ on-the-fly within their own sessions.
+ Typical usage might be:
+
+postgres=# LOAD 'auto_explain';
+postgres=# SET auto_explain.log_min_duration = 0;
+postgres=# SET auto_explain.log_analyze = true;
+postgres=# SELECT count(*)
+ FROM pg_class, pg_index
+ WHERE oid = indrelid AND indisunique;
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup-dump.html b/pgsql/doc/postgresql/html/backup-dump.html
new file mode 100644
index 0000000000000000000000000000000000000000..423cc2d4271dea12e75179134e9e76d14a565510
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup-dump.html
@@ -0,0 +1,247 @@
+
+26.1. SQL Dump
+ The idea behind this dump method is to generate a file with SQL
+ commands that, when fed back to the server, will recreate the
+ database in the same state as it was at the time of the dump.
+ PostgreSQL provides the utility program
+ pg_dump for this purpose. The basic usage of this
+ command is:
+
+pg_dump dbname > dumpfile
+
+ As you see, pg_dump writes its result to the
+ standard output. We will see below how this can be useful.
+ While the above command creates a text file, pg_dump
+ can create files in other formats that allow for parallelism and more
+ fine-grained control of object restoration.
+
+ pg_dump is a regular PostgreSQL
+ client application (albeit a particularly clever one). This means
+ that you can perform this backup procedure from any remote host that has
+ access to the database. But remember that pg_dump
+ does not operate with special permissions. In particular, it must
+ have read access to all tables that you want to back up, so in order
+ to back up the entire database you almost always have to run it as a
+ database superuser. (If you do not have sufficient privileges to back up
+ the entire database, you can still back up portions of the database to which
+ you do have access using options such as
+ -n schema
+ or -t table.)
+
+ To specify which database server pg_dump should
+ contact, use the command line options -h
+ host and -p port. The
+ default host is the local host or whatever your
+ PGHOST environment variable specifies. Similarly,
+ the default port is indicated by the PGPORT
+ environment variable or, failing that, by the compiled-in default.
+ (Conveniently, the server will normally have the same compiled-in
+ default.)
+
+ Like any other PostgreSQL client application,
+ pg_dump will by default connect with the database
+ user name that is equal to the current operating system user name. To override
+ this, either specify the -U option or set the
+ environment variable PGUSER. Remember that
+ pg_dump connections are subject to the normal
+ client authentication mechanisms (which are described in Chapter 21).
+
+ An important advantage of pg_dump over the other backup
+ methods described later is that pg_dump's output can
+ generally be re-loaded into newer versions of PostgreSQL,
+ whereas file-level backups and continuous archiving are both extremely
+ server-version-specific. pg_dump is also the only method
+ that will work when transferring a database to a different machine
+ architecture, such as going from a 32-bit to a 64-bit server.
+
+ Dumps created by pg_dump are internally consistent,
+ meaning, the dump represents a snapshot of the database at the time
+ pg_dump began running. pg_dump does not
+ block other operations on the database while it is working.
+ (Exceptions are those operations that need to operate with an
+ exclusive lock, such as most forms of ALTER TABLE.)
+
+ Text files created by pg_dump are intended to
+ be read in by the psql program. The
+ general command form to restore a dump is
+
+psql dbname < dumpfile
+
+ where dumpfile is the
+ file output by the pg_dump command. The database dbname will not be created by this
+ command, so you must create it yourself from template0
+ before executing psql (e.g., with
+ createdb -T template0 dbname). psql
+ supports options similar to pg_dump for specifying
+ the database server to connect to and the user name to use. See
+ the psql reference page for more information.
+ Non-text file dumps are restored using the pg_restore utility.
+
+ Before restoring an SQL dump, all the users who own objects or were
+ granted permissions on objects in the dumped database must already
+ exist. If they do not, the restore will fail to recreate the
+ objects with the original ownership and/or permissions.
+ (Sometimes this is what you want, but usually it is not.)
+
+ By default, the psql script will continue to
+ execute after an SQL error is encountered. You might wish to run
+ psql with
+ the ON_ERROR_STOP variable set to alter that
+ behavior and have psql exit with an
+ exit status of 3 if an SQL error occurs:
+
+psql --set ON_ERROR_STOP=on dbname < dumpfile
+
+ Either way, you will only have a partially restored database.
+ Alternatively, you can specify that the whole dump should be
+ restored as a single transaction, so the restore is either fully
+ completed or fully rolled back. This mode can be specified by
+ passing the -1 or --single-transaction
+ command-line options to psql. When using this
+ mode, be aware that even a minor error can rollback a
+ restore that has already run for many hours. However, that might
+ still be preferable to manually cleaning up a complex database
+ after a partially restored dump.
+
+ The ability of pg_dump and psql to
+ write to or read from pipes makes it possible to dump a database
+ directly from one server to another, for example:
+
+pg_dump -h host1dbname | psql -h host2dbname
+
+
Important
+ The dumps produced by pg_dump are relative to
+ template0. This means that any languages, procedures,
+ etc. added via template1 will also be dumped by
+ pg_dump. As a result, when restoring, if you are
+ using a customized template1, you must create the
+ empty database from template0, as in the example
+ above.
+
+ After restoring a backup, it is wise to run ANALYZE on each
+ database so the query optimizer has useful statistics;
+ see Section 25.1.3
+ and Section 25.1.6 for more information.
+ For more advice on how to load large amounts of data
+ into PostgreSQL efficiently, refer to Section 14.4.
+
+ pg_dump dumps only a single database at a time,
+ and it does not dump information about roles or tablespaces
+ (because those are cluster-wide rather than per-database).
+ To support convenient dumping of the entire contents of a database
+ cluster, the pg_dumpall program is provided.
+ pg_dumpall backs up each database in a given
+ cluster, and also preserves cluster-wide data such as role and
+ tablespace definitions. The basic usage of this command is:
+
+pg_dumpall > dumpfile
+
+ The resulting dump can be restored with psql:
+
+psql -f dumpfile postgres
+
+ (Actually, you can specify any existing database name to start from,
+ but if you are loading into an empty cluster then postgres
+ should usually be used.) It is always necessary to have
+ database superuser access when restoring a pg_dumpall
+ dump, as that is required to restore the role and tablespace information.
+ If you use tablespaces, make sure that the tablespace paths in the
+ dump are appropriate for the new installation.
+
+ pg_dumpall works by emitting commands to re-create
+ roles, tablespaces, and empty databases, then invoking
+ pg_dump for each database. This means that while
+ each database will be internally consistent, the snapshots of
+ different databases are not synchronized.
+
+ Cluster-wide data can be dumped alone using the
+ pg_dumpall--globals-only option.
+ This is necessary to fully backup the cluster if running the
+ pg_dump command on individual databases.
+
+ Some operating systems have maximum file size limits that cause
+ problems when creating large pg_dump output files.
+ Fortunately, pg_dump can write to the standard
+ output, so you can use standard Unix tools to work around this
+ potential problem. There are several possible methods:
+
Use compressed dumps.
+ You can use your favorite compression program, for example
+ gzip:
+
+
+pg_dump dbname | gzip > filename.gz
+
+
+ Reload with:
+
+
+gunzip -c filename.gz | psql dbname
+
+
+ or:
+
+
+cat filename.gz | gunzip | psql dbname
+
+
Use split.
+ The split command
+ allows you to split the output into smaller files that are
+ acceptable in size to the underlying file system. For example, to
+ make 2 gigabyte chunks:
+
+
+pg_dump dbname | split -b 2G - filename
+
+
+ Reload with:
+
+
+cat filename* | psql dbname
+
+
+ If using GNU split, it is possible to
+ use it and gzip together:
+
+
Use pg_dump's custom dump format.
+ If PostgreSQL was built on a system with the
+ zlib compression library installed, the custom dump
+ format will compress data as it writes it to the output file. This will
+ produce dump file sizes similar to using gzip, but it
+ has the added advantage that tables can be restored selectively. The
+ following command dumps a database using the custom dump format:
+
+
+pg_dump -Fc dbname > filename
+
+
+ A custom-format dump is not a script for psql, but
+ instead must be restored with pg_restore, for example:
+
+
+ For very large databases, you might need to combine split
+ with one of the other two approaches.
+
Use pg_dump's parallel dump feature.
+ To speed up the dump of a large database, you can use
+ pg_dump's parallel mode. This will dump
+ multiple tables at the same time. You can control the degree of
+ parallelism with the -j parameter. Parallel dumps
+ are only supported for the "directory" archive format.
+
+
+pg_dump -j num -F d -f out.dirdbname
+
+
+ You can use pg_restore -j to restore a dump in parallel.
+ This will work for any archive of either the "custom" or the "directory"
+ archive mode, whether or not it has been created with pg_dump -j.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup-file.html b/pgsql/doc/postgresql/html/backup-file.html
new file mode 100644
index 0000000000000000000000000000000000000000..b57ca61a7d16d687235cf81147ba944c6137d823
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup-file.html
@@ -0,0 +1,91 @@
+
+26.2. File System Level Backup
+ An alternative backup strategy is to directly copy the files that
+ PostgreSQL uses to store the data in the database;
+ Section 19.2 explains where these files
+ are located. You can use whatever method you prefer
+ for doing file system backups; for example:
+
+
+tar -cf backup.tar /usr/local/pgsql/data
+
+
+ There are two restrictions, however, which make this method
+ impractical, or at least inferior to the pg_dump
+ method:
+
+
+ The database server must be shut down in order to
+ get a usable backup. Half-way measures such as disallowing all
+ connections will not work
+ (in part because tar and similar tools do not take
+ an atomic snapshot of the state of the file system,
+ but also because of internal buffering within the server).
+ Information about stopping the server can be found in
+ Section 19.5. Needless to say, you
+ also need to shut down the server before restoring the data.
+
+ If you have dug into the details of the file system layout of the
+ database, you might be tempted to try to back up or restore only certain
+ individual tables or databases from their respective files or
+ directories. This will not work because the
+ information contained in these files is not usable without
+ the commit log files,
+ pg_xact/*, which contain the commit status of
+ all transactions. A table file is only usable with this
+ information. Of course it is also impossible to restore only a
+ table and the associated pg_xact data
+ because that would render all other tables in the database
+ cluster useless. So file system backups only work for complete
+ backup and restoration of an entire database cluster.
+
+
+ An alternative file-system backup approach is to make a
+ “consistent snapshot” of the data directory, if the
+ file system supports that functionality (and you are willing to
+ trust that it is implemented correctly). The typical procedure is
+ to make a “frozen snapshot” of the volume containing the
+ database, then copy the whole data directory (not just parts, see
+ above) from the snapshot to a backup device, then release the frozen
+ snapshot. This will work even while the database server is running.
+ However, a backup created in this way saves
+ the database files in a state as if the database server was not
+ properly shut down; therefore, when you start the database server
+ on the backed-up data, it will think the previous server instance
+ crashed and will replay the WAL log. This is not a problem; just
+ be aware of it (and be sure to include the WAL files in your backup).
+ You can perform a CHECKPOINT before taking the
+ snapshot to reduce recovery time.
+
+ If your database is spread across multiple file systems, there might not
+ be any way to obtain exactly-simultaneous frozen snapshots of all
+ the volumes. For example, if your data files and WAL log are on different
+ disks, or if tablespaces are on different file systems, it might
+ not be possible to use snapshot backup because the snapshots
+ must be simultaneous.
+ Read your file system documentation very carefully before trusting
+ the consistent-snapshot technique in such situations.
+
+ If simultaneous snapshots are not possible, one option is to shut down
+ the database server long enough to establish all the frozen snapshots.
+ Another option is to perform a continuous archiving base backup (Section 26.3.2) because such backups are immune to file
+ system changes during the backup. This requires enabling continuous
+ archiving just during the backup process; restore is done using
+ continuous archive recovery (Section 26.3.4).
+
+ Another option is to use rsync to perform a file
+ system backup. This is done by first running rsync
+ while the database server is running, then shutting down the database
+ server long enough to do an rsync --checksum.
+ (--checksum is necessary because rsync only
+ has file modification-time granularity of one second.) The
+ second rsync will be quicker than the first,
+ because it has relatively little data to transfer, and the end result
+ will be consistent because the server was down. This method
+ allows a file system backup to be performed with minimal downtime.
+
+ Note that a file system backup will typically be larger
+ than an SQL dump. (pg_dump does not need to dump
+ the contents of indexes for example, just the commands to recreate
+ them.) However, taking a file system backup might be faster.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup-manifest-files.html b/pgsql/doc/postgresql/html/backup-manifest-files.html
new file mode 100644
index 0000000000000000000000000000000000000000..d8678971e80d9cac9671d4cdbc18ef7986c57035
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup-manifest-files.html
@@ -0,0 +1,39 @@
+
+77.2. Backup Manifest File Object
+ The object which describes a single file contains either a
+ Path key or an Encoded-Path key.
+ Normally, the Path key will be present. The
+ associated string value is the path of the file relative to the root
+ of the backup directory. Files located in a user-defined tablespace
+ will have paths whose first two components are pg_tblspc and the OID
+ of the tablespace. If the path is not a string that is legal in UTF-8,
+ or if the user requests that encoded paths be used for all files, then
+ the Encoded-Path key will be present instead. This
+ stores the same data, but it is encoded as a string of hexadecimal
+ digits. Each pair of hexadecimal digits in the string represents a
+ single octet.
+
+ The following two keys are always present:
+
Size
+ The expected size of this file, as an integer.
+
Last-Modified
+ The last modification time of the file as reported by the server at
+ the time of the backup. Unlike the other fields stored in the backup,
+ this field is not used by pg_verifybackup.
+ It is included only for informational purposes.
+
+ If the backup was taken with file checksums enabled, the following
+ keys will be present:
+
Checksum-Algorithm
+ The checksum algorithm used to compute a checksum for this file.
+ Currently, this will be the same for every file in the backup
+ manifest, but this may change in future releases. At present, the
+ supported checksum algorithms are CRC32C,
+ SHA224,
+ SHA256,
+ SHA384, and
+ SHA512.
+
Checksum
+ The checksum computed for this file, stored as a series of
+ hexadecimal characters, two for each byte of the checksum.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup-manifest-format.html b/pgsql/doc/postgresql/html/backup-manifest-format.html
new file mode 100644
index 0000000000000000000000000000000000000000..4e9185888fb1fa020d75eca19ba19dc11f36d6f2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup-manifest-format.html
@@ -0,0 +1,16 @@
+
+Chapter 77. Backup Manifest Format
+ The backup manifest generated by pg_basebackup is
+ primarily intended to permit the backup to be verified using
+ pg_verifybackup. However, it is
+ also possible for other tools to read the backup manifest file and use
+ the information contained therein for their own purposes. To that end,
+ this chapter describes the format of the backup manifest file.
+
+ A backup manifest is a JSON document encoded as UTF-8. (Although in
+ general JSON documents are required to be Unicode, PostgreSQL permits
+ the json and jsonb data types to be used with any
+ supported server encoding. There is no similar exception for backup
+ manifests.) The JSON document is always an object; the keys that are present
+ in this object are described in the next section.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup-manifest-toplevel.html b/pgsql/doc/postgresql/html/backup-manifest-toplevel.html
new file mode 100644
index 0000000000000000000000000000000000000000..7730ca9236243957c57a8217b328ea24d2476e10
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup-manifest-toplevel.html
@@ -0,0 +1,25 @@
+
+77.1. Backup Manifest Top-level Object
+ The backup manifest JSON document contains the following keys.
+
PostgreSQL-Backup-Manifest-Version
+ The associated value is always the integer 1.
+
Files
+ The associated value is always a list of objects, each describing one
+ file that is present in the backup. No entries are present in this
+ list for the WAL files that are needed in order to use the backup,
+ or for the backup manifest itself. The structure of each object in the
+ list is described in Section 77.2.
+
WAL-Ranges
+ The associated value is always a list of objects, each describing a
+ range of WAL records that must be readable from a particular timeline
+ in order to make use of the backup. The structure of these objects is
+ further described in Section 77.3.
+
Manifest-Checksum
+ This key is always present on the last line of the backup manifest file.
+ The associated value is a SHA256 checksum of all the preceding lines.
+ We use a fixed checksum method here to make it possible for clients
+ to do incremental parsing of the manifest. While a SHA256 checksum
+ is significantly more expensive than a CRC32C checksum, the manifest
+ should normally be small enough that the extra computation won't matter
+ very much.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup-manifest-wal-ranges.html b/pgsql/doc/postgresql/html/backup-manifest-wal-ranges.html
new file mode 100644
index 0000000000000000000000000000000000000000..b67af964c5c67861d6f8958c03ac4a9576dad8a1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup-manifest-wal-ranges.html
@@ -0,0 +1,22 @@
+
+77.3. Backup Manifest WAL Range Object
+ The object which describes a WAL range always has three keys:
+
Timeline
+ The timeline for this range of WAL records, as an integer.
+
Start-LSN
+ The LSN at which replay must begin on the indicated timeline in order to
+ make use of this backup. The LSN is stored in the format normally used
+ by PostgreSQL; that is, it is a string
+ consisting of two strings of hexadecimal characters, each with a length
+ of between 1 and 8, separated by a slash.
+
End-LSN
+ The earliest LSN at which replay on the indicated timeline may end when
+ making use of this backup. This is stored in the same format as
+ Start-LSN.
+
+ Ordinarily, there will be only a single WAL range. However, if a backup is
+ taken from a standby which switches timelines during the backup due to an
+ upstream promotion, it is possible for multiple ranges to be present, each
+ with a different timeline. There will never be multiple WAL ranges present
+ for the same timeline.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/backup.html b/pgsql/doc/postgresql/html/backup.html
new file mode 100644
index 0000000000000000000000000000000000000000..d077721f090d05d29268f7184d9dcf2c1b6ce7b8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/backup.html
@@ -0,0 +1,13 @@
+
+Chapter 26. Backup and Restore
+ As with everything that contains valuable data, PostgreSQL
+ databases should be backed up regularly. While the procedure is
+ essentially simple, it is important to have a clear understanding of
+ the underlying techniques and assumptions.
+
+ There are three fundamentally different approaches to backing up
+ PostgreSQL data:
+
SQL dump
File system level backup
Continuous archiving
+ Each has its own strengths and weaknesses; each is discussed in turn
+ in the following sections.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/basebackup-to-shell.html b/pgsql/doc/postgresql/html/basebackup-to-shell.html
new file mode 100644
index 0000000000000000000000000000000000000000..b3c3fdb64d6b23dbf8f80a89810f39fadacca522
--- /dev/null
+++ b/pgsql/doc/postgresql/html/basebackup-to-shell.html
@@ -0,0 +1,43 @@
+
+F.5. basebackup_to_shell — example "shell" pg_basebackup module
F.5. basebackup_to_shell — example "shell" pg_basebackup module
+ basebackup_to_shell adds a custom basebackup target
+ called shell. This makes it possible to run
+ pg_basebackup --target=shell or, depending on how this
+ module is configured,
+ pg_basebackup --target=shell:DETAIL_STRING,
+ and cause a server command chosen by the server administrator to be executed
+ for each tar archive generated by the backup process. The command will receive
+ the contents of the archive via standard input.
+
+ This module is primarily intended as an example of how to create a new
+ backup targets via an extension module, but in some scenarios it may be
+ useful for its own sake.
+ In order to function, this module must be loaded via
+ shared_preload_libraries or
+ local_preload_libraries.
+
+ The command which the server should execute for each archive generated
+ by the backup process. If %f occurs in the command
+ string, it will be replaced by the name of the archive (e.g.
+ base.tar). If %d occurs in the
+ command string, it will be replaced by the target detail provided by
+ the user. A target detail is required if %d is
+ used in the command string, and prohibited otherwise. For security
+ reasons, it may contain only alphanumeric characters. If
+ %% occurs in the command string, it will be replaced
+ by a single %. If % occurs in
+ the command string followed by any other character or at the end of the
+ string, an error occurs.
+
+ basebackup_to_shell.required_role (string)
+
+
+ The role required in order to make use of the shell
+ backup target. If this is not set, any replication user may make use of
+ the shell backup target.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/basic-archive.html b/pgsql/doc/postgresql/html/basic-archive.html
new file mode 100644
index 0000000000000000000000000000000000000000..f761dd3f0394f32133eb924398f68d264c74d606
--- /dev/null
+++ b/pgsql/doc/postgresql/html/basic-archive.html
@@ -0,0 +1,38 @@
+
+F.6. basic_archive — an example WAL archive module
F.6. basic_archive — an example WAL archive module
+ basic_archive is an example of an archive module. This
+ module copies completed WAL segment files to the specified directory. This
+ may not be especially useful, but it can serve as a starting point for
+ developing your own archive module. For more information about archive
+ modules, see Chapter 51.
+
+ In order to function, this module must be loaded via
+ archive_library, and archive_mode
+ must be enabled.
+
+ The directory where the server should copy WAL segment files. This
+ directory must already exist. The default is an empty string, which
+ effectively halts WAL archiving, but if archive_mode
+ is enabled, the server will accumulate WAL segment files in the
+ expectation that a value will soon be provided.
+
+ These parameters must be set in postgresql.conf.
+ Typical usage might be:
+
+ Server crashes may leave temporary files with the prefix
+ archtemp in the archive directory. It is recommended to
+ delete such files before restarting the server after a crash. It is safe to
+ remove such files while the server is running as long as they are unrelated
+ to any archiving still in progress, but users should use extra caution when
+ doing so.
+
+ PostgreSQL can be extended to run user-supplied code in separate processes.
+ Such processes are started, stopped and monitored by postgres,
+ which permits them to have a lifetime closely linked to the server's status.
+ These processes are attached to PostgreSQL's
+ shared memory area and have the option to connect to databases internally; they can also run
+ multiple transactions serially, just like a regular client-connected server
+ process. Also, by linking to libpq they can connect to the
+ server and behave like a regular client application.
+
Warning
+ There are considerable robustness and security risks in using background
+ worker processes because, being written in the C language,
+ they have unrestricted access to data. Administrators wishing to enable
+ modules that include background worker processes should exercise extreme
+ caution. Only carefully audited modules should be permitted to run
+ background worker processes.
+
+ Background workers can be initialized at the time that
+ PostgreSQL is started by including the module name in
+ shared_preload_libraries. A module wishing to run a background
+ worker can register it by calling
+ RegisterBackgroundWorker(BackgroundWorker
+ *worker)
+ from its _PG_init() function.
+ Background workers can also be started
+ after the system is up and running by calling
+ RegisterDynamicBackgroundWorker(BackgroundWorker
+ *worker, BackgroundWorkerHandle
+ **handle). Unlike
+ RegisterBackgroundWorker, which can only be called from
+ within the postmaster process,
+ RegisterDynamicBackgroundWorker must be called
+ from a regular backend or another background worker.
+
+ The structure BackgroundWorker is defined thus:
+
+typedef void (*bgworker_main_type)(Datum main_arg);
+typedef struct BackgroundWorker
+{
+ char bgw_name[BGW_MAXLEN];
+ char bgw_type[BGW_MAXLEN];
+ int bgw_flags;
+ BgWorkerStartTime bgw_start_time;
+ int bgw_restart_time; /* in seconds, or BGW_NEVER_RESTART */
+ char bgw_library_name[BGW_MAXLEN];
+ char bgw_function_name[BGW_MAXLEN];
+ Datum bgw_main_arg;
+ char bgw_extra[BGW_EXTRALEN];
+ pid_t bgw_notify_pid;
+} BackgroundWorker;
+
+
+ bgw_name and bgw_type are
+ strings to be used in log messages, process listings and similar contexts.
+ bgw_type should be the same for all background
+ workers of the same type, so that it is possible to group such workers in a
+ process listing, for example. bgw_name on the
+ other hand can contain additional information about the specific process.
+ (Typically, the string for bgw_name will contain
+ the type somehow, but that is not strictly required.)
+
+ bgw_flags is a bitwise-or'd bit mask indicating the
+ capabilities that the module wants. Possible values are:
+
BGWORKER_SHMEM_ACCESS
+
+ Requests shared memory access. This flag is required.
+
BGWORKER_BACKEND_DATABASE_CONNECTION
+
+ Requests the ability to establish a database connection through which it
+ can later run transactions and queries. A background worker using
+ BGWORKER_BACKEND_DATABASE_CONNECTION to connect to a
+ database must also attach shared memory using
+ BGWORKER_SHMEM_ACCESS, or worker start-up will fail.
+
+
+
+ bgw_start_time is the server state during which
+ postgres should start the process; it can be one of
+ BgWorkerStart_PostmasterStart (start as soon as
+ postgres itself has finished its own initialization; processes
+ requesting this are not eligible for database connections),
+ BgWorkerStart_ConsistentState (start as soon as a consistent state
+ has been reached in a hot standby, allowing processes to connect to
+ databases and run read-only queries), and
+ BgWorkerStart_RecoveryFinished (start as soon as the system has
+ entered normal read-write state). Note the last two values are equivalent
+ in a server that's not a hot standby. Note that this setting only indicates
+ when the processes are to be started; they do not stop when a different state
+ is reached.
+
+ bgw_restart_time is the interval, in seconds, that
+ postgres should wait before restarting the process in
+ the event that it crashes. It can be any positive value,
+ or BGW_NEVER_RESTART, indicating not to restart the
+ process in case of a crash.
+
+ bgw_library_name is the name of a library in
+ which the initial entry point for the background worker should be sought.
+ The named library will be dynamically loaded by the worker process and
+ bgw_function_name will be used to identify the
+ function to be called. If calling a function in the core code, this must
+ be set to "postgres".
+
+ bgw_function_name is the name of the function
+ to use as the initial entry point for the new background worker. If
+ this function is in a dynamically loaded library, it must be marked
+ PGDLLEXPORT (and not static).
+
+ bgw_main_arg is the Datum argument
+ to the background worker main function. This main function should take a
+ single argument of type Datum and return void.
+ bgw_main_arg will be passed as the argument.
+ In addition, the global variable MyBgworkerEntry
+ points to a copy of the BackgroundWorker structure
+ passed at registration time; the worker may find it helpful to examine
+ this structure.
+
+ On Windows (and anywhere else where EXEC_BACKEND is
+ defined) or in dynamic background workers it is not safe to pass a
+ Datum by reference, only by value. If an argument is required, it
+ is safest to pass an int32 or other small value and use that as an index
+ into an array allocated in shared memory. If a value like a cstring
+ or text is passed then the pointer won't be valid from the
+ new background worker process.
+
+ bgw_extra can contain extra data to be passed
+ to the background worker. Unlike bgw_main_arg, this data
+ is not passed as an argument to the worker's main function, but it can be
+ accessed via MyBgworkerEntry, as discussed above.
+
+ bgw_notify_pid is the PID of a PostgreSQL
+ backend process to which the postmaster should send SIGUSR1
+ when the process is started or exits. It should be 0 for workers registered
+ at postmaster startup time, or when the backend registering the worker does
+ not wish to wait for the worker to start up. Otherwise, it should be
+ initialized to MyProcPid.
+
Once running, the process can connect to a database by calling
+ BackgroundWorkerInitializeConnection(char *dbname, char *username, uint32 flags) or
+ BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags).
+ This allows the process to run transactions and queries using the
+ SPI interface. If dbname is NULL or
+ dboid is InvalidOid, the session is not connected
+ to any particular database, but shared catalogs can be accessed.
+ If username is NULL or useroid is
+ InvalidOid, the process will run as the superuser created
+ during initdb. If BGWORKER_BYPASS_ALLOWCONN
+ is specified as flags it is possible to bypass the restriction
+ to connect to databases not allowing user connections.
+ A background worker can only call one of these two functions, and only
+ once. It is not possible to switch databases.
+
+ Signals are initially blocked when control reaches the
+ background worker's main function, and must be unblocked by it; this is to
+ allow the process to customize its signal handlers, if necessary.
+ Signals can be unblocked in the new process by calling
+ BackgroundWorkerUnblockSignals and blocked by calling
+ BackgroundWorkerBlockSignals.
+
+ If bgw_restart_time for a background worker is
+ configured as BGW_NEVER_RESTART, or if it exits with an exit
+ code of 0 or is terminated by TerminateBackgroundWorker,
+ it will be automatically unregistered by the postmaster on exit.
+ Otherwise, it will be restarted after the time period configured via
+ bgw_restart_time, or immediately if the postmaster
+ reinitializes the cluster due to a backend failure. Backends which need
+ to suspend execution only temporarily should use an interruptible sleep
+ rather than exiting; this can be achieved by calling
+ WaitLatch(). Make sure the
+ WL_POSTMASTER_DEATH flag is set when calling that function, and
+ verify the return code for a prompt exit in the emergency case that
+ postgres itself has terminated.
+
+ When a background worker is registered using the
+ RegisterDynamicBackgroundWorker function, it is
+ possible for the backend performing the registration to obtain information
+ regarding the status of the worker. Backends wishing to do this should
+ pass the address of a BackgroundWorkerHandle * as the second
+ argument to RegisterDynamicBackgroundWorker. If the
+ worker is successfully registered, this pointer will be initialized with an
+ opaque handle that can subsequently be passed to
+ GetBackgroundWorkerPid(BackgroundWorkerHandle *, pid_t *) or
+ TerminateBackgroundWorker(BackgroundWorkerHandle *).
+ GetBackgroundWorkerPid can be used to poll the status of the
+ worker: a return value of BGWH_NOT_YET_STARTED indicates that
+ the worker has not yet been started by the postmaster;
+ BGWH_STOPPED indicates that it has been started but is
+ no longer running; and BGWH_STARTED indicates that it is
+ currently running. In this last case, the PID will also be returned via the
+ second argument.
+ TerminateBackgroundWorker causes the postmaster to send
+ SIGTERM to the worker if it is running, and to unregister it
+ as soon as it is not.
+
+ In some cases, a process which registers a background worker may wish to
+ wait for the worker to start up. This can be accomplished by initializing
+ bgw_notify_pid to MyProcPid and
+ then passing the BackgroundWorkerHandle * obtained at
+ registration time to
+ WaitForBackgroundWorkerStartup(BackgroundWorkerHandle
+ *handle, pid_t *) function.
+ This function will block until the postmaster has attempted to start the
+ background worker, or until the postmaster dies. If the background worker
+ is running, the return value will be BGWH_STARTED, and
+ the PID will be written to the provided address. Otherwise, the return
+ value will be BGWH_STOPPED or
+ BGWH_POSTMASTER_DIED.
+
+ A process can also wait for a background worker to shut down, by using the
+ WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle
+ *handle) function and passing the
+ BackgroundWorkerHandle * obtained at registration. This
+ function will block until the background worker exits, or postmaster dies.
+ When the background worker exits, the return value is
+ BGWH_STOPPED, if postmaster dies it will return
+ BGWH_POSTMASTER_DIED.
+
+ Background workers can send asynchronous notification messages, either by
+ using the NOTIFY command via SPI,
+ or directly via Async_Notify(). Such notifications
+ will be sent at transaction commit.
+ Background workers should not register to receive asynchronous
+ notifications with the LISTEN command, as there is no
+ infrastructure for a worker to consume such notifications.
+
+ The src/test/modules/worker_spi module
+ contains a working example,
+ which demonstrates some useful techniques.
+
+ The maximum number of registered background workers is limited by
+ max_worker_processes.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/biblio.html b/pgsql/doc/postgresql/html/biblio.html
new file mode 100644
index 0000000000000000000000000000000000000000..5f9fe1a5406d40c0bcf248edb6cb2e4a3ca673ec
--- /dev/null
+++ b/pgsql/doc/postgresql/html/biblio.html
@@ -0,0 +1,23 @@
+
+Bibliography
+ Selected references and readings for SQL
+ and PostgreSQL.
+
+ Some white papers and technical reports from the original
+ POSTGRES development team
+ are available at the University of California, Berkeley, Computer Science
+ Department web site.
+
SQL Reference Books
[bowman01] The Practical SQL Handbook. Using SQL Variants. Fourth Edition. JudithBowman, SandraEmerson, and MarcyDarnovsky. ISBN 0-201-70309-2. Addison-Wesley Professional. 2001.
[date97] A Guide to the SQL Standard. A user's guide to the standard database language SQL. Fourth Edition. C. J.Date and HughDarwen. ISBN 0-201-96426-0. Addison-Wesley. 1997.
[date04] An Introduction to Database Systems. Eighth Edition. C. J.Date. ISBN 0-321-19784-4. Addison-Wesley. 2003.
[elma04] Fundamentals of Database Systems. Fourth Edition. RamezElmasri and ShamkantNavathe. ISBN 0-321-12226-7. Addison-Wesley. 2003.
[melt93] Understanding the New SQL. A complete guide. JimMelton and Alan R.Simon. ISBN 1-55860-245-3. Morgan Kaufmann. 1993.
[ull88] Principles of Database and Knowledge-Base Systems. Classical Database Systems. Jeffrey D.Ullman. Volume 1. Computer Science Press. 1988.
[sqltr-19075-6] SQL Technical Report. Part 6: SQL support for JavaScript Object
+ Notation (JSON). First Edition. 2017.
PostgreSQL-specific Documentation
[sim98] Enhancement of the ANSI SQL Implementation of PostgreSQL. StefanSimkovics. Department of Information Systems, Vienna University of Technology. Vienna, Austria. November 29, 1998.
[yu95] The Postgres95. User Manual. A.Yu and J.Chen. University of California. Berkeley, California. Sept. 5, 1995.
[berenson95] “A Critique of ANSI SQL Isolation Levels”. H.Berenson, P.Bernstein, J.Gray, J.Melton, E.O'Neil, and P.O'Neil. ACM-SIGMOD Conference on Management of Data, June 1995.
[olson93] Partial indexing in POSTGRES: research project. NelsOlson. UCB Engin T7.49.1993 O676. University of California. Berkeley, California. 1993.
[ong90] “A Unified Framework for Version Modeling Using Production Rules in a Database System”. L.Ong and J.Goh. ERL Technical Memorandum M90/33. University of California. Berkeley, California. April, 1990.
[seshadri95] “Generalized
+ Partial Indexes”. P.Seshadri and A.Swami. Eleventh International Conference on Data Engineering, 6–10 March 1995. Cat. No.95CH35724. IEEE Computer Society Press. Los Alamitos, California. 1995. 420–7.
[ston86] “The
+ design of POSTGRES”. M.Stonebraker and L.Rowe. ACM-SIGMOD Conference on Management of Data, May 1986.
[ston87a] “The design of the POSTGRES rules system”. M.Stonebraker, E.Hanson, and C. H.Hong. IEEE Conference on Data Engineering, Feb. 1987.
[ston90a] “The
+ implementation of POSTGRES”. M.Stonebraker, L. A.Rowe, and M.Hirohama. Transactions on Knowledge and Data Engineering 2(1). IEEE. March 1990.
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bki-commands.html b/pgsql/doc/postgresql/html/bki-commands.html
new file mode 100644
index 0000000000000000000000000000000000000000..7c81764421408bf5dd2d0059d609fce75a15dada
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bki-commands.html
@@ -0,0 +1,111 @@
+
+75.4. BKI Commands
+ create
+ tablename
+ tableoid
+ [bootstrap]
+ [shared_relation]
+ [rowtype_oidoid]
+ (name1 =
+ type1
+ [FORCE NOT NULL | FORCE NULL] [,
+ name2 =
+ type2
+ [FORCE NOT NULL | FORCE NULL],
+ ...])
+
+ Create a table named tablename, and having the OID
+ tableoid,
+ with the columns given in parentheses.
+
+ The following column types are supported directly by
+ bootstrap.c: bool,
+ bytea, char (1 byte),
+ name, int2,
+ int4, regproc, regclass,
+ regtype, text,
+ oid, tid, xid,
+ cid, int2vector, oidvector,
+ _int4 (array), _text (array),
+ _oid (array), _char (array),
+ _aclitem (array). Although it is possible to create
+ tables containing columns of other types, this cannot be done until
+ after pg_type has been created and filled with
+ appropriate entries. (That effectively means that only these
+ column types can be used in bootstrap catalogs, but non-bootstrap
+ catalogs can contain any built-in type.)
+
+ When bootstrap is specified,
+ the table will only be created on disk; nothing is entered into
+ pg_class,
+ pg_attribute, etc., for it. Thus the
+ table will not be accessible by ordinary SQL operations until
+ such entries are made the hard way (with insert
+ commands). This option is used for creating
+ pg_class etc. themselves.
+
+ The table is created as shared if shared_relation is
+ specified.
+ The table's row type OID (pg_type OID) can optionally
+ be specified via the rowtype_oid clause; if not specified,
+ an OID is automatically generated for it. (The rowtype_oid
+ clause is useless if bootstrap is specified, but it can be
+ provided anyway for documentation.)
+
+ opentablename
+
+ Open the table named
+ tablename
+ for insertion of data. Any currently open table is closed.
+
+ closetablename
+
+ Close the open table. The name of the table must be given as a
+ cross-check.
+
+ insert( [oid_value] value1value2 ... )
+
+ Insert a new row into the open table using value1, value2, etc., for its column
+ values.
+
+ NULL values can be specified using the special key word
+ _null_. Values that do not look like
+ identifiers or digit strings must be single-quoted.
+ (To include a single quote in a value, write it twice.
+ Escape-string-style backslash escapes are allowed in the string, too.)
+
+ Create an index named indexname, having OID
+ indexoid,
+ on the table named
+ tablename, using the
+ amname access
+ method. The fields to index are called name1, name2 etc., and the operator
+ classes to use are opclass1, opclass2 etc., respectively.
+ The index file is created and appropriate catalog entries are
+ made for it, but the index contents are not initialized by this command.
+
+ Create a TOAST table for the table named
+ tablename.
+ The TOAST table is assigned OID
+ toasttableoid
+ and its index is assigned OID
+ toastindexoid.
+ As with declare index, filling of the index
+ is postponed.
+
build indices
+ Fill in the indices that have previously been declared.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bki-example.html b/pgsql/doc/postgresql/html/bki-example.html
new file mode 100644
index 0000000000000000000000000000000000000000..8854266ae6473dd0670850cfd108be5728ce5f9f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bki-example.html
@@ -0,0 +1,15 @@
+
+75.6. BKI Example
+ The following sequence of commands will create the table
+ test_table with OID 420, having three columns
+ oid, cola and colb
+ of type oid, int4 and text,
+ respectively, and insert two rows into the table:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bki-format.html b/pgsql/doc/postgresql/html/bki-format.html
new file mode 100644
index 0000000000000000000000000000000000000000..4f3bf22a166645aa64272c63e2a0600b13c4f45d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bki-format.html
@@ -0,0 +1,19 @@
+
+75.3. BKI File Format
+ This section describes how the PostgreSQL
+ backend interprets BKI files. This description
+ will be easier to understand if the postgres.bki
+ file is at hand as an example.
+
+ BKI input consists of a sequence of commands. Commands are made up
+ of a number of tokens, depending on the syntax of the command.
+ Tokens are usually separated by whitespace, but need not be if
+ there is no ambiguity. There is no special command separator; the
+ next token that syntactically cannot belong to the preceding
+ command starts a new one. (Usually you would put a new command on
+ a new line, for clarity.) Tokens can be certain key words, special
+ characters (parentheses, commas, etc.), identifiers, numbers, or
+ single-quoted strings. Everything is case sensitive.
+
+ Lines starting with # are ignored.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bki-structure.html b/pgsql/doc/postgresql/html/bki-structure.html
new file mode 100644
index 0000000000000000000000000000000000000000..5b358f7813f1f906ac7f7af3adc83ae1daeb6d4f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bki-structure.html
@@ -0,0 +1,42 @@
+
+75.5. Structure of the Bootstrap BKI File
+ The open command cannot be used until the tables it uses
+ exist and have entries for the table that is to be opened.
+ (These minimum tables are pg_class,
+ pg_attribute, pg_proc, and
+ pg_type.) To allow those tables themselves to be filled,
+ create with the bootstrap option implicitly opens
+ the created table for data insertion.
+
+ Also, the declare index and declare toast
+ commands cannot be used until the system catalogs they need have been
+ created and filled in.
+
+ Thus, the structure of the postgres.bki file has to
+ be:
+
+ create bootstrap one of the critical tables
+
+ insert data describing at least the critical tables
+
+ close
+
+ Repeat for the other critical tables.
+
+ create (without bootstrap) a noncritical table
+
+ open
+
+ insert desired data
+
+ close
+
+ Repeat for the other noncritical tables.
+
+ Define indexes and toast tables.
+
+ build indices
+
+
+ There are doubtless other, undocumented ordering dependencies.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bki.html b/pgsql/doc/postgresql/html/bki.html
new file mode 100644
index 0000000000000000000000000000000000000000..be017fcd0ca3f36c6678d794d45ae3b73640e5d9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bki.html
@@ -0,0 +1,56 @@
+
+Chapter 75. System Catalog Declarations and Initial Contents
Chapter 75. System Catalog Declarations and Initial Contents
+ PostgreSQL uses many different system catalogs
+ to keep track of the existence and properties of database objects, such as
+ tables and functions. Physically there is no difference between a system
+ catalog and a plain user table, but the backend C code knows the structure
+ and properties of each catalog, and can manipulate it directly at a low
+ level. Thus, for example, it is inadvisable to attempt to alter the
+ structure of a catalog on-the-fly; that would break assumptions built into
+ the C code about how rows of the catalog are laid out. But the structure
+ of the catalogs can change between major versions.
+
+ The structures of the catalogs are declared in specially formatted C
+ header files in the src/include/catalog/ directory of
+ the source tree. For each catalog there is a header file
+ named after the catalog (e.g., pg_class.h
+ for pg_class), which defines the set of columns
+ the catalog has, as well as some other basic properties such as its OID.
+
+ Many of the catalogs have initial data that must be loaded into them
+ during the “bootstrap” phase
+ of initdb, to bring the system up to a point
+ where it is capable of executing SQL commands. (For
+ example, pg_class.h must contain an entry for itself,
+ as well as one for each other system catalog and index.) This
+ initial data is kept in editable form in data files that are also stored
+ in the src/include/catalog/ directory. For example,
+ pg_proc.dat describes all the initial rows that must
+ be inserted into the pg_proc catalog.
+
+ To create the catalog files and load this initial data into them, a
+ backend running in bootstrap mode reads a BKI
+ (Backend Interface) file containing commands and initial data.
+ The postgres.bki file used in this mode is prepared
+ from the aforementioned header and data files, while building
+ a PostgreSQL distribution, by a Perl script
+ named genbki.pl.
+ Although it's specific to a particular PostgreSQL
+ release, postgres.bki is platform-independent and is
+ installed in the share subdirectory of the
+ installation tree.
+
+ genbki.pl also produces a derived header file for
+ each catalog, for example pg_class_d.h for
+ the pg_class catalog. This file contains
+ automatically-generated macro definitions, and may contain other macros,
+ enum declarations, and so on that can be useful for client C code that
+ reads a particular catalog.
+
+ Most PostgreSQL developers don't need to be directly concerned with
+ the BKI file, but almost any nontrivial feature
+ addition in the backend will require modifying the catalog header files
+ and/or initial data files. The rest of this chapter gives some
+ information about that, and for completeness describes
+ the BKI file format.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bloom.html b/pgsql/doc/postgresql/html/bloom.html
new file mode 100644
index 0000000000000000000000000000000000000000..cb01a737f3e6d4fb623a02c38a26d938a53c685e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bloom.html
@@ -0,0 +1,190 @@
+
+F.7. bloom — bloom filter index access method
+ bloom provides an index access method based on
+ Bloom filters.
+
+ A Bloom filter is a space-efficient data structure that is used to test
+ whether an element is a member of a set. In the case of an index access
+ method, it allows fast exclusion of non-matching tuples via signatures
+ whose size is determined at index creation.
+
+ A signature is a lossy representation of the indexed attribute(s), and as
+ such is prone to reporting false positives; that is, it may be reported
+ that an element is in the set, when it is not. So index search results
+ must always be rechecked using the actual attribute values from the heap
+ entry. Larger signatures reduce the odds of a false positive and thus
+ reduce the number of useless heap visits, but of course also make the index
+ larger and hence slower to scan.
+
+ This type of index is most useful when a table has many attributes and
+ queries test arbitrary combinations of them. A traditional btree index is
+ faster than a bloom index, but it can require many btree indexes to support
+ all possible queries where one needs only a single bloom index. Note
+ however that bloom indexes only support equality queries, whereas btree
+ indexes can also perform inequality and range searches.
+
+ A bloom index accepts the following parameters in its
+ WITH clause:
+
length
+ Length of each signature (index entry) in bits. It is rounded up to the
+ nearest multiple of 16. The default is
+ 80 bits and the maximum is 4096.
+
col1 — col32
+ Number of bits generated for each index column. Each parameter's name
+ refers to the number of the index column that it controls. The default
+ is 2 bits and the maximum is 4095.
+ Parameters for index columns not actually used are ignored.
+
+CREATE INDEX bloomidx ON tbloom USING bloom (i1,i2,i3)
+ WITH (length=80, col1=2, col2=2, col3=4);
+
+ The index is created with a signature length of 80 bits, with attributes
+ i1 and i2 mapped to 2 bits, and attribute i3 mapped to 4 bits. We could
+ have omitted the length, col1,
+ and col2 specifications since those have the default values.
+
+ Here is a more complete example of bloom index definition and usage, as
+ well as a comparison with equivalent btree indexes. The bloom index is
+ considerably smaller than the btree index, and can perform better.
+
+=# CREATE TABLE tbloom AS
+ SELECT
+ (random() * 1000000)::int as i1,
+ (random() * 1000000)::int as i2,
+ (random() * 1000000)::int as i3,
+ (random() * 1000000)::int as i4,
+ (random() * 1000000)::int as i5,
+ (random() * 1000000)::int as i6
+ FROM
+ generate_series(1,10000000);
+SELECT 10000000
+
+ A sequential scan over this large table takes a long time:
+
+=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451;
+ QUERY PLAN
+------------------------------------------------------------------------------------------------------
+ Seq Scan on tbloom (cost=0.00..2137.14 rows=3 width=24) (actual time=16.971..16.971 rows=0 loops=1)
+ Filter: ((i2 = 898732) AND (i5 = 123451))
+ Rows Removed by Filter: 100000
+ Planning Time: 0.346 ms
+ Execution Time: 16.988 ms
+(5 rows)
+
+
+ Even with the btree index defined the result will still be a
+ sequential scan:
+
+=# CREATE INDEX btreeidx ON tbloom (i1, i2, i3, i4, i5, i6);
+CREATE INDEX
+=# SELECT pg_size_pretty(pg_relation_size('btreeidx'));
+ pg_size_pretty
+----------------
+ 3976 kB
+(1 row)
+=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451;
+ QUERY PLAN
+------------------------------------------------------------------------------------------------------
+ Seq Scan on tbloom (cost=0.00..2137.00 rows=2 width=24) (actual time=12.805..12.805 rows=0 loops=1)
+ Filter: ((i2 = 898732) AND (i5 = 123451))
+ Rows Removed by Filter: 100000
+ Planning Time: 0.138 ms
+ Execution Time: 12.817 ms
+(5 rows)
+
+
+ Having the bloom index defined on the table is better than btree in
+ handling this type of search:
+
+=# CREATE INDEX bloomidx ON tbloom USING bloom (i1, i2, i3, i4, i5, i6);
+CREATE INDEX
+=# SELECT pg_size_pretty(pg_relation_size('bloomidx'));
+ pg_size_pretty
+----------------
+ 1584 kB
+(1 row)
+=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451;
+ QUERY PLAN
+---------------------------------------------------------------------------------------------------------------------
+ Bitmap Heap Scan on tbloom (cost=1792.00..1799.69 rows=2 width=24) (actual time=0.388..0.388 rows=0 loops=1)
+ Recheck Cond: ((i2 = 898732) AND (i5 = 123451))
+ Rows Removed by Index Recheck: 29
+ Heap Blocks: exact=28
+ -> Bitmap Index Scan on bloomidx (cost=0.00..1792.00 rows=2 width=0) (actual time=0.356..0.356 rows=29 loops=1)
+ Index Cond: ((i2 = 898732) AND (i5 = 123451))
+ Planning Time: 0.099 ms
+ Execution Time: 0.408 ms
+(8 rows)
+
+
+ Now, the main problem with the btree search is that btree is inefficient
+ when the search conditions do not constrain the leading index column(s).
+ A better strategy for btree is to create a separate index on each column.
+ Then the planner will choose something like this:
+
+=# CREATE INDEX btreeidx1 ON tbloom (i1);
+CREATE INDEX
+=# CREATE INDEX btreeidx2 ON tbloom (i2);
+CREATE INDEX
+=# CREATE INDEX btreeidx3 ON tbloom (i3);
+CREATE INDEX
+=# CREATE INDEX btreeidx4 ON tbloom (i4);
+CREATE INDEX
+=# CREATE INDEX btreeidx5 ON tbloom (i5);
+CREATE INDEX
+=# CREATE INDEX btreeidx6 ON tbloom (i6);
+CREATE INDEX
+=# EXPLAIN ANALYZE SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451;
+ QUERY PLAN
+---------------------------------------------------------------------------------------------------------------------------
+ Bitmap Heap Scan on tbloom (cost=24.34..32.03 rows=2 width=24) (actual time=0.028..0.029 rows=0 loops=1)
+ Recheck Cond: ((i5 = 123451) AND (i2 = 898732))
+ -> BitmapAnd (cost=24.34..24.34 rows=2 width=0) (actual time=0.027..0.027 rows=0 loops=1)
+ -> Bitmap Index Scan on btreeidx5 (cost=0.00..12.04 rows=500 width=0) (actual time=0.026..0.026 rows=0 loops=1)
+ Index Cond: (i5 = 123451)
+ -> Bitmap Index Scan on btreeidx2 (cost=0.00..12.04 rows=500 width=0) (never executed)
+ Index Cond: (i2 = 898732)
+ Planning Time: 0.491 ms
+ Execution Time: 0.055 ms
+(9 rows)
+
+ Although this query runs much faster than with either of the single
+ indexes, we pay a penalty in index size. Each of the single-column
+ btree indexes occupies 2 MB, so the total space needed is 12 MB,
+ eight times the space used by the bloom index.
+
+ An operator class for bloom indexes requires only a hash function for the
+ indexed data type and an equality operator for searching. This example
+ shows the operator class definition for the text data type:
+
+CREATE OPERATOR CLASS text_ops
+DEFAULT FOR TYPE text USING bloom AS
+ OPERATOR 1 =(text, text),
+ FUNCTION 1 hashtext(text);
+
+ Only operator classes for int4 and text are
+ included with the module.
+
+ Only the = operator is supported for search. But
+ it is possible to add support for arrays with union and intersection
+ operations in the future.
+
+ bloom access method doesn't support
+ UNIQUE indexes.
+
+ bloom access method doesn't support searching for
+ NULL values.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bookindex.html b/pgsql/doc/postgresql/html/bookindex.html
new file mode 100644
index 0000000000000000000000000000000000000000..e941755b8f3c810a1358e50c7e715c8ac8da9537
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bookindex.html
@@ -0,0 +1,72 @@
+
+Index
Symbols
+ |
+ A
+ |
+ B
+ |
+ C
+ |
+ D
+ |
+ E
+ |
+ F
+ |
+ G
+ |
+ H
+ |
+ I
+ |
+ J
+ |
+ K
+ |
+ L
+ |
+ M
+ |
+ N
+ |
+ O
+ |
+ P
+ |
+ Q
+ |
+ R
+ |
+ S
+ |
+ T
+ |
+ U
+ |
+ V
+ |
+ W
+ |
+ X
+ |
+ Y
+ |
+ Z
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/brin-builtin-opclasses.html b/pgsql/doc/postgresql/html/brin-builtin-opclasses.html
new file mode 100644
index 0000000000000000000000000000000000000000..9d91b3167ad41957e886806a00e0a3565e7a7de0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/brin-builtin-opclasses.html
@@ -0,0 +1,46 @@
+
+71.2. Built-in Operator Classes
+ The core PostgreSQL distribution
+ includes the BRIN operator classes shown in
+ Table 71.1.
+
+ The minmax
+ operator classes store the minimum and the maximum values appearing
+ in the indexed column within the range. The inclusion
+ operator classes store a value which includes the values in the indexed
+ column within the range. The bloom operator
+ classes build a Bloom filter for all values in the range. The
+ minmax-multi operator classes store multiple
+ minimum and maximum values, representing values appearing in the indexed
+ column within the range.
+
+ Some of the built-in operator classes allow specifying parameters affecting
+ behavior of the operator class. Each operator class has its own set of
+ allowed parameters. Only the bloom and minmax-multi
+ operator classes allow specifying parameters:
+
+ bloom operator classes accept these parameters:
+
n_distinct_per_range
+ Defines the estimated number of distinct non-null values in the block
+ range, used by BRIN bloom indexes for sizing of the
+ Bloom filter. It behaves similarly to n_distinct option
+ for ALTER TABLE. When set to a positive value,
+ each block range is assumed to contain this number of distinct non-null
+ values. When set to a negative value, which must be greater than or
+ equal to -1, the number of distinct non-null values is assumed to grow linearly with
+ the maximum possible number of tuples in the block range (about 290
+ rows per block). The default value is -0.1, and
+ the minimum number of distinct non-null values is 16.
+
false_positive_rate
+ Defines the desired false positive rate used by BRIN
+ bloom indexes for sizing of the Bloom filter. The values must be
+ between 0.0001 and 0.25. The default value is 0.01, which is 1% false
+ positive rate.
+
+ minmax-multi operator classes accept these parameters:
+
values_per_range
+ Defines the maximum number of values stored by BRIN
+ minmax indexes to summarize a block range. Each value may represent
+ either a point, or a boundary of an interval. Values must be between
+ 8 and 256, and the default value is 32.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/brin-extensibility.html b/pgsql/doc/postgresql/html/brin-extensibility.html
new file mode 100644
index 0000000000000000000000000000000000000000..03dee66fbbfd7d7617964d5bcc0d36dbd664c1b6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/brin-extensibility.html
@@ -0,0 +1,168 @@
+
+71.3. Extensibility
+ The BRIN interface has a high level of abstraction,
+ requiring the access method implementer only to implement the semantics
+ of the data type being accessed. The BRIN layer
+ itself takes care of concurrency, logging and searching the index structure.
+
+ All it takes to get a BRIN access method working is to
+ implement a few user-defined methods, which define the behavior of
+ summary values stored in the index and the way they interact with
+ scan keys.
+ In short, BRIN combines
+ extensibility with generality, code reuse, and a clean interface.
+
+ There are four methods that an operator class for BRIN
+ must provide:
+
+
BrinOpcInfo *opcInfo(Oid type_oid)
+ Returns internal information about the indexed columns' summary data.
+ The return value must point to a palloc'd BrinOpcInfo,
+ which has this definition:
+
+typedef struct BrinOpcInfo
+{
+ /* Number of columns stored in an index column of this opclass */
+ uint16 oi_nstored;
+
+ /* Opaque pointer for the opclass' private use */
+ void *oi_opaque;
+
+ /* Type cache entries of the stored columns */
+ TypeCacheEntry *oi_typcache[FLEXIBLE_ARRAY_MEMBER];
+} BrinOpcInfo;
+
+ BrinOpcInfo.oi_opaque can be used by the
+ operator class routines to pass information between support functions
+ during an index scan.
+
bool consistent(BrinDesc *bdesc, BrinValues *column,
+ ScanKey *keys, int nkeys)
+ Returns whether all the ScanKey entries are consistent with the given
+ indexed values for a range.
+ The attribute number to use is passed as part of the scan key.
+ Multiple scan keys for the same attribute may be passed at once; the
+ number of entries is determined by the nkeys parameter.
+
+ Returns whether the ScanKey is consistent with the given indexed
+ values for a range.
+ The attribute number to use is passed as part of the scan key.
+ This is an older backward-compatible variant of the consistent function.
+
bool addValue(BrinDesc *bdesc, BrinValues *column,
+ Datum newval, bool isnull)
+ Given an index tuple and an indexed value, modifies the indicated
+ attribute of the tuple so that it additionally represents the new value.
+ If any modification was done to the tuple, true is
+ returned.
+
+ Consolidates two index tuples. Given two index tuples, modifies the
+ indicated attribute of the first of them so that it represents both tuples.
+ The second tuple is not modified.
+
+
+ An operator class for BRIN can optionally specify the
+ following method:
+
+
void options(local_relopts *relopts)
+ Defines a set of user-visible parameters that control operator class
+ behavior.
+
+ The options function is passed a pointer to a
+ local_relopts struct, which needs to be
+ filled with a set of operator class specific options. The options
+ can be accessed from other support functions using the
+ PG_HAS_OPCLASS_OPTIONS() and
+ PG_GET_OPCLASS_OPTIONS() macros.
+
+ Since both key extraction of indexed values and representation of the
+ key in BRIN are flexible, they may depend on
+ user-specified parameters.
+
+
+ The core distribution includes support for four types of operator classes:
+ minmax, minmax-multi, inclusion and bloom. Operator class definitions
+ using them are shipped for in-core data types as appropriate. Additional
+ operator classes can be defined by the user for other data types using
+ equivalent definitions, without having to write any source code;
+ appropriate catalog entries being declared is enough. Note that
+ assumptions about the semantics of operator strategies are embedded in the
+ support functions' source code.
+
+ Operator classes that implement completely different semantics are also
+ possible, provided implementations of the four main support functions
+ described above are written. Note that backwards compatibility across major
+ releases is not guaranteed: for example, additional support functions might
+ be required in later releases.
+
+ To write an operator class for a data type that implements a totally
+ ordered set, it is possible to use the minmax support functions
+ alongside the corresponding operators, as shown in
+ Table 71.2.
+ All operator class members (functions and operators) are mandatory.
+
Table 71.2. Function and Support Numbers for Minmax Operator Classes
Operator class member
Object
Support Function 1
internal function brin_minmax_opcinfo()
Support Function 2
internal function brin_minmax_add_value()
Support Function 3
internal function brin_minmax_consistent()
Support Function 4
internal function brin_minmax_union()
Operator Strategy 1
operator less-than
Operator Strategy 2
operator less-than-or-equal-to
Operator Strategy 3
operator equal-to
Operator Strategy 4
operator greater-than-or-equal-to
Operator Strategy 5
operator greater-than
+ To write an operator class for a complex data type which has values
+ included within another type, it's possible to use the inclusion support
+ functions alongside the corresponding operators, as shown
+ in Table 71.3. It requires
+ only a single additional function, which can be written in any language.
+ More functions can be defined for additional functionality. All operators
+ are optional. Some operators require other operators, as shown as
+ dependencies on the table.
+
Table 71.3. Function and Support Numbers for Inclusion Operator Classes
Operator class member
Object
Dependency
Support Function 1
internal function brin_inclusion_opcinfo()
Support Function 2
internal function brin_inclusion_add_value()
Support Function 3
internal function brin_inclusion_consistent()
Support Function 4
internal function brin_inclusion_union()
Support Function 11
function to merge two elements
Support Function 12
optional function to check whether two elements are mergeable
Support Function 13
optional function to check if an element is contained within another
Support Function 14
optional function to check whether an element is empty
Operator Strategy 1
operator left-of
Operator Strategy 4
Operator Strategy 2
operator does-not-extend-to-the-right-of
Operator Strategy 5
Operator Strategy 3
operator overlaps
Operator Strategy 4
operator does-not-extend-to-the-left-of
Operator Strategy 1
Operator Strategy 5
operator right-of
Operator Strategy 2
Operator Strategy 6, 18
operator same-as-or-equal-to
Operator Strategy 7
Operator Strategy 7, 16, 24, 25
operator contains-or-equal-to
Operator Strategy 8, 26, 27
operator is-contained-by-or-equal-to
Operator Strategy 3
Operator Strategy 9
operator does-not-extend-above
Operator Strategy 11
Operator Strategy 10
operator is-below
Operator Strategy 12
Operator Strategy 11
operator is-above
Operator Strategy 9
Operator Strategy 12
operator does-not-extend-below
Operator Strategy 10
Operator Strategy 20
operator less-than
Operator Strategy 5
Operator Strategy 21
operator less-than-or-equal-to
Operator Strategy 5
Operator Strategy 22
operator greater-than
Operator Strategy 1
Operator Strategy 23
operator greater-than-or-equal-to
Operator Strategy 1
+ Support function numbers 1 through 10 are reserved for the BRIN internal
+ functions, so the SQL level functions start with number 11. Support
+ function number 11 is the main function required to build the index.
+ It should accept two arguments with the same data type as the operator class,
+ and return the union of them. The inclusion operator class can store union
+ values with different data types if it is defined with the
+ STORAGE parameter. The return value of the union
+ function should match the STORAGE data type.
+
+ Support function numbers 12 and 14 are provided to support
+ irregularities of built-in data types. Function number 12
+ is used to support network addresses from different families which
+ are not mergeable. Function number 14 is used to support
+ empty ranges. Function number 13 is an optional but
+ recommended one, which allows the new value to be checked before
+ it is passed to the union function. As the BRIN framework can shortcut
+ some operations when the union is not changed, using this
+ function can improve index performance.
+
+ To write an operator class for a data type that implements only an equality
+ operator and supports hashing, it is possible to use the bloom support procedures
+ alongside the corresponding operators, as shown in
+ Table 71.4.
+ All operator class members (procedures and operators) are mandatory.
+
Table 71.4. Procedure and Support Numbers for Bloom Operator Classes
Operator class member
Object
Support Procedure 1
internal function brin_bloom_opcinfo()
Support Procedure 2
internal function brin_bloom_add_value()
Support Procedure 3
internal function brin_bloom_consistent()
Support Procedure 4
internal function brin_bloom_union()
Support Procedure 5
internal function brin_bloom_options()
Support Procedure 11
function to compute hash of an element
Operator Strategy 1
operator equal-to
+ Support procedure numbers 1-10 are reserved for the BRIN internal
+ functions, so the SQL level functions start with number 11. Support
+ function number 11 is the main function required to build the index.
+ It should accept one argument with the same data type as the operator class,
+ and return a hash of the value.
+
+ The minmax-multi operator class is also intended for data types implementing
+ a totally ordered set, and may be seen as a simple extension of the minmax
+ operator class. While minmax operator class summarizes values from each block
+ range into a single contiguous interval, minmax-multi allows summarization
+ into multiple smaller intervals to improve handling of outlier values.
+ It is possible to use the minmax-multi support procedures alongside the
+ corresponding operators, as shown in
+ Table 71.5.
+ All operator class members (procedures and operators) are mandatory.
+
Table 71.5. Procedure and Support Numbers for minmax-multi Operator Classes
Operator class member
Object
Support Procedure 1
internal function brin_minmax_multi_opcinfo()
Support Procedure 2
internal function brin_minmax_multi_add_value()
Support Procedure 3
internal function brin_minmax_multi_consistent()
Support Procedure 4
internal function brin_minmax_multi_union()
Support Procedure 5
internal function brin_minmax_multi_options()
Support Procedure 11
function to compute distance between two values (length of a range)
Operator Strategy 1
operator less-than
Operator Strategy 2
operator less-than-or-equal-to
Operator Strategy 3
operator equal-to
Operator Strategy 4
operator greater-than-or-equal-to
Operator Strategy 5
operator greater-than
+ Both minmax and inclusion operator classes support cross-data-type
+ operators, though with these the dependencies become more complicated.
+ The minmax operator class requires a full set of operators to be
+ defined with both arguments having the same data type. It allows
+ additional data types to be supported by defining extra sets
+ of operators. Inclusion operator class operator strategies are dependent
+ on another operator strategy as shown in
+ Table 71.3, or the same
+ operator strategy as themselves. They require the dependency
+ operator to be defined with the STORAGE data type as the
+ left-hand-side argument and the other supported data type to be the
+ right-hand-side argument of the supported operator. See
+ float4_minmax_ops as an example of minmax, and
+ box_inclusion_ops as an example of inclusion.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/brin-intro.html b/pgsql/doc/postgresql/html/brin-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..e2403c8f7f755ebea21bf226631899d730269828
--- /dev/null
+++ b/pgsql/doc/postgresql/html/brin-intro.html
@@ -0,0 +1,99 @@
+
+71.1. Introduction
+ BRIN stands for Block Range Index.
+ BRIN is designed for handling very large tables
+ in which certain columns have some natural correlation with their
+ physical location within the table.
+
+ BRIN works in terms of block ranges
+ (or “page ranges”).
+ A block range is a group of pages that are physically
+ adjacent in the table; for each block range, some summary info is stored
+ by the index.
+ For example, a table storing a store's sale orders might have
+ a date column on which each order was placed, and most of the time
+ the entries for earlier orders will appear earlier in the table as well;
+ a table storing a ZIP code column might have all codes for a city
+ grouped together naturally.
+
+ BRIN indexes can satisfy queries via regular bitmap
+ index scans, and will return all tuples in all pages within each range if
+ the summary info stored by the index is consistent with the
+ query conditions.
+ The query executor is in charge of rechecking these tuples and discarding
+ those that do not match the query conditions — in other words, these
+ indexes are lossy.
+ Because a BRIN index is very small, scanning the index
+ adds little overhead compared to a sequential scan, but may avoid scanning
+ large parts of the table that are known not to contain matching tuples.
+
+ The specific data that a BRIN index will store,
+ as well as the specific queries that the index will be able to satisfy,
+ depend on the operator class selected for each column of the index.
+ Data types having a linear sort order can have operator classes that
+ store the minimum and maximum value within each block range, for instance;
+ geometrical types might store the bounding box for all the objects
+ in the block range.
+
+ The size of the block range is determined at index creation time by
+ the pages_per_range storage parameter. The number of index
+ entries will be equal to the size of the relation in pages divided by
+ the selected value for pages_per_range. Therefore, the smaller
+ the number, the larger the index becomes (because of the need to
+ store more index entries), but at the same time the summary data stored can
+ be more precise and more data blocks can be skipped during an index scan.
+
+ At the time of creation, all existing heap pages are scanned and a
+ summary index tuple is created for each range, including the
+ possibly-incomplete range at the end.
+ As new pages are filled with data, page ranges that are already
+ summarized will cause the summary information to be updated with data
+ from the new tuples.
+ When a new page is created that does not fall within the last
+ summarized range, the range that the new page belongs to
+ does not automatically acquire a summary tuple;
+ those tuples remain unsummarized until a summarization run is
+ invoked later, creating the initial summary for that range.
+
+ There are several ways to trigger the initial summarization of a page range.
+ If the table is vacuumed, either manually or by
+ autovacuum, all existing unsummarized
+ page ranges are summarized.
+ Also, if the index's
+ autosummarize parameter is enabled,
+ which it isn't by default,
+ whenever autovacuum runs in that database, summarization will occur for all
+ unsummarized page ranges that have been filled,
+ regardless of whether the table itself is processed by autovacuum; see below.
+
+ Lastly, the following functions can be used:
+
+ brin_summarize_new_values(regclass)
+ which summarizes all unsummarized ranges;
+
+ brin_summarize_range(regclass, bigint)
+ which summarizes only the range containing the given page,
+ if it is unsummarized.
+
+
+ When autosummarization is enabled, a request is sent to
+ autovacuum to execute a targeted summarization
+ for a block range when an insertion is detected for the first item
+ of the first page of the next block range,
+ to be fulfilled the next time an autovacuum
+ worker finishes running in the
+ same database. If the request queue is full, the request is not recorded
+ and a message is sent to the server log:
+
+LOG: request for BRIN range summarization for index "brin_wi_idx" page 128 was not recorded
+
+ When this happens, the range will remain unsummarized until the next
+ regular vacuum run on the table, or one of the functions mentioned above
+ are invoked.
+
+ Conversely, a range can be de-summarized using the
+ brin_desummarize_range(regclass, bigint) function,
+ which is useful when the index tuple is no longer a very good
+ representation because the existing values have changed.
+ See Section 9.27.8 for details.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/brin.html b/pgsql/doc/postgresql/html/brin.html
new file mode 100644
index 0000000000000000000000000000000000000000..8f75dcb5a2e9db091d0d9427021749e30325f80d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/brin.html
@@ -0,0 +1,2 @@
+
+Chapter 71. BRIN Indexes
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree-behavior.html b/pgsql/doc/postgresql/html/btree-behavior.html
new file mode 100644
index 0000000000000000000000000000000000000000..8c9ae84c6f5dd386a6419417cc6e16637cdb3641
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree-behavior.html
@@ -0,0 +1,118 @@
+
+67.2. Behavior of B-Tree Operator Classes
+ As shown in Table 38.3, a btree operator
+ class must provide five comparison operators,
+ <,
+ <=,
+ =,
+ >= and
+ >.
+ One might expect that <> should also be part of
+ the operator class, but it is not, because it would almost never be
+ useful to use a <> WHERE clause in an index
+ search. (For some purposes, the planner treats <>
+ as associated with a btree operator class; but it finds that operator via
+ the = operator's negator link, rather than
+ from pg_amop.)
+
+ When several data types share near-identical sorting semantics, their
+ operator classes can be grouped into an operator family. Doing so is
+ advantageous because it allows the planner to make deductions about
+ cross-type comparisons. Each operator class within the family should
+ contain the single-type operators (and associated support functions)
+ for its input data type, while cross-type comparison operators and
+ support functions are “loose” in the family. It is
+ recommendable that a complete set of cross-type operators be included
+ in the family, thus ensuring that the planner can represent any
+ comparison conditions that it deduces from transitivity.
+
+ There are some basic assumptions that a btree operator family must
+ satisfy:
+
+ An = operator must be an equivalence relation; that
+ is, for all non-null values A,
+ B, C of the
+ data type:
+
+
+ A=
+ A is true
+ (reflexive law)
+
+ if A=
+ B,
+ then B=
+ A
+ (symmetric law)
+
+ if A=
+ B and B
+ =C,
+ then A=
+ C
+ (transitive law)
+
+
+ A < operator must be a strong ordering relation;
+ that is, for all non-null values A,
+ B, C:
+
+
+ A<
+ A is false
+ (irreflexive law)
+
+ if A<
+ B
+ and B<
+ C,
+ then A<
+ C
+ (transitive law)
+
+
+ Furthermore, the ordering is total; that is, for all non-null
+ values A, B:
+
+
+ exactly one of A<
+ B, A
+ =B, and
+ B<
+ A is true
+ (trichotomy law)
+
+
+ (The trichotomy law justifies the definition of the comparison support
+ function, of course.)
+
+ The other three operators are defined in terms of =
+ and < in the obvious way, and must act consistently
+ with them.
+
+ For an operator family supporting multiple data types, the above laws must
+ hold when A, B,
+ C are taken from any data types in the family.
+ The transitive laws are the trickiest to ensure, as in cross-type
+ situations they represent statements that the behaviors of two or three
+ different operators are consistent.
+ As an example, it would not work to put float8
+ and numeric into the same operator family, at least not with
+ the current semantics that numeric values are converted
+ to float8 for comparison to a float8. Because
+ of the limited accuracy of float8, this means there are
+ distinct numeric values that will compare equal to the
+ same float8 value, and thus the transitive law would fail.
+
+ Another requirement for a multiple-data-type family is that any implicit
+ or binary-coercion casts that are defined between data types included in
+ the operator family must not change the associated sort ordering.
+
+ It should be fairly clear why a btree index requires these laws to hold
+ within a single data type: without them there is no ordering to arrange
+ the keys with. Also, index searches using a comparison key of a
+ different data type require comparisons to behave sanely across two
+ data types. The extensions to three or more data types within a family
+ are not strictly required by the btree index mechanism itself, but the
+ planner relies on them for optimization purposes.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree-gin.html b/pgsql/doc/postgresql/html/btree-gin.html
new file mode 100644
index 0000000000000000000000000000000000000000..6c47e57faefca3d175f0e8a155d277f08a9d7a8d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree-gin.html
@@ -0,0 +1,38 @@
+
+F.8. btree_gin — GIN operator classes with B-tree behavior
F.8. btree_gin — GIN operator classes with B-tree behavior
+ btree_gin provides GIN operator classes that
+ implement B-tree equivalent behavior for the data types
+ int2, int4, int8, float4,
+ float8, timestamp with time zone,
+ timestamp without time zone, time with time zone,
+ time without time zone, date, interval,
+ oid, money, "char",
+ varchar, text, bytea, bit,
+ varbit, macaddr, macaddr8, inet,
+ cidr, uuid, name, bool,
+ bpchar, and all enum types.
+
+ In general, these operator classes will not outperform the equivalent
+ standard B-tree index methods, and they lack one major feature of the
+ standard B-tree code: the ability to enforce uniqueness. However,
+ they are useful for GIN testing and as a base for developing other
+ GIN operator classes. Also, for queries that test both a GIN-indexable
+ column and a B-tree-indexable column, it might be more efficient to create
+ a multicolumn GIN index that uses one of these operator classes than to create
+ two separate indexes that would have to be combined via bitmap ANDing.
+
+ This module is considered “trusted”, that is, it can be
+ installed by non-superusers who have CREATE privilege
+ on the current database.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree-gist.html b/pgsql/doc/postgresql/html/btree-gist.html
new file mode 100644
index 0000000000000000000000000000000000000000..5558c0082dca21c07439594d53909d7cd100b63d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree-gist.html
@@ -0,0 +1,80 @@
+
+F.9. btree_gist — GiST operator classes with B-tree behavior
F.9. btree_gist — GiST operator classes with B-tree behavior
+ btree_gist provides GiST index operator classes that
+ implement B-tree equivalent behavior for the data types
+ int2, int4, int8, float4,
+ float8, numeric, timestamp with time zone,
+ timestamp without time zone, time with time zone,
+ time without time zone, date, interval,
+ oid, money, char,
+ varchar, text, bytea, bit,
+ varbit, macaddr, macaddr8, inet,
+ cidr, uuid, bool and all enum types.
+
+ In general, these operator classes will not outperform the equivalent
+ standard B-tree index methods, and they lack one major feature of the
+ standard B-tree code: the ability to enforce uniqueness. However,
+ they provide some other features that are not available with a B-tree
+ index, as described below. Also, these operator classes are useful
+ when a multicolumn GiST index is needed, wherein some of the columns
+ are of data types that are only indexable with GiST but other columns
+ are just simple data types. Lastly, these operator classes are useful for
+ GiST testing and as a base for developing other GiST operator classes.
+
+ In addition to the typical B-tree search operators, btree_gist
+ also provides index support for <> (“not
+ equals”). This may be useful in combination with an
+ exclusion constraint,
+ as described below.
+
+ Also, for data types for which there is a natural distance metric,
+ btree_gist defines a distance operator <->,
+ and provides GiST index support for nearest-neighbor searches using
+ this operator. Distance operators are provided for
+ int2, int4, int8, float4,
+ float8, timestamp with time zone,
+ timestamp without time zone,
+ time without time zone, date, interval,
+ oid, and money.
+
+ This module is considered “trusted”, that is, it can be
+ installed by non-superusers who have CREATE privilege
+ on the current database.
+
+ Simple example using btree_gist instead of btree:
+
+CREATE TABLE test (a int4);
+-- create index
+CREATE INDEX testidx ON test USING GIST (a);
+-- query
+SELECT * FROM test WHERE a < 10;
+-- nearest-neighbor search: find the ten entries closest to "42"
+SELECT *, a <-> 42 AS dist FROM test ORDER BY a <-> 42 LIMIT 10;
+
+ Use an exclusion
+ constraint to enforce the rule that a cage at a zoo
+ can contain only one kind of animal:
+
+=> CREATE TABLE zoo (
+ cage INTEGER,
+ animal TEXT,
+ EXCLUDE USING GIST (cage WITH =, animal WITH <>)
+);
+
+=> INSERT INTO zoo VALUES(123, 'zebra');
+INSERT 0 1
+=> INSERT INTO zoo VALUES(123, 'zebra');
+INSERT 0 1
+=> INSERT INTO zoo VALUES(123, 'lion');
+ERROR: conflicting key value violates exclusion constraint "zoo_cage_animal_excl"
+DETAIL: Key (cage, animal)=(123, lion) conflicts with existing key (cage, animal)=(123, zebra).
+=> INSERT INTO zoo VALUES(124, 'lion');
+INSERT 0 1
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree-implementation.html b/pgsql/doc/postgresql/html/btree-implementation.html
new file mode 100644
index 0000000000000000000000000000000000000000..45931113461acdce309e90b438be2e74ebb8fe57
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree-implementation.html
@@ -0,0 +1,254 @@
+
+67.4. Implementation
+ This section covers B-Tree index implementation details that may be
+ of use to advanced users. See
+ src/backend/access/nbtree/README in the source
+ distribution for a much more detailed, internals-focused description
+ of the B-Tree implementation.
+
+ PostgreSQL B-Tree indexes are
+ multi-level tree structures, where each level of the tree can be
+ used as a doubly-linked list of pages. A single metapage is stored
+ in a fixed position at the start of the first segment file of the
+ index. All other pages are either leaf pages or internal pages.
+ Leaf pages are the pages on the lowest level of the tree. All
+ other levels consist of internal pages. Each leaf page contains
+ tuples that point to table rows. Each internal page contains
+ tuples that point to the next level down in the tree. Typically,
+ over 99% of all pages are leaf pages. Both internal pages and leaf
+ pages use the standard page format described in Section 73.6.
+
+ New leaf pages are added to a B-Tree index when an existing leaf
+ page cannot fit an incoming tuple. A page
+ split operation makes room for items that originally
+ belonged on the overflowing page by moving a portion of the items
+ to a new page. Page splits must also insert a new
+ downlink to the new page in the parent page,
+ which may cause the parent to split in turn. Page splits
+ “cascade upwards” in a recursive fashion. When the
+ root page finally cannot fit a new downlink, a root page
+ split operation takes place. This adds a new level to
+ the tree structure by creating a new root page that is one level
+ above the original root page.
+
+ B-Tree indexes are not directly aware that under MVCC, there might
+ be multiple extant versions of the same logical table row; to an
+ index, each tuple is an independent object that needs its own index
+ entry. “Version churn” tuples may sometimes
+ accumulate and adversely affect query latency and throughput. This
+ typically occurs with UPDATE-heavy workloads
+ where most individual updates cannot apply the
+ HOT optimization.
+ Changing the value of only
+ one column covered by one index during an UPDATE
+ always necessitates a new set of index tuples
+ — one for each and every index on the
+ table. Note in particular that this includes indexes that were not
+ “logically modified” by the UPDATE.
+ All indexes will need a successor physical index tuple that points
+ to the latest version in the table. Each new tuple within each
+ index will generally need to coexist with the original
+ “updated” tuple for a short period of time (typically
+ until shortly after the UPDATE transaction
+ commits).
+
+ B-Tree indexes incrementally delete version churn index tuples by
+ performing bottom-up index deletion passes.
+ Each deletion pass is triggered in reaction to an anticipated
+ “version churn page split”. This only happens with
+ indexes that are not logically modified by
+ UPDATE statements, where concentrated build up
+ of obsolete versions in particular pages would occur otherwise. A
+ page split will usually be avoided, though it's possible that
+ certain implementation-level heuristics will fail to identify and
+ delete even one garbage index tuple (in which case a page split or
+ deduplication pass resolves the issue of an incoming new tuple not
+ fitting on a leaf page). The worst-case number of versions that
+ any index scan must traverse (for any single logical row) is an
+ important contributor to overall system responsiveness and
+ throughput. A bottom-up index deletion pass targets suspected
+ garbage tuples in a single leaf page based on
+ qualitative distinctions involving logical
+ rows and versions. This contrasts with the “top-down”
+ index cleanup performed by autovacuum workers, which is triggered
+ when certain quantitative table-level
+ thresholds are exceeded (see Section 25.1.6).
+
Note
+ Not all deletion operations that are performed within B-Tree
+ indexes are bottom-up deletion operations. There is a distinct
+ category of index tuple deletion: simple index tuple
+ deletion. This is a deferred maintenance operation
+ that deletes index tuples that are known to be safe to delete
+ (those whose item identifier's LP_DEAD bit is
+ already set). Like bottom-up index deletion, simple index
+ deletion takes place at the point that a page split is anticipated
+ as a way of avoiding the split.
+
+ Simple deletion is opportunistic in the sense that it can only
+ take place when recent index scans set the
+ LP_DEAD bits of affected items in passing.
+ Prior to PostgreSQL 14, the only
+ category of B-Tree deletion was simple deletion. The main
+ differences between it and bottom-up deletion are that only the
+ former is opportunistically driven by the activity of passing
+ index scans, while only the latter specifically targets version
+ churn from UPDATEs that do not logically modify
+ indexed columns.
+
+ Bottom-up index deletion performs the vast majority of all garbage
+ index tuple cleanup for particular indexes with certain workloads.
+ This is expected with any B-Tree index that is subject to
+ significant version churn from UPDATEs that
+ rarely or never logically modify the columns that the index covers.
+ The average and worst-case number of versions per logical row can
+ be kept low purely through targeted incremental deletion passes.
+ It's quite possible that the on-disk size of certain indexes will
+ never increase by even one single page/block despite
+ constant version churn from
+ UPDATEs. Even then, an exhaustive “clean
+ sweep” by a VACUUM operation (typically
+ run in an autovacuum worker process) will eventually be required as
+ a part of collective cleanup of the table and
+ each of its indexes.
+
+ Unlike VACUUM, bottom-up index deletion does not
+ provide any strong guarantees about how old the oldest garbage
+ index tuple may be. No index can be permitted to retain
+ “floating garbage” index tuples that became dead prior
+ to a conservative cutoff point shared by the table and all of its
+ indexes collectively. This fundamental table-level invariant makes
+ it safe to recycle table TIDs. This is how it
+ is possible for distinct logical rows to reuse the same table
+ TID over time (though this can never happen with
+ two logical rows whose lifetimes span the same
+ VACUUM cycle).
+
+ A duplicate is a leaf page tuple (a tuple that points to a table
+ row) where all indexed key columns have values
+ that match corresponding column values from at least one other leaf
+ page tuple in the same index. Duplicate tuples are quite common in
+ practice. B-Tree indexes can use a special, space-efficient
+ representation for duplicates when an optional technique is
+ enabled: deduplication.
+
+ Deduplication works by periodically merging groups of duplicate
+ tuples together, forming a single posting list tuple for each
+ group. The column key value(s) only appear once in this
+ representation. This is followed by a sorted array of
+ TIDs that point to rows in the table. This
+ significantly reduces the storage size of indexes where each value
+ (or each distinct combination of column values) appears several
+ times on average. The latency of queries can be reduced
+ significantly. Overall query throughput may increase
+ significantly. The overhead of routine index vacuuming may also be
+ reduced significantly.
+
Note
+ B-Tree deduplication is just as effective with
+ “duplicates” that contain a NULL value, even though
+ NULL values are never equal to each other according to the
+ = member of any B-Tree operator class. As far
+ as any part of the implementation that understands the on-disk
+ B-Tree structure is concerned, NULL is just another value from the
+ domain of indexed values.
+
+ The deduplication process occurs lazily, when a new item is
+ inserted that cannot fit on an existing leaf page, though only when
+ index tuple deletion could not free sufficient space for the new
+ item (typically deletion is briefly considered and then skipped
+ over). Unlike GIN posting list tuples, B-Tree posting list tuples
+ do not need to expand every time a new duplicate is inserted; they
+ are merely an alternative physical representation of the original
+ logical contents of the leaf page. This design prioritizes
+ consistent performance with mixed read-write workloads. Most
+ client applications will at least see a moderate performance
+ benefit from using deduplication. Deduplication is enabled by
+ default.
+
+ CREATE INDEX and REINDEX
+ apply deduplication to create posting list tuples, though the
+ strategy they use is slightly different. Each group of duplicate
+ ordinary tuples encountered in the sorted input taken from the
+ table is merged into a posting list tuple
+ before being added to the current pending leaf
+ page. Individual posting list tuples are packed with as many
+ TIDs as possible. Leaf pages are written out in
+ the usual way, without any separate deduplication pass. This
+ strategy is well-suited to CREATE INDEX and
+ REINDEX because they are once-off batch
+ operations.
+
+ Write-heavy workloads that don't benefit from deduplication due to
+ having few or no duplicate values in indexes will incur a small,
+ fixed performance penalty (unless deduplication is explicitly
+ disabled). The deduplicate_items storage
+ parameter can be used to disable deduplication within individual
+ indexes. There is never any performance penalty with read-only
+ workloads, since reading posting list tuples is at least as
+ efficient as reading the standard tuple representation. Disabling
+ deduplication isn't usually helpful.
+
+ It is sometimes possible for unique indexes (as well as unique
+ constraints) to use deduplication. This allows leaf pages to
+ temporarily “absorb” extra version churn duplicates.
+ Deduplication in unique indexes augments bottom-up index deletion,
+ especially in cases where a long-running transaction holds a
+ snapshot that blocks garbage collection. The goal is to buy time
+ for the bottom-up index deletion strategy to become effective
+ again. Delaying page splits until a single long-running
+ transaction naturally goes away can allow a bottom-up deletion pass
+ to succeed where an earlier deletion pass failed.
+
Tip
+ A special heuristic is applied to determine whether a
+ deduplication pass in a unique index should take place. It can
+ often skip straight to splitting a leaf page, avoiding a
+ performance penalty from wasting cycles on unhelpful deduplication
+ passes. If you're concerned about the overhead of deduplication,
+ consider setting deduplicate_items = off
+ selectively. Leaving deduplication enabled in unique indexes has
+ little downside.
+
+ Deduplication cannot be used in all cases due to
+ implementation-level restrictions. Deduplication safety is
+ determined when CREATE INDEX or
+ REINDEX is run.
+
+ Note that deduplication is deemed unsafe and cannot be used in the
+ following cases involving semantically significant differences
+ among equal datums:
+
+
+ text, varchar, and char
+ cannot use deduplication when a
+ nondeterministic collation is used. Case
+ and accent differences must be preserved among equal datums.
+
+ numeric cannot use deduplication. Numeric display
+ scale must be preserved among equal datums.
+
+ jsonb cannot use deduplication, since the
+ jsonb B-Tree operator class uses
+ numeric internally.
+
+ float4 and float8 cannot use
+ deduplication. These types have distinct representations for
+ -0 and 0, which are
+ nevertheless considered equal. This difference must be
+ preserved.
+
+
+ There is one further implementation-level restriction that may be
+ lifted in a future version of
+ PostgreSQL:
+
+
+ Container types (such as composite types, arrays, or range
+ types) cannot use deduplication.
+
+
+ There is one further implementation-level restriction that applies
+ regardless of the operator class or collation used:
+
+
+ INCLUDE indexes can never use deduplication.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree-intro.html b/pgsql/doc/postgresql/html/btree-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..22f8d63ec3b841801de4e855dff430bb60fd1b5b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree-intro.html
@@ -0,0 +1,17 @@
+
+67.1. Introduction
+ PostgreSQL includes an implementation of the
+ standard btree (multi-way balanced tree) index data
+ structure. Any data type that can be sorted into a well-defined linear
+ order can be indexed by a btree index. The only limitation is that an
+ index entry cannot exceed approximately one-third of a page (after TOAST
+ compression, if applicable).
+
+ Because each btree operator class imposes a sort order on its data type,
+ btree operator classes (or, really, operator families) have come to be
+ used as PostgreSQL's general representation
+ and understanding of sorting semantics. Therefore, they've acquired
+ some features that go beyond what would be needed just to support btree
+ indexes, and parts of the system that are quite distant from the
+ btree AM make use of them.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree-support-funcs.html b/pgsql/doc/postgresql/html/btree-support-funcs.html
new file mode 100644
index 0000000000000000000000000000000000000000..3682faa8afce944a0d73943fe679be6cf593ca52
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree-support-funcs.html
@@ -0,0 +1,291 @@
+
+67.3. B-Tree Support Functions
+ As shown in Table 38.9, btree defines
+ one required and four optional support functions. The five
+ user-defined methods are:
+
order
+ For each combination of data types that a btree operator family
+ provides comparison operators for, it must provide a comparison
+ support function, registered in
+ pg_amproc with support function number 1
+ and
+ amproclefttype/amprocrighttype
+ equal to the left and right data types for the comparison (i.e.,
+ the same data types that the matching operators are registered
+ with in pg_amop). The comparison
+ function must take two non-null values
+ A and B and
+ return an int32 value that is
+ <0,
+ 0, or >
+ 0 when A
+ <B,
+ A=
+ B, or A
+ >B,
+ respectively. A null result is disallowed: all values of the
+ data type must be comparable. See
+ src/backend/access/nbtree/nbtcompare.c for
+ examples.
+
+ If the compared values are of a collatable data type, the
+ appropriate collation OID will be passed to the comparison
+ support function, using the standard
+ PG_GET_COLLATION() mechanism.
+
sortsupport
+ Optionally, a btree operator family may provide sort
+ support function(s), registered under support
+ function number 2. These functions allow implementing
+ comparisons for sorting purposes in a more efficient way than
+ naively calling the comparison support function. The APIs
+ involved in this are defined in
+ src/include/utils/sortsupport.h.
+
in_range
+ Optionally, a btree operator family may provide
+ in_range support function(s), registered
+ under support function number 3. These are not used during btree
+ index operations; rather, they extend the semantics of the
+ operator family so that it can support window clauses containing
+ the RANGEoffset
+ PRECEDING and RANGE
+ offsetFOLLOWING
+ frame bound types (see Section 4.2.8). Fundamentally, the extra
+ information provided is how to add or subtract an
+ offset value in a way that is
+ compatible with the family's data ordering.
+
+ An in_range function must have the signature
+
+in_range(val type1, base type1, offset type2, sub bool, less bool)
+returns bool
+
+ val and
+ base must be of the same type, which
+ is one of the types supported by the operator family (i.e., a
+ type for which it provides an ordering). However,
+ offset could be of a different type,
+ which might be one otherwise unsupported by the family. An
+ example is that the built-in time_ops family
+ provides an in_range function that has
+ offset of type interval.
+ A family can provide in_range functions for
+ any of its supported types and one or more
+ offset types. Each
+ in_range function should be entered in
+ pg_amproc with
+ amproclefttype equal to
+ type1 and amprocrighttype
+ equal to type2.
+
+ The essential semantics of an in_range
+ function depend on the two Boolean flag parameters. It should
+ add or subtract base and
+ offset, then compare
+ val to the result, as follows:
+
+ if !sub and
+ !less, return
+ val>=
+ (base+
+ offset)
+
+ if !sub and
+ less, return
+ val<=
+ (base+
+ offset)
+
+ if sub and
+ !less, return
+ val>=
+ (base-
+ offset)
+
+ if sub and
+ less, return
+ val<=
+ (base-
+ offset)
+
+ Before doing so, the function should check the sign of
+ offset: if it is less than zero, raise
+ error
+ ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE
+ (22013) with error text like “invalid preceding or
+ following size in window function”. (This is required by
+ the SQL standard, although nonstandard operator families might
+ perhaps choose to ignore this restriction, since there seems to
+ be little semantic necessity for it.) This requirement is
+ delegated to the in_range function so that
+ the core code needn't understand what “less than
+ zero” means for a particular data type.
+
+ An additional expectation is that in_range
+ functions should, if practical, avoid throwing an error if
+ base+
+ offset or
+ base-
+ offset would overflow. The correct
+ comparison result can be determined even if that value would be
+ out of the data type's range. Note that if the data type
+ includes concepts such as “infinity” or
+ “NaN”, extra care may be needed to ensure that
+ in_range's results agree with the normal
+ sort order of the operator family.
+
+ The results of the in_range function must be
+ consistent with the sort ordering imposed by the operator family.
+ To be precise, given any fixed values of
+ offset and
+ sub, then:
+
+ If in_range with
+ less = true is true for some
+ val1 and
+ base, it must be true for every
+ val2<=
+ val1 with the same
+ base.
+
+ If in_range with
+ less = true is false for some
+ val1 and
+ base, it must be false for every
+ val2>=
+ val1 with the same
+ base.
+
+ If in_range with
+ less = true is true for some
+ val and
+ base1, it must be true for every
+ base2>=
+ base1 with the same
+ val.
+
+ If in_range with
+ less = true is false for some
+ val and
+ base1, it must be false for every
+ base2<=
+ base1 with the same
+ val.
+
+ Analogous statements with inverted conditions hold when
+ less = false.
+
+ If the type being ordered (type1) is collatable, the
+ appropriate collation OID will be passed to the
+ in_range function, using the standard
+ PG_GET_COLLATION() mechanism.
+
+ in_range functions need not handle NULL
+ inputs, and typically will be marked strict.
+
equalimage
+ Optionally, a btree operator family may provide
+ equalimage (“equality implies image
+ equality”) support functions, registered under support
+ function number 4. These functions allow the core code to
+ determine when it is safe to apply the btree deduplication
+ optimization. Currently, equalimage
+ functions are only called when building or rebuilding an index.
+
+ An equalimage function must have the
+ signature
+
+equalimage(opcintypeoid) returns bool
+
+ The return value is static information about an operator class
+ and collation. Returning true indicates that
+ the order function for the operator class is
+ guaranteed to only return 0 (“arguments
+ are equal”) when its A and
+ B arguments are also interchangeable
+ without any loss of semantic information. Not registering an
+ equalimage function or returning
+ false indicates that this condition cannot be
+ assumed to hold.
+
+ The opcintype argument is the
+ pg_type.oid of the
+ data type that the operator class indexes. This is a convenience
+ that allows reuse of the same underlying
+ equalimage function across operator classes.
+ If opcintype is a collatable data
+ type, the appropriate collation OID will be passed to the
+ equalimage function, using the standard
+ PG_GET_COLLATION() mechanism.
+
+ As far as the operator class is concerned, returning
+ true indicates that deduplication is safe (or
+ safe for the collation whose OID was passed to its
+ equalimage function). However, the core
+ code will only deem deduplication safe for an index when
+ every indexed column uses an operator class
+ that registers an equalimage function, and
+ each function actually returns true when
+ called.
+
+ Image equality is almost the same condition
+ as simple bitwise equality. There is one subtle difference: When
+ indexing a varlena data type, the on-disk representation of two
+ image equal datums may not be bitwise equal due to inconsistent
+ application of TOAST compression on input.
+ Formally, when an operator class's
+ equalimage function returns
+ true, it is safe to assume that the
+ datum_image_eq() C function will always agree
+ with the operator class's order function
+ (provided that the same collation OID is passed to both the
+ equalimage and order
+ functions).
+
+ The core code is fundamentally unable to deduce anything about
+ the “equality implies image equality” status of an
+ operator class within a multiple-data-type family based on
+ details from other operator classes in the same family. Also, it
+ is not sensible for an operator family to register a cross-type
+ equalimage function, and attempting to do so
+ will result in an error. This is because “equality implies
+ image equality” status does not just depend on
+ sorting/equality semantics, which are more or less defined at the
+ operator family level. In general, the semantics that one
+ particular data type implements must be considered separately.
+
+ The convention followed by the operator classes included with the
+ core PostgreSQL distribution is to
+ register a stock, generic equalimage
+ function. Most operator classes register
+ btequalimage(), which indicates that
+ deduplication is safe unconditionally. Operator classes for
+ collatable data types such as text register
+ btvarstrequalimage(), which indicates that
+ deduplication is safe with deterministic collations. Best
+ practice for third-party extensions is to register their own
+ custom function to retain control.
+
options
+ Optionally, a B-tree operator family may provide
+ options (“operator class specific
+ options”) support functions, registered under support
+ function number 5. These functions define a set of user-visible
+ parameters that control operator class behavior.
+
+ An options support function must have the
+ signature
+
+options(reloptslocal_relopts *) returns void
+
+ The function is passed a pointer to a local_relopts
+ struct, which needs to be filled with a set of operator class
+ specific options. The options can be accessed from other support
+ functions using the PG_HAS_OPCLASS_OPTIONS() and
+ PG_GET_OPCLASS_OPTIONS() macros.
+
+ Currently, no B-Tree operator class has an options
+ support function. B-tree doesn't allow flexible representation of keys
+ like GiST, SP-GiST, GIN and BRIN do. So, options
+ probably doesn't have much application in the current B-tree index
+ access method. Nevertheless, this support function was added to B-tree
+ for uniformity, and will probably find uses during further
+ evolution of B-tree in PostgreSQL.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/btree.html b/pgsql/doc/postgresql/html/btree.html
new file mode 100644
index 0000000000000000000000000000000000000000..29a31209bab8ee8240241bccd26b4c9647eb2813
--- /dev/null
+++ b/pgsql/doc/postgresql/html/btree.html
@@ -0,0 +1,2 @@
+
+Chapter 67. B-Tree Indexes
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/bug-reporting.html b/pgsql/doc/postgresql/html/bug-reporting.html
new file mode 100644
index 0000000000000000000000000000000000000000..a743dc06a138bccd2486e1c127a1495d6e21bff2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/bug-reporting.html
@@ -0,0 +1,248 @@
+
+5. Bug Reporting Guidelines
+ When you find a bug in PostgreSQL we want to
+ hear about it. Your bug reports play an important part in making
+ PostgreSQL more reliable because even the utmost
+ care cannot guarantee that every part of
+ PostgreSQL
+ will work on every platform under every circumstance.
+
+ The following suggestions are intended to assist you in forming bug reports
+ that can be handled in an effective fashion. No one is required to follow
+ them but doing so tends to be to everyone's advantage.
+
+ We cannot promise to fix every bug right away. If the bug is obvious, critical,
+ or affects a lot of users, chances are good that someone will look into it. It
+ could also happen that we tell you to update to a newer version to see if the
+ bug happens there. Or we might decide that the bug
+ cannot be fixed before some major rewrite we might be planning is done. Or
+ perhaps it is simply too hard and there are more important things on the agenda.
+ If you need help immediately, consider obtaining a commercial support contract.
+
+ Before you report a bug, please read and re-read the
+ documentation to verify that you can really do whatever it is you are
+ trying. If it is not clear from the documentation whether you can do
+ something or not, please report that too; it is a bug in the documentation.
+ If it turns out that a program does something different from what the
+ documentation says, that is a bug. That might include, but is not limited to,
+ the following circumstances:
+
+
+ A program terminates with a fatal signal or an operating system
+ error message that would point to a problem in the program. (A
+ counterexample might be a “disk full” message,
+ since you have to fix that yourself.)
+
+ A program produces the wrong output for any given input.
+
+ A program refuses to accept valid input (as defined in the documentation).
+
+ A program accepts invalid input without a notice or error message.
+ But keep in mind that your idea of invalid input might be our idea of
+ an extension or compatibility with traditional practice.
+
+ PostgreSQL fails to compile, build, or
+ install according to the instructions on supported platforms.
+
+
+ Here “program” refers to any executable, not only the backend process.
+
+ Being slow or resource-hogging is not necessarily a bug. Read the
+ documentation or ask on one of the mailing lists for help in tuning your
+ applications. Failing to comply to the SQL standard is
+ not necessarily a bug either, unless compliance for the
+ specific feature is explicitly claimed.
+
+ Before you continue, check on the TODO list and in the FAQ to see if your bug is
+ already known. If you cannot decode the information on the TODO list, report your
+ problem. The least we can do is make the TODO list clearer.
+
+ The most important thing to remember about bug reporting is to state all
+ the facts and only facts. Do not speculate what you think went wrong, what
+ “it seemed to do”, or which part of the program has a fault.
+ If you are not familiar with the implementation you would probably guess
+ wrong and not help us a bit. And even if you are, educated explanations are
+ a great supplement to but no substitute for facts. If we are going to fix
+ the bug we still have to see it happen for ourselves first.
+ Reporting the bare facts
+ is relatively straightforward (you can probably copy and paste them from the
+ screen) but all too often important details are left out because someone
+ thought it does not matter or the report would be understood
+ anyway.
+
+ The following items should be contained in every bug report:
+
+
+ The exact sequence of steps from program
+ start-up necessary to reproduce the problem. This
+ should be self-contained; it is not enough to send in a bare
+ SELECT statement without the preceding
+ CREATE TABLE and INSERT
+ statements, if the output should depend on the data in the
+ tables. We do not have the time to reverse-engineer your
+ database schema, and if we are supposed to make up our own data
+ we would probably miss the problem.
+
+ The best format for a test case for SQL-related problems is a
+ file that can be run through the psql
+ frontend that shows the problem. (Be sure to not have anything
+ in your ~/.psqlrc start-up file.) An easy
+ way to create this file is to use pg_dump
+ to dump out the table declarations and data needed to set the
+ scene, then add the problem query. You are encouraged to
+ minimize the size of your example, but this is not absolutely
+ necessary. If the bug is reproducible, we will find it either
+ way.
+
+ If your application uses some other client interface, such as PHP, then
+ please try to isolate the offending queries. We will probably not set up a
+ web server to reproduce your problem. In any case remember to provide
+ the exact input files; do not guess that the problem happens for
+ “large files” or “midsize databases”, etc. since this
+ information is too inexact to be of use.
+
+ The output you got. Please do not say that it “didn't work” or
+ “crashed”. If there is an error message,
+ show it, even if you do not understand it. If the program terminates with
+ an operating system error, say which. If nothing at all happens, say so.
+ Even if the result of your test case is a program crash or otherwise obvious
+ it might not happen on our platform. The easiest thing is to copy the output
+ from the terminal, if possible.
+
Note
+ If you are reporting an error message, please obtain the most verbose
+ form of the message. In psql, say \set
+ VERBOSITY verbose beforehand. If you are extracting the message
+ from the server log, set the run-time parameter
+ log_error_verbosity to verbose so that all
+ details are logged.
+
Note
+ In case of fatal errors, the error message reported by the client might
+ not contain all the information available. Please also look at the
+ log output of the database server. If you do not keep your server's log
+ output, this would be a good time to start doing so.
+
+ The output you expected is very important to state. If you just write
+ “This command gives me that output.” or “This is not
+ what I expected.”, we might run it ourselves, scan the output, and
+ think it looks OK and is exactly what we expected. We should not have to
+ spend the time to decode the exact semantics behind your commands.
+ Especially refrain from merely saying that “This is not what SQL says/Oracle
+ does.” Digging out the correct behavior from SQL
+ is not a fun undertaking, nor do we all know how all the other relational
+ databases out there behave. (If your problem is a program crash, you can
+ obviously omit this item.)
+
+ Any command line options and other start-up options, including
+ any relevant environment variables or configuration files that
+ you changed from the default. Again, please provide exact
+ information. If you are using a prepackaged distribution that
+ starts the database server at boot time, you should try to find
+ out how that is done.
+
+ Anything you did at all differently from the installation
+ instructions.
+
+ The PostgreSQL version. You can run the command
+ SELECT version(); to
+ find out the version of the server you are connected to. Most executable
+ programs also support a --version option; at least
+ postgres --version and psql --version
+ should work.
+ If the function or the options do not exist then your version is
+ more than old enough to warrant an upgrade.
+ If you run a prepackaged version, such as RPMs, say so, including any
+ subversion the package might have. If you are talking about a Git
+ snapshot, mention that, including the commit hash.
+
+ If your version is older than 16.3 we will almost certainly
+ tell you to upgrade. There are many bug fixes and improvements
+ in each new release, so it is quite possible that a bug you have
+ encountered in an older release of PostgreSQL
+ has already been fixed. We can only provide limited support for
+ sites using older releases of PostgreSQL; if you
+ require more than we can provide, consider acquiring a
+ commercial support contract.
+
+
+ Platform information. This includes the kernel name and version,
+ C library, processor, memory information, and so on. In most
+ cases it is sufficient to report the vendor and version, but do
+ not assume everyone knows what exactly “Debian”
+ contains or that everyone runs on x86_64. If you have
+ installation problems then information about the toolchain on
+ your machine (compiler, make, and so
+ on) is also necessary.
+
+
+ Do not be afraid if your bug report becomes rather lengthy. That is a fact of life.
+ It is better to report everything the first time than us having to squeeze the
+ facts out of you. On the other hand, if your input files are huge, it is
+ fair to ask first whether somebody is interested in looking into it. Here is
+ an article
+ that outlines some more tips on reporting bugs.
+
+ Do not spend all your time to figure out which changes in the input make
+ the problem go away. This will probably not help solving it. If it turns
+ out that the bug cannot be fixed right away, you will still have time to
+ find and share your work-around. Also, once again, do not waste your time
+ guessing why the bug exists. We will find that out soon enough.
+
+ When writing a bug report, please avoid confusing terminology.
+ The software package in total is called “PostgreSQL”,
+ sometimes “Postgres” for short. If you
+ are specifically talking about the backend process, mention that, do not
+ just say “PostgreSQL crashes”. A crash of a single
+ backend process is quite different from crash of the parent
+ “postgres” process; please don't say “the server
+ crashed” when you mean a single backend process went down, nor vice versa.
+ Also, client programs such as the interactive frontend “psql”
+ are completely separate from the backend. Please try to be specific
+ about whether the problem is on the client or server side.
+
+ In general, send bug reports to the bug report mailing list at
+ <pgsql-bugs@lists.postgresql.org>.
+ You are requested to use a descriptive subject for your email
+ message, perhaps parts of the error message.
+
+ Another method is to fill in the bug report web-form available
+ at the project's
+ web site.
+ Entering a bug report this way causes it to be mailed to the
+ <pgsql-bugs@lists.postgresql.org> mailing list.
+
+ If your bug report has security implications and you'd prefer that it
+ not become immediately visible in public archives, don't send it to
+ pgsql-bugs. Security issues can be
+ reported privately to <security@postgresql.org>.
+
+ Do not send bug reports to any of the user mailing lists, such as
+ <pgsql-sql@lists.postgresql.org> or
+ <pgsql-general@lists.postgresql.org>.
+ These mailing lists are for answering
+ user questions, and their subscribers normally do not wish to receive
+ bug reports. More importantly, they are unlikely to fix them.
+
+ Also, please do not send reports to
+ the developers' mailing list <pgsql-hackers@lists.postgresql.org>.
+ This list is for discussing the
+ development of PostgreSQL, and it would be nice
+ if we could keep the bug reports separate. We might choose to take up a
+ discussion about your bug report on pgsql-hackers,
+ if the problem needs more review.
+
+ If you have a problem with the documentation, the best place to report it
+ is the documentation mailing list <pgsql-docs@lists.postgresql.org>.
+ Please be specific about what part of the documentation you are unhappy
+ with.
+
+ If your bug is a portability problem on a non-supported platform,
+ send mail to <pgsql-hackers@lists.postgresql.org>,
+ so we (and you) can work on
+ porting PostgreSQL to your platform.
+
Note
+ Due to the unfortunate amount of spam going around, all of the above
+ lists will be moderated unless you are subscribed. That means there
+ will be some delay before the email is delivered. If you wish to subscribe
+ to the lists, please visit
+ https://lists.postgresql.org/ for instructions.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-aggregate.html b/pgsql/doc/postgresql/html/catalog-pg-aggregate.html
new file mode 100644
index 0000000000000000000000000000000000000000..5348a2896a5abefd2482d01e6b84bd610f32e339
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-aggregate.html
@@ -0,0 +1,170 @@
+
+53.2. pg_aggregate
+ The catalog pg_aggregate stores information about
+ aggregate functions. An aggregate function is a function that
+ operates on a set of values (typically one column from each row
+ that matches a query condition) and returns a single value computed
+ from all these values. Typical aggregate functions are
+ sum, count, and
+ max. Each entry in
+ pg_aggregate is an extension of an entry
+ in pg_proc.
+ The pg_proc entry carries the aggregate's name,
+ input and output data types, and other information that is similar to
+ ordinary functions.
+
+ Aggregate kind:
+ n for “normal” aggregates,
+ o for “ordered-set” aggregates, or
+ h for “hypothetical-set” aggregates
+
+ aggnumdirectargsint2
+
+
+ Number of direct (non-aggregated) arguments of an ordered-set or
+ hypothetical-set aggregate, counting a variadic array as one argument.
+ If equal to pronargs, the aggregate must be variadic
+ and the variadic array describes the aggregated arguments as well as
+ the final direct arguments.
+ Always zero for normal aggregates.
+
+ Final function for moving-aggregate mode (zero if none)
+
+ aggfinalextrabool
+
+
+ True to pass extra dummy arguments to aggfinalfn
+
+ aggmfinalextrabool
+
+
+ True to pass extra dummy arguments to aggmfinalfn
+
+ aggfinalmodifychar
+
+
+ Whether aggfinalfn modifies the
+ transition state value:
+ r if it is read-only,
+ s if the aggtransfn
+ cannot be applied after the aggfinalfn, or
+ w if it writes on the value
+
+ aggmfinalmodifychar
+
+
+ Like aggfinalmodify, but for
+ the aggmfinalfn
+
+ Data type of the aggregate function's internal transition (state)
+ data for moving-aggregate mode (zero if none)
+
+ aggmtransspaceint4
+
+
+ Approximate average size (in bytes) of the transition state data
+ for moving-aggregate mode, or zero to use a default estimate
+
+ agginitvaltext
+
+
+ The initial value of the transition state. This is a text
+ field containing the initial value in its external string
+ representation. If this field is null, the transition state
+ value starts out null.
+
+ aggminitvaltext
+
+
+ The initial value of the transition state for moving-aggregate mode.
+ This is a text field containing the initial value in its external
+ string representation. If this field is null, the transition state
+ value starts out null.
+
+ New aggregate functions are registered with the CREATE AGGREGATE
+ command. See Section 38.12 for more information about
+ writing aggregate functions and the meaning of the transition
+ functions, etc.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-am.html b/pgsql/doc/postgresql/html/catalog-pg-am.html
new file mode 100644
index 0000000000000000000000000000000000000000..2d6322217663fbb66bc028cff417b04c5fbe9a04
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-am.html
@@ -0,0 +1,44 @@
+
+53.3. pg_am
+ The catalog pg_am stores information about
+ relation access methods. There is one row for each access method supported
+ by the system.
+ Currently, only tables and indexes have access methods. The requirements for table
+ and index access methods are discussed in detail in Chapter 63 and
+ Chapter 64 respectively.
+
+ OID of a handler function that is responsible for supplying information
+ about the access method
+
+ amtypechar
+
+
+ t = table (including materialized views),
+ i = index.
+
Note
+ Before PostgreSQL 9.6, pg_am
+ contained many additional columns representing properties of index access
+ methods. That data is now only directly visible at the C code level.
+ However, pg_index_column_has_property() and related
+ functions have been added to allow SQL queries to inspect index access
+ method properties; see Table 9.72.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-amop.html b/pgsql/doc/postgresql/html/catalog-pg-amop.html
new file mode 100644
index 0000000000000000000000000000000000000000..30228b7046753283309e66acceb4ce27483e80bc
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-amop.html
@@ -0,0 +1,104 @@
+
+53.4. pg_amop
+ The catalog pg_amop stores information about
+ operators associated with access method operator families. There is one
+ row for each operator that is a member of an operator family. A family
+ member can be either a search operator or an
+ ordering operator. An operator
+ can appear in more than one family, but cannot appear in more than one
+ search position nor more than one ordering position within a family.
+ (It is allowed, though unlikely, for an operator to be used for both
+ search and ordering purposes.)
+
+ The B-tree operator family this entry sorts according to, if an
+ ordering operator; zero if a search operator
+
+ A “search” operator entry indicates that an index of this operator
+ family can be searched to find all rows satisfying
+ WHERE
+ indexed_column
+ operator
+ constant.
+ Obviously, such an operator must return boolean, and its left-hand input
+ type must match the index's column data type.
+
+ An “ordering” operator entry indicates that an index of this
+ operator family can be scanned to return rows in the order represented by
+ ORDER BY
+ indexed_column
+ operator
+ constant.
+ Such an operator could return any sortable data type, though again
+ its left-hand input type must match the index's column data type.
+ The exact semantics of the ORDER BY are specified by the
+ amopsortfamily column, which must reference
+ a B-tree operator family for the operator's result type.
+
Note
+ At present, it's assumed that the sort order for an ordering operator
+ is the default for the referenced operator family, i.e., ASC NULLS
+ LAST. This might someday be relaxed by adding additional columns
+ to specify sort options explicitly.
+
+ An entry's amopmethod must match the
+ opfmethod of its containing operator family (including
+ amopmethod here is an intentional denormalization of the
+ catalog structure for performance reasons). Also,
+ amoplefttype and amoprighttype must match
+ the oprleft and oprright fields of the
+ referenced pg_operator entry.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-amproc.html b/pgsql/doc/postgresql/html/catalog-pg-amproc.html
new file mode 100644
index 0000000000000000000000000000000000000000..826567dbd022b6343569ab7cfcbcabddc2b04c8a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-amproc.html
@@ -0,0 +1,55 @@
+
+53.5. pg_amproc
+ The catalog pg_amproc stores information about
+ support functions associated with access method operator families. There
+ is one row for each support function belonging to an operator family.
+
+ The usual interpretation of the
+ amproclefttype and amprocrighttype fields
+ is that they identify the left and right input types of the operator(s)
+ that a particular support function supports. For some access methods
+ these match the input data type(s) of the support function itself, for
+ others not. There is a notion of “default” support functions for
+ an index, which are those with amproclefttype and
+ amprocrighttype both equal to the index operator class's
+ opcintype.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-attrdef.html b/pgsql/doc/postgresql/html/catalog-pg-attrdef.html
new file mode 100644
index 0000000000000000000000000000000000000000..951abbaff608a36ad63a1162b4d075680e798b79
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-attrdef.html
@@ -0,0 +1,37 @@
+
+53.6. pg_attrdef
+ The catalog pg_attrdef stores column default
+ values. The main information about columns is stored in
+ pg_attribute.
+ Only columns for which a default value has been explicitly set will have
+ an entry here.
+
+ The column default value, in nodeToString()
+ representation. Use pg_get_expr(adbin, adrelid) to
+ convert it to an SQL expression.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-attribute.html b/pgsql/doc/postgresql/html/catalog-pg-attribute.html
new file mode 100644
index 0000000000000000000000000000000000000000..08474d08c7b3131c40a7f90c6a15551e971c3383
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-attribute.html
@@ -0,0 +1,211 @@
+
+53.7. pg_attribute
+ The catalog pg_attribute stores information about
+ table columns. There will be exactly one
+ pg_attribute row for every column in every
+ table in the database. (There will also be attribute entries for
+ indexes, and indeed all objects that have
+ pg_class
+ entries.)
+
+ The term attribute is equivalent to column and is used for
+ historical reasons.
+
+ The data type of this column (zero for a dropped column)
+
+ attlenint2
+
+
+ A copy of pg_type.typlen of this column's
+ type
+
+ attnumint2
+
+
+ The number of the column. Ordinary columns are numbered from 1
+ up. System columns, such as ctid,
+ have (arbitrary) negative numbers.
+
+ attcacheoffint4
+
+
+ Always -1 in storage, but when loaded into a row descriptor
+ in memory this might be updated to cache the offset of the attribute
+ within the row
+
+ atttypmodint4
+
+
+ atttypmod records type-specific data
+ supplied at table creation time (for example, the maximum
+ length of a varchar column). It is passed to
+ type-specific input functions and length coercion functions.
+ The value will generally be -1 for types that do not need atttypmod.
+
+ attndimsint2
+
+
+ Number of dimensions, if the column is an array type; otherwise 0.
+ (Presently, the number of dimensions of an array is not enforced,
+ so any nonzero value effectively means “it's an array”.)
+
+ attbyvalbool
+
+
+ A copy of pg_type.typbyval of this column's type
+
+ attalignchar
+
+
+ A copy of pg_type.typalign of this column's type
+
+ attstoragechar
+
+
+ Normally a copy of pg_type.typstorage of this
+ column's type. For TOAST-able data types, this can be altered
+ after column creation to control storage policy.
+
+ attcompressionchar
+
+
+ The current compression method of the column. Typically this is
+ '\0' to specify use of the current default setting
+ (see default_toast_compression). Otherwise,
+ 'p' selects pglz compression, while
+ 'l' selects LZ4
+ compression. However, this field is ignored
+ whenever attstorage does not allow
+ compression.
+
+ attnotnullbool
+
+
+ This represents a not-null constraint.
+
+ atthasdefbool
+
+
+ This column has a default expression or generation expression, in which
+ case there will be a corresponding entry in the
+ pg_attrdef catalog that actually defines the
+ expression. (Check attgenerated to
+ determine whether this is a default or a generation expression.)
+
+ atthasmissingbool
+
+
+ This column has a value which is used where the column is entirely
+ missing from the row, as happens when a column is added with a
+ non-volatile DEFAULT value after the row is created.
+ The actual value used is stored in the
+ attmissingval column.
+
+ attidentitychar
+
+
+ If a zero byte (''), then not an identity column.
+ Otherwise, a = generated
+ always, d = generated by default.
+
+ attgeneratedchar
+
+
+ If a zero byte (''), then not a generated column.
+ Otherwise, s = stored. (Other values might be added
+ in the future.)
+
+ attisdroppedbool
+
+
+ This column has been dropped and is no longer valid. A dropped
+ column is still physically present in the table, but is
+ ignored by the parser and so cannot be accessed via SQL.
+
+ attislocalbool
+
+
+ This column is defined locally in the relation. Note that a column can
+ be locally defined and inherited simultaneously.
+
+ attinhcountint2
+
+
+ The number of direct ancestors this column has. A column with a
+ nonzero number of ancestors cannot be dropped nor renamed.
+
+ attstattargetint2
+
+
+ attstattarget controls the level of detail
+ of statistics accumulated for this column by
+ ANALYZE.
+ A zero value indicates that no statistics should be collected.
+ A negative value says to use the system default statistics target.
+ The exact meaning of positive values is data type-dependent.
+ For scalar data types, attstattarget
+ is both the target number of “most common values”
+ to collect, and the target number of histogram bins to create.
+
+ The defined collation of the column, or zero if the column is
+ not of a collatable data type
+
+ attaclaclitem[]
+
+
+ Column-level access privileges, if any have been granted specifically
+ on this column
+
+ attoptionstext[]
+
+
+ Attribute-level options, as “keyword=value” strings
+
+ attfdwoptionstext[]
+
+
+ Attribute-level foreign data wrapper options, as “keyword=value” strings
+
+ attmissingvalanyarray
+
+
+ This column has a one element array containing the value used when the
+ column is entirely missing from the row, as happens when the column is
+ added with a non-volatile DEFAULT value after the
+ row is created. The value is only used when
+ atthasmissing is true. If there is no value
+ the column is null.
+
+ In a dropped column's pg_attribute entry,
+ atttypid is reset to zero, but
+ attlen and the other fields copied from
+ pg_type are still valid. This arrangement is needed
+ to cope with the situation where the dropped column's data type was
+ later dropped, and so there is no pg_type row anymore.
+ attlen and the other fields can be used
+ to interpret the contents of a row of the table.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-auth-members.html b/pgsql/doc/postgresql/html/catalog-pg-auth-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..ec44a7712f8ca015a6d0ecbb38fbe81b9d892e14
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-auth-members.html
@@ -0,0 +1,58 @@
+
+53.9. pg_auth_members
+ The catalog pg_auth_members shows the membership
+ relations between roles. Any non-circular set of relationships is allowed.
+
+ Because user identities are cluster-wide,
+ pg_auth_members
+ is shared across all databases of a cluster: there is only one
+ copy of pg_auth_members per cluster, not
+ one per database.
+
+ True if member can grant membership in
+ roleid to others
+
+ inherit_optionbool
+
+
+ True if the member automatically inherits the privileges of the
+ granted role
+
+ set_optionbool
+
+
+ True if the member can
+ SET ROLE
+ to the granted role
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-authid.html b/pgsql/doc/postgresql/html/catalog-pg-authid.html
new file mode 100644
index 0000000000000000000000000000000000000000..6ac0f5d95c9137f350e450ee76244fb0509ee364
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-authid.html
@@ -0,0 +1,113 @@
+
+53.8. pg_authid
+ The catalog pg_authid contains information about
+ database authorization identifiers (roles). A role subsumes the concepts
+ of “users” and “groups”. A user is essentially just a
+ role with the rolcanlogin flag set. Any role (with or
+ without rolcanlogin) can have other roles as members; see
+ pg_auth_members.
+
+ Since this catalog contains passwords, it must not be publicly readable.
+ pg_roles
+ is a publicly readable view on
+ pg_authid that blanks out the password field.
+
+ Chapter 22 contains detailed information about user and
+ privilege management.
+
+ Because user identities are cluster-wide,
+ pg_authid
+ is shared across all databases of a cluster: there is only one
+ copy of pg_authid per cluster, not
+ one per database.
+
Table 53.8. pg_authid Columns
+ Column Type
+
+
+ Description
+
+ oidoid
+
+
+ Row identifier
+
+ rolnamename
+
+
+ Role name
+
+ rolsuperbool
+
+
+ Role has superuser privileges
+
+ rolinheritbool
+
+
+ Role automatically inherits privileges of roles it is a
+ member of
+
+ rolcreaterolebool
+
+
+ Role can create more roles
+
+ rolcreatedbbool
+
+
+ Role can create databases
+
+ rolcanloginbool
+
+
+ Role can log in. That is, this role can be given as the initial
+ session authorization identifier.
+
+ rolreplicationbool
+
+
+ Role is a replication role. A replication role can initiate replication
+ connections and create and drop replication slots.
+
+ rolbypassrlsbool
+
+
+ Role bypasses every row-level security policy, see
+ Section 5.8 for more information.
+
+ rolconnlimitint4
+
+
+ For roles that can log in, this sets maximum number of concurrent
+ connections this role can make. -1 means no limit.
+
+ rolpasswordtext
+
+
+ Password (possibly encrypted); null if none. The format depends
+ on the form of encryption used.
+
+ rolvaliduntiltimestamptz
+
+
+ Password expiry time (only used for password authentication);
+ null if no expiration
+
+ For an MD5 encrypted password, rolpassword
+ column will begin with the string md5 followed by a
+ 32-character hexadecimal MD5 hash. The MD5 hash will be of the user's
+ password concatenated to their user name. For example, if user
+ joe has password xyzzy, PostgreSQL
+ will store the md5 hash of xyzzyjoe.
+
+ If the password is encrypted with SCRAM-SHA-256, it has the format:
+
+ where salt, StoredKey and
+ ServerKey are in Base64 encoded format. This format is
+ the same as that specified by RFC 5803.
+
+ A password that does not follow either of those formats is assumed to be
+ unencrypted.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-cast.html b/pgsql/doc/postgresql/html/catalog-pg-cast.html
new file mode 100644
index 0000000000000000000000000000000000000000..f439849c9b84ea802fe8b840c1346f1d014cbda6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-cast.html
@@ -0,0 +1,86 @@
+
+53.10. pg_cast
+ The catalog pg_cast stores data type conversion
+ paths, both built-in and user-defined.
+
+ It should be noted that pg_cast does not represent
+ every type conversion that the system knows how to perform; only those that
+ cannot be deduced from some generic rule. For example, casting between a
+ domain and its base type is not explicitly represented in
+ pg_cast. Another important exception is that
+ “automatic I/O conversion casts”, those performed using a data
+ type's own I/O functions to convert to or from text or other
+ string types, are not explicitly represented in
+ pg_cast.
+
+ The OID of the function to use to perform this cast. Zero is
+ stored if the cast method doesn't require a function.
+
+ castcontextchar
+
+
+ Indicates what contexts the cast can be invoked in.
+ e means only as an explicit cast (using
+ CAST or :: syntax).
+ a means implicitly in assignment
+ to a target column, as well as explicitly.
+ i means implicitly in expressions, as well as the
+ other cases.
+
+ castmethodchar
+
+
+ Indicates how the cast is performed.
+ f means that the function specified in the castfunc field is used.
+ i means that the input/output functions are used.
+ b means that the types are binary-coercible, thus no conversion is required.
+
+ The cast functions listed in pg_cast must
+ always take the cast source type as their first argument type, and
+ return the cast destination type as their result type. A cast
+ function can have up to three arguments. The second argument,
+ if present, must be type integer; it receives the type
+ modifier associated with the destination type, or -1
+ if there is none. The third argument,
+ if present, must be type boolean; it receives true
+ if the cast is an explicit cast, false otherwise.
+
+ It is legitimate to create a pg_cast entry
+ in which the source and target types are the same, if the associated
+ function takes more than one argument. Such entries represent
+ “length coercion functions” that coerce values of the type
+ to be legal for a particular type modifier value.
+
+ When a pg_cast entry has different source and
+ target types and a function that takes more than one argument, it
+ represents converting from one type to another and applying a length
+ coercion in a single step. When no such entry is available, coercion
+ to a type that uses a type modifier involves two steps, one to
+ convert between data types and a second to apply the modifier.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-class.html b/pgsql/doc/postgresql/html/catalog-pg-class.html
new file mode 100644
index 0000000000000000000000000000000000000000..67ca8258f8b12184bd50bd757ddc964f8acf5116
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-class.html
@@ -0,0 +1,267 @@
+
+53.11. pg_class
+ The catalog pg_class describes tables and
+ other objects that have columns or are otherwise similar to a
+ table. This includes indexes (but see also pg_index),
+ sequences (but see also pg_sequence),
+ views, materialized views, composite types, and TOAST tables;
+ see relkind.
+ Below, when we mean all of these kinds of objects we speak of
+ “relations”. Not all of pg_class's
+ columns are meaningful for all relation kinds.
+
+ The OID of the data type that corresponds to this table's row type,
+ if any; zero for indexes, sequences, and toast tables, which have
+ no pg_type entry
+
+ If this is a table or an index, the access method used (heap,
+ B-tree, hash, etc.); otherwise zero (zero occurs for sequences,
+ as well as relations without storage, such as views)
+
+ relfilenodeoid
+
+
+ Name of the on-disk file of this relation; zero means this
+ is a “mapped” relation whose disk file name is determined
+ by low-level state
+
+ The tablespace in which this relation is stored.
+ If zero, the database's default tablespace is implied.
+ Not meaningful if the relation has no on-disk file,
+ except for partitioned tables, where this is the tablespace
+ in which partitions will be created when one is not
+ specified in the creation command.
+
+ relpagesint4
+
+
+ Size of the on-disk representation of this table in pages (of size
+ BLCKSZ). This is only an estimate used by the
+ planner. It is updated by VACUUM,
+ ANALYZE, and a few DDL commands such as
+ CREATE INDEX.
+
+ reltuplesfloat4
+
+
+ Number of live rows in the table. This is only an estimate used by
+ the planner. It is updated by VACUUM,
+ ANALYZE, and a few DDL commands such as
+ CREATE INDEX.
+ If the table has never yet been vacuumed or
+ analyzed, reltuples
+ contains -1 indicating that the row count is
+ unknown.
+
+ relallvisibleint4
+
+
+ Number of pages that are marked all-visible in the table's
+ visibility map. This is only an estimate used by the
+ planner. It is updated by VACUUM,
+ ANALYZE, and a few DDL commands such as
+ CREATE INDEX.
+
+ OID of the TOAST table associated with this table, zero if none. The
+ TOAST table stores large attributes “out of line” in a
+ secondary table.
+
+ relhasindexbool
+
+
+ True if this is a table and it has (or recently had) any indexes
+
+ relissharedbool
+
+
+ True if this table is shared across all databases in the cluster. Only
+ certain system catalogs (such as pg_database)
+ are shared.
+
+ relpersistencechar
+
+
+ p = permanent table/sequence, u = unlogged table/sequence,
+ t = temporary table/sequence
+
+ relkindchar
+
+
+ r = ordinary table,
+ i = index,
+ S = sequence,
+ t = TOAST table,
+ v = view,
+ m = materialized view,
+ c = composite type,
+ f = foreign table,
+ p = partitioned table,
+ I = partitioned index
+
+ relnattsint2
+
+
+ Number of user columns in the relation (system columns not
+ counted). There must be this many corresponding entries in
+ pg_attribute. See also
+ pg_attribute.attnum.
+
+ relchecksint2
+
+
+ Number of CHECK constraints on the table; see
+ pg_constraint catalog
+
+ relhasrulesbool
+
+
+ True if table has (or once had) rules; see
+ pg_rewrite catalog
+
+ relhastriggersbool
+
+
+ True if table has (or once had) triggers; see
+ pg_trigger catalog
+
+ relhassubclassbool
+
+
+ True if table or index has (or once had) any inheritance children or partitions
+
+ relrowsecuritybool
+
+
+ True if table has row-level security enabled; see
+ pg_policy catalog
+
+ relforcerowsecuritybool
+
+
+ True if row-level security (when enabled) will also apply to table owner; see
+ pg_policy catalog
+
+ relispopulatedbool
+
+
+ True if relation is populated (this is true for all
+ relations other than some materialized views)
+
+ relreplidentchar
+
+
+ Columns used to form “replica identity” for rows:
+ d = default (primary key, if any),
+ n = nothing,
+ f = all columns,
+ i = index with
+ indisreplident set (same as nothing if the
+ index used has been dropped)
+
+ For new relations being written during a DDL operation that requires a
+ table rewrite, this contains the OID of the original relation;
+ otherwise zero. That state is only visible internally; this field should
+ never contain anything other than zero for a user-visible relation.
+
+ relfrozenxidxid
+
+
+ All transaction IDs before this one have been replaced with a permanent
+ (“frozen”) transaction ID in this table. This is used to track
+ whether the table needs to be vacuumed in order to prevent transaction
+ ID wraparound or to allow pg_xact to be shrunk. Zero
+ (InvalidTransactionId) if the relation is not a table.
+
+ relminmxidxid
+
+
+ All multixact IDs before this one have been replaced by a
+ transaction ID in this table. This is used to track
+ whether the table needs to be vacuumed in order to prevent multixact ID
+ wraparound or to allow pg_multixact to be shrunk. Zero
+ (InvalidMultiXactId) if the relation is not a table.
+
+ relaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
+ reloptionstext[]
+
+
+ Access-method-specific options, as “keyword=value” strings
+
+ relpartboundpg_node_tree
+
+
+ If table is a partition (see relispartition),
+ internal representation of the partition bound
+
+ Several of the Boolean flags in pg_class are maintained
+ lazily: they are guaranteed to be true if that's the correct state, but
+ may not be reset to false immediately when the condition is no longer
+ true. For example, relhasindex is set by
+ CREATE INDEX, but it is never cleared by
+ DROP INDEX. Instead, VACUUM clears
+ relhasindex if it finds the table has no indexes. This
+ arrangement avoids race conditions and improves concurrency.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-collation.html b/pgsql/doc/postgresql/html/catalog-pg-collation.html
new file mode 100644
index 0000000000000000000000000000000000000000..61fb425a38568e242de26061c548de2f31a84ff4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-collation.html
@@ -0,0 +1,98 @@
+
+53.12. pg_collation
+ The catalog pg_collation describes the
+ available collations, which are essentially mappings from an SQL
+ name to operating system locale categories.
+ See Section 24.2 for more information.
+
Table 53.12. pg_collation Columns
+ Column Type
+
+
+ Description
+
+ oidoid
+
+
+ Row identifier
+
+ collnamename
+
+
+ Collation name (unique per namespace and encoding)
+
+ Provider of the collation: d = database
+ default, c = libc, i = icu
+
+ collisdeterministicbool
+
+
+ Is the collation deterministic?
+
+ collencodingint4
+
+
+ Encoding in which the collation is applicable, or -1 if it
+ works for any encoding
+
+ collcollatetext
+
+
+ LC_COLLATE for this collation object
+
+ collctypetext
+
+
+ LC_CTYPE for this collation object
+
+ colliculocaletext
+
+
+ ICU locale ID for this collation object
+
+ collicurulestext
+
+
+ ICU collation rules for this collation object
+
+ collversiontext
+
+
+ Provider-specific version of the collation. This is recorded when the
+ collation is created and then checked when it is used, to detect
+ changes in the collation definition that could lead to data corruption.
+
+ Note that the unique key on this catalog is (collname,
+ collencoding, collnamespace) not just
+ (collname, collnamespace).
+ PostgreSQL generally ignores all
+ collations that do not have collencoding equal to
+ either the current database's encoding or -1, and creation of new entries
+ with the same name as an entry with collencoding = -1
+ is forbidden. Therefore it is sufficient to use a qualified SQL name
+ (schema.name) to identify a collation,
+ even though this is not unique according to the catalog definition.
+ The reason for defining the catalog this way is that
+ initdb fills it in at cluster initialization time with
+ entries for all locales available on the system, so it must be able to
+ hold entries for all encodings that might ever be used in the cluster.
+
+ In the template0 database, it could be useful to create
+ collations whose encoding does not match the database encoding,
+ since they could match the encodings of databases later cloned from
+ template0. This would currently have to be done manually.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-constraint.html b/pgsql/doc/postgresql/html/catalog-pg-constraint.html
new file mode 100644
index 0000000000000000000000000000000000000000..87e1b126343bd61d9ff6bfc2dfae6653b583621e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-constraint.html
@@ -0,0 +1,206 @@
+
+53.13. pg_constraint
+ The catalog pg_constraint stores check, primary
+ key, unique, foreign key, and exclusion constraints on tables.
+ (Column constraints are not treated specially. Every column constraint is
+ equivalent to some table constraint.)
+ Not-null constraints are represented in the
+ pg_attribute
+ catalog, not here.
+
+ User-defined constraint triggers (created with
+ CREATE CONSTRAINT TRIGGER) also give rise to an entry in this table.
+
+ Check constraints on domains are stored here, too.
+
+ If a foreign key with a SET NULL or SET
+ DEFAULT delete action, the columns that will be updated.
+ If null, all of the referencing columns will be updated.
+
+ If an exclusion constraint, list of the per-column exclusion operators
+
+ conbinpg_node_tree
+
+
+ If a check constraint, an internal representation of the
+ expression. (It's recommended to use
+ pg_get_constraintdef() to extract the definition of
+ a check constraint.)
+
+ In the case of an exclusion constraint, conkey
+ is only useful for constraint elements that are simple column references.
+ For other cases, a zero appears in conkey
+ and the associated index must be consulted to discover the expression
+ that is constrained. (conkey thus has the
+ same contents as pg_index.indkey for the
+ index.)
+
Note
+ pg_class.relchecks needs to agree with the
+ number of check-constraint entries found in this table for each
+ relation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-conversion.html b/pgsql/doc/postgresql/html/catalog-pg-conversion.html
new file mode 100644
index 0000000000000000000000000000000000000000..5c8be3b650d32393f00b03f33327431fc0228a2b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-conversion.html
@@ -0,0 +1,56 @@
+
+53.14. pg_conversion
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-database.html b/pgsql/doc/postgresql/html/catalog-pg-database.html
new file mode 100644
index 0000000000000000000000000000000000000000..4ce4b63a229de65376b89f51b049391b8d90220c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-database.html
@@ -0,0 +1,129 @@
+
+53.15. pg_database
+ The catalog pg_database stores information about
+ the available databases. Databases are created with the CREATE DATABASE command.
+ Consult Chapter 23 for details about the meaning
+ of some of the parameters.
+
+ Unlike most system catalogs, pg_database
+ is shared across all databases of a cluster: there is only one
+ copy of pg_database per cluster, not
+ one per database.
+
+ Owner of the database, usually the user who created it
+
+ encodingint4
+
+
+ Character encoding for this database
+ (pg_encoding_to_char() can translate
+ this number to the encoding name)
+
+ datlocproviderchar
+
+
+ Locale provider for this database: c = libc,
+ i = icu
+
+ datistemplatebool
+
+
+ If true, then this database can be cloned by
+ any user with CREATEDB privileges;
+ if false, then only superusers or the owner of
+ the database can clone it.
+
+ datallowconnbool
+
+
+ If false then no one can connect to this database. This is
+ used to protect the template0 database from being altered.
+
+ datconnlimitint4
+
+
+ Sets maximum number of concurrent connections that can be made
+ to this database. -1 means no limit, -2 indicates the database is
+ invalid.
+
+ datfrozenxidxid
+
+
+ All transaction IDs before this one have been replaced with a permanent
+ (“frozen”) transaction ID in this database. This is used to
+ track whether the database needs to be vacuumed in order to prevent
+ transaction ID wraparound or to allow pg_xact to be shrunk.
+ It is the minimum of the per-table
+ pg_class.relfrozenxid values.
+
+ datminmxidxid
+
+
+ All multixact IDs before this one have been replaced with a
+ transaction ID in this database. This is used to
+ track whether the database needs to be vacuumed in order to prevent
+ multixact ID wraparound or to allow pg_multixact to be shrunk.
+ It is the minimum of the per-table
+ pg_class.relminmxid values.
+
+ The default tablespace for the database.
+ Within this database, all tables for which
+ pg_class.reltablespace is zero
+ will be stored in this tablespace; in particular, all the non-shared
+ system catalogs will be there.
+
+ datcollatetext
+
+
+ LC_COLLATE for this database
+
+ datctypetext
+
+
+ LC_CTYPE for this database
+
+ daticulocaletext
+
+
+ ICU locale ID for this database
+
+ daticurulestext
+
+
+ ICU collation rules for this database
+
+ datcollversiontext
+
+
+ Provider-specific version of the collation. This is recorded when the
+ database is created and then checked when it is used, to detect
+ changes in the collation definition that could lead to data corruption.
+
+ dataclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-db-role-setting.html b/pgsql/doc/postgresql/html/catalog-pg-db-role-setting.html
new file mode 100644
index 0000000000000000000000000000000000000000..883627297eaf8c63d1397f81507343c2ce951637
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-db-role-setting.html
@@ -0,0 +1,33 @@
+
+53.16. pg_db_role_setting
+ The catalog pg_db_role_setting records the default
+ values that have been set for run-time configuration variables,
+ for each role and database combination.
+
+ Unlike most system catalogs, pg_db_role_setting
+ is shared across all databases of a cluster: there is only one
+ copy of pg_db_role_setting per cluster, not
+ one per database.
+
+ The OID of the role the setting is applicable to, or zero if not role-specific
+
+ setconfigtext[]
+
+
+ Defaults for run-time configuration variables
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-default-acl.html b/pgsql/doc/postgresql/html/catalog-pg-default-acl.html
new file mode 100644
index 0000000000000000000000000000000000000000..96ee79b2425e17f65dbc759355941b5e2a78face
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-default-acl.html
@@ -0,0 +1,58 @@
+
+53.17. pg_default_acl
+ The OID of the namespace associated with this entry,
+ or zero if none
+
+ defaclobjtypechar
+
+
+ Type of object this entry is for:
+ r = relation (table, view),
+ S = sequence,
+ f = function,
+ T = type,
+ n = schema
+
+ defaclaclaclitem[]
+
+
+ Access privileges that this type of object should have on creation
+
+ A pg_default_acl entry shows the initial privileges to
+ be assigned to an object belonging to the indicated user. There are
+ currently two types of entry: “global” entries with
+ defaclnamespace = zero, and “per-schema” entries
+ that reference a particular schema. If a global entry is present then
+ it overrides the normal hard-wired default privileges
+ for the object type. A per-schema entry, if present, represents privileges
+ to be added to the global or hard-wired default privileges.
+
+ Note that when an ACL entry in another catalog is null, it is taken
+ to represent the hard-wired default privileges for its object,
+ not whatever might be in pg_default_acl
+ at the moment. pg_default_acl is only consulted during
+ object creation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-depend.html b/pgsql/doc/postgresql/html/catalog-pg-depend.html
new file mode 100644
index 0000000000000000000000000000000000000000..ddee28ffea9193f68f67c24aee0734473fcd18e8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-depend.html
@@ -0,0 +1,175 @@
+
+53.18. pg_depend
+ The catalog pg_depend records the dependency
+ relationships between database objects. This information allows
+ DROP commands to find which other objects must be dropped
+ by DROP CASCADE or prevent dropping in the DROP
+ RESTRICT case.
+
+ See also pg_shdepend,
+ which performs a similar function for dependencies involving objects
+ that are shared across a database cluster.
+
+ The OID of the system catalog the dependent object is in
+
+ objidoid
+ (references any OID column)
+
+
+ The OID of the specific dependent object
+
+ objsubidint4
+
+
+ For a table column, this is the column number (the
+ objid and classid refer to the
+ table itself). For all other object types, this column is
+ zero.
+
+ The OID of the system catalog the referenced object is in
+
+ refobjidoid
+ (references any OID column)
+
+
+ The OID of the specific referenced object
+
+ refobjsubidint4
+
+
+ For a table column, this is the column number (the
+ refobjid and refclassid refer
+ to the table itself). For all other object types, this column
+ is zero.
+
+ deptypechar
+
+
+ A code defining the specific semantics of this dependency relationship; see text
+
+ In all cases, a pg_depend entry indicates that the
+ referenced object cannot be dropped without also dropping the dependent
+ object. However, there are several subflavors identified by
+ deptype:
+
+
DEPENDENCY_NORMAL (n)
+ A normal relationship between separately-created objects. The
+ dependent object can be dropped without affecting the
+ referenced object. The referenced object can only be dropped
+ by specifying CASCADE, in which case the dependent
+ object is dropped, too. Example: a table column has a normal
+ dependency on its data type.
+
DEPENDENCY_AUTO (a)
+ The dependent object can be dropped separately from the
+ referenced object, and should be automatically dropped
+ (regardless of RESTRICT or CASCADE
+ mode) if the referenced object is dropped. Example: a named
+ constraint on a table is made auto-dependent on the table, so
+ that it will go away if the table is dropped.
+
DEPENDENCY_INTERNAL (i)
+ The dependent object was created as part of creation of the
+ referenced object, and is really just a part of its internal
+ implementation. A direct DROP of the dependent
+ object will be disallowed outright (we'll tell the user to issue
+ a DROP against the referenced object, instead).
+ A DROP of the referenced object will result in
+ automatically dropping the dependent object
+ whether CASCADE is specified or not. If the
+ dependent object has to be dropped due to a dependency on some other
+ object being removed, its drop is converted to a drop of the referenced
+ object, so that NORMAL and AUTO
+ dependencies of the dependent object behave much like they were
+ dependencies of the referenced object.
+ Example: a view's ON SELECT rule is made
+ internally dependent on the view, preventing it from being dropped
+ while the view remains. Dependencies of the rule (such as tables it
+ refers to) act as if they were dependencies of the view.
+
DEPENDENCY_PARTITION_PRI (P) DEPENDENCY_PARTITION_SEC (S)
+ The dependent object was created as part of creation of the
+ referenced object, and is really just a part of its internal
+ implementation; however, unlike INTERNAL,
+ there is more than one such referenced object. The dependent object
+ must not be dropped unless at least one of these referenced objects
+ is dropped; if any one is, the dependent object should be dropped
+ whether or not CASCADE is specified. Also
+ unlike INTERNAL, a drop of some other object
+ that the dependent object depends on does not result in automatic
+ deletion of any partition-referenced object. Hence, if the drop
+ does not cascade to at least one of these objects via some other
+ path, it will be refused. (In most cases, the dependent object
+ shares all its non-partition dependencies with at least one
+ partition-referenced object, so that this restriction does not
+ result in blocking any cascaded delete.)
+ Primary and secondary partition dependencies behave identically
+ except that the primary dependency is preferred for use in error
+ messages; hence, a partition-dependent object should have one
+ primary partition dependency and one or more secondary partition
+ dependencies.
+ Note that partition dependencies are made in addition to, not
+ instead of, any dependencies the object would normally have. This
+ simplifies ATTACH/DETACH PARTITION operations:
+ the partition dependencies need only be added or removed.
+ Example: a child partitioned index is made partition-dependent
+ on both the partition table it is on and the parent partitioned
+ index, so that it goes away if either of those is dropped, but
+ not otherwise. The dependency on the parent index is primary,
+ so that if the user tries to drop the child partitioned index,
+ the error message will suggest dropping the parent index instead
+ (not the table).
+
DEPENDENCY_EXTENSION (e)
+ The dependent object is a member of the extension that is
+ the referenced object (see
+ pg_extension).
+ The dependent object can be dropped only via
+ DROP EXTENSION on the referenced object.
+ Functionally this dependency type acts the same as
+ an INTERNAL dependency, but it's kept separate for
+ clarity and to simplify pg_dump.
+
DEPENDENCY_AUTO_EXTENSION (x)
+ The dependent object is not a member of the extension that is the
+ referenced object (and so it should not be ignored
+ by pg_dump), but it cannot function
+ without the extension and should be auto-dropped if the extension is.
+ The dependent object may be dropped on its own as well.
+ Functionally this dependency type acts the same as
+ an AUTO dependency, but it's kept separate for
+ clarity and to simplify pg_dump.
+
+
+ Other dependency flavors might be needed in future.
+
+ Note that it's quite possible for two objects to be linked by more than
+ one pg_depend entry. For example, a child
+ partitioned index would have both a partition-type dependency on its
+ associated partition table, and an auto dependency on each column of
+ that table that it indexes. This sort of situation expresses the union
+ of multiple dependency semantics. A dependent object can be dropped
+ without CASCADE if any of its dependencies satisfies
+ its condition for automatic dropping. Conversely, all the
+ dependencies' restrictions about which objects must be dropped together
+ must be satisfied.
+
+ Most objects created during initdb are
+ considered “pinned”, which means that the system itself
+ depends on them. Therefore, they are never allowed to be dropped.
+ Also, knowing that pinned objects will not be dropped, the dependency
+ mechanism doesn't bother to make pg_depend
+ entries showing dependencies on them. Thus, for example, a table
+ column of type numeric notionally has
+ a NORMAL dependency on the numeric
+ data type, but no such entry actually appears
+ in pg_depend.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-description.html b/pgsql/doc/postgresql/html/catalog-pg-description.html
new file mode 100644
index 0000000000000000000000000000000000000000..5e62efd1afbf5ab1bab61966c8d492d431aaea82
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-description.html
@@ -0,0 +1,43 @@
+
+53.19. pg_description
+ The catalog pg_description stores optional descriptions
+ (comments) for each database object. Descriptions can be manipulated
+ with the COMMENT command and viewed with
+ psql's \d commands.
+ Descriptions of many built-in system objects are provided in the initial
+ contents of pg_description.
+
+ See also pg_shdescription,
+ which performs a similar function for descriptions involving objects that
+ are shared across a database cluster.
+
Table 53.19. pg_description Columns
+ Column Type
+
+
+ Description
+
+ objoidoid
+ (references any OID column)
+
+
+ The OID of the object this description pertains to
+
+ The OID of the system catalog this object appears in
+
+ objsubidint4
+
+
+ For a comment on a table column, this is the column number (the
+ objoid and classoid refer to
+ the table itself). For all other object types, this column is
+ zero.
+
+ descriptiontext
+
+
+ Arbitrary text that serves as the description of this object
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-enum.html b/pgsql/doc/postgresql/html/catalog-pg-enum.html
new file mode 100644
index 0000000000000000000000000000000000000000..2949b11a355d6a23fad5ebfc2cb79f7f713a997c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-enum.html
@@ -0,0 +1,49 @@
+
+53.20. pg_enum
+ The pg_enum catalog contains entries
+ showing the values and labels for each enum type. The
+ internal representation of a given enum value is actually the OID
+ of its associated row in pg_enum.
+
+ The OID of the pg_type entry owning this enum value
+
+ enumsortorderfloat4
+
+
+ The sort position of this enum value within its enum type
+
+ enumlabelname
+
+
+ The textual label for this enum value
+
+ The OIDs for pg_enum rows follow a special
+ rule: even-numbered OIDs are guaranteed to be ordered in the same way
+ as the sort ordering of their enum type. That is, if two even OIDs
+ belong to the same enum type, the smaller OID must have the smaller
+ enumsortorder value. Odd-numbered OID values
+ need bear no relationship to the sort order. This rule allows the
+ enum comparison routines to avoid catalog lookups in many common cases.
+ The routines that create and alter enum types attempt to assign even
+ OIDs to enum values whenever possible.
+
+ When an enum type is created, its members are assigned sort-order
+ positions 1..n. But members added later might be given
+ negative or fractional values of enumsortorder.
+ The only requirement on these values is that they be correctly
+ ordered and unique within each enum type.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-event-trigger.html b/pgsql/doc/postgresql/html/catalog-pg-event-trigger.html
new file mode 100644
index 0000000000000000000000000000000000000000..cc1dbac80a6c9dcec21c8dc787344b78caac0cf4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-event-trigger.html
@@ -0,0 +1,53 @@
+
+53.21. pg_event_trigger
+ Controls in which session_replication_role modes
+ the event trigger fires.
+ O = trigger fires in “origin” and “local” modes,
+ D = trigger is disabled,
+ R = trigger fires in “replica” mode,
+ A = trigger fires always.
+
+ evttagstext[]
+
+
+ Command tags for which this trigger will fire. If NULL, the firing
+ of this trigger is not restricted on the basis of the command tag.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-extension.html b/pgsql/doc/postgresql/html/catalog-pg-extension.html
new file mode 100644
index 0000000000000000000000000000000000000000..e1e68df7d700e76ea404b1500f649e473a1d07e2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-extension.html
@@ -0,0 +1,65 @@
+
+53.22. pg_extension
+ Array of regclass OIDs for the extension's configuration
+ table(s), or NULL if none
+
+ extconditiontext[]
+
+
+ Array of WHERE-clause filter conditions for the
+ extension's configuration table(s), or NULL if none
+
+ Note that unlike most catalogs with a “namespace” column,
+ extnamespace is not meant to imply
+ that the extension belongs to that schema. Extension names are never
+ schema-qualified. Rather, extnamespace
+ indicates the schema that contains most or all of the extension's
+ objects. If extrelocatable is true, then
+ this schema must in fact contain all schema-qualifiable objects
+ belonging to the extension.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-foreign-data-wrapper.html b/pgsql/doc/postgresql/html/catalog-pg-foreign-data-wrapper.html
new file mode 100644
index 0000000000000000000000000000000000000000..3c7b701935dc0f05d788469225c8ab0240e8d0b5
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-foreign-data-wrapper.html
@@ -0,0 +1,56 @@
+
+53.23. pg_foreign_data_wrapper
+ The catalog pg_foreign_data_wrapper stores
+ foreign-data wrapper definitions. A foreign-data wrapper is the
+ mechanism by which external data, residing on foreign servers, is
+ accessed.
+
+ References a handler function that is responsible for
+ supplying execution routines for the foreign-data wrapper.
+ Zero if no handler is provided
+
+ References a validator function that is responsible for
+ checking the validity of the options given to the
+ foreign-data wrapper, as well as options for foreign servers and user
+ mappings using the foreign-data wrapper. Zero if no validator
+ is provided
+
+ fdwaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
+ fdwoptionstext[]
+
+
+ Foreign-data wrapper specific options, as “keyword=value” strings
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-foreign-server.html b/pgsql/doc/postgresql/html/catalog-pg-foreign-server.html
new file mode 100644
index 0000000000000000000000000000000000000000..6d225ce26e6c37b3fa4a7f34aa1b2890c3bfc63f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-foreign-server.html
@@ -0,0 +1,54 @@
+
+53.24. pg_foreign_server
+ The catalog pg_foreign_server stores
+ foreign server definitions. A foreign server describes a source
+ of external data, such as a remote server. Foreign
+ servers are accessed via foreign-data wrappers.
+
+ OID of the foreign-data wrapper of this foreign server
+
+ srvtypetext
+
+
+ Type of the server (optional)
+
+ srvversiontext
+
+
+ Version of the server (optional)
+
+ srvaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
+ srvoptionstext[]
+
+
+ Foreign server specific options, as “keyword=value” strings
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-foreign-table.html b/pgsql/doc/postgresql/html/catalog-pg-foreign-table.html
new file mode 100644
index 0000000000000000000000000000000000000000..99c6b92e73c93aede76fee0587f7ae2c37086b58
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-foreign-table.html
@@ -0,0 +1,32 @@
+
+53.25. pg_foreign_table
+ The catalog pg_foreign_table contains
+ auxiliary information about foreign tables. A foreign table is
+ primarily represented by a
+ pg_class
+ entry, just like a regular table. Its pg_foreign_table
+ entry contains the information that is pertinent only to foreign tables
+ and not any other kind of relation.
+
+ OID of the foreign server for this foreign table
+
+ ftoptionstext[]
+
+
+ Foreign table options, as “keyword=value” strings
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-index.html b/pgsql/doc/postgresql/html/catalog-pg-index.html
new file mode 100644
index 0000000000000000000000000000000000000000..492e2acb8046ac0a4730df365793408a1b83b139
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-index.html
@@ -0,0 +1,163 @@
+
+53.26. pg_index
+ The OID of the pg_class entry for the table this index is for
+
+ indnattsint2
+
+
+ The total number of columns in the index (duplicates
+ pg_class.relnatts); this number includes both key and included attributes
+
+ indnkeyattsint2
+
+
+ The number of key columns in the index,
+ not counting any included columns, which are
+ merely stored and do not participate in the index semantics
+
+ indisuniquebool
+
+
+ If true, this is a unique index
+
+ indnullsnotdistinctbool
+
+
+ This value is only used for unique indexes. If false, this unique
+ index will consider null values distinct (so the index can contain
+ multiple null values in a column, the default PostgreSQL behavior). If
+ it is true, it will consider null values to be equal (so the index can
+ only contain one null value in a column).
+
+ indisprimarybool
+
+
+ If true, this index represents the primary key of the table
+ (indisunique should always be true when this is true)
+
+ indisexclusionbool
+
+
+ If true, this index supports an exclusion constraint
+
+ indimmediatebool
+
+
+ If true, the uniqueness check is enforced immediately on
+ insertion
+ (irrelevant if indisunique is not true)
+
+ indisclusteredbool
+
+
+ If true, the table was last clustered on this index
+
+ indisvalidbool
+
+
+ If true, the index is currently valid for queries. False means the
+ index is possibly incomplete: it must still be modified by
+ INSERT/UPDATE operations, but it cannot safely
+ be used for queries. If it is unique, the uniqueness property is not
+ guaranteed true either.
+
+ indcheckxminbool
+
+
+ If true, queries must not use the index until the xmin
+ of this pg_index row is below their TransactionXmin
+ event horizon, because the table may contain broken HOT chains with
+ incompatible rows that they can see
+
+ indisreadybool
+
+
+ If true, the index is currently ready for inserts. False means the
+ index must be ignored by INSERT/UPDATE
+ operations.
+
+ indislivebool
+
+
+ If false, the index is in process of being dropped, and should be
+ ignored for all purposes (including HOT-safety decisions)
+
+ This is an array of indnatts values that
+ indicate which table columns this index indexes. For example, a value
+ of 1 3 would mean that the first and the third table
+ columns make up the index entries. Key columns come before non-key
+ (included) columns. A zero in this array indicates that the
+ corresponding index attribute is an expression over the table columns,
+ rather than a simple column reference.
+
+ For each column in the index key
+ (indnkeyatts values), this contains the OID
+ of the collation to use for the index, or zero if the column is not of
+ a collatable data type.
+
+ For each column in the index key
+ (indnkeyatts values), this contains the OID
+ of the operator class to use. See
+ pg_opclass for details.
+
+ indoptionint2vector
+
+
+ This is an array of indnkeyatts values that
+ store per-column flag bits. The meaning of the bits is defined by
+ the index's access method.
+
+ indexprspg_node_tree
+
+
+ Expression trees (in nodeToString()
+ representation) for index attributes that are not simple column
+ references. This is a list with one element for each zero
+ entry in indkey. Null if all index attributes
+ are simple references.
+
+ indpredpg_node_tree
+
+
+ Expression tree (in nodeToString()
+ representation) for partial index predicate. Null if not a
+ partial index.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-inherits.html b/pgsql/doc/postgresql/html/catalog-pg-inherits.html
new file mode 100644
index 0000000000000000000000000000000000000000..b5630a0cdb8e9b220d2a589b19a14fce7f392853
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-inherits.html
@@ -0,0 +1,41 @@
+
+53.27. pg_inherits
+ The catalog pg_inherits records information about
+ table and index inheritance hierarchies. There is one entry for each direct
+ parent-child table or index relationship in the database. (Indirect
+ inheritance can be determined by following chains of entries.)
+
+ If there is more than one direct parent for a child table (multiple
+ inheritance), this number tells the order in which the
+ inherited columns are to be arranged. The count starts at 1.
+
+
+ Indexes cannot have multiple inheritance, since they can only inherit
+ when using declarative partitioning.
+
+ inhdetachpendingbool
+
+
+ true for a partition that is in the process of
+ being detached; false otherwise.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-init-privs.html b/pgsql/doc/postgresql/html/catalog-pg-init-privs.html
new file mode 100644
index 0000000000000000000000000000000000000000..a9c35d67f8887b114d7cb0f245939416f287e6bd
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-init-privs.html
@@ -0,0 +1,61 @@
+
+53.28. pg_init_privs
+ The catalog pg_init_privs records information about
+ the initial privileges of objects in the system. There is one entry
+ for each object in the database which has a non-default (non-NULL)
+ initial set of privileges.
+
+ Objects can have initial privileges either by having those privileges set
+ when the system is initialized (by initdb) or when the
+ object is created during a CREATE EXTENSION and the
+ extension script sets initial privileges using the GRANT
+ system. Note that the system will automatically handle recording of the
+ privileges during the extension script and that extension authors need
+ only use the GRANT and REVOKE
+ statements in their script to have the privileges recorded. The
+ privtype column indicates if the initial privilege was
+ set by initdb or during a
+ CREATE EXTENSION command.
+
+ Objects which have initial privileges set by initdb will
+ have entries where privtype is
+ 'i', while objects which have initial privileges set
+ by CREATE EXTENSION will have entries where
+ privtype is 'e'.
+
+ The OID of the system catalog the object is in
+
+ objsubidint4
+
+
+ For a table column, this is the column number (the
+ objoid and classoid refer to the
+ table itself). For all other object types, this column is
+ zero.
+
+ privtypechar
+
+
+ A code defining the type of initial privilege of this object; see text
+
+ initprivsaclitem[]
+
+
+ The initial access privileges; see
+ Section 5.7 for details
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-language.html b/pgsql/doc/postgresql/html/catalog-pg-language.html
new file mode 100644
index 0000000000000000000000000000000000000000..9b40ea2282d61bce67c20ee60e34d8d7de274e6b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-language.html
@@ -0,0 +1,76 @@
+
+53.29. pg_language
+ The catalog pg_language registers
+ languages in which you can write functions or stored procedures.
+ See CREATE LANGUAGE
+ and Chapter 42 for more information about language handlers.
+
+ This is false for internal languages (such as
+ SQL) and true for user-defined languages.
+ Currently, pg_dump still uses this
+ to determine which languages need to be dumped, but this might be
+ replaced by a different mechanism in the future.
+
+ lanpltrustedbool
+
+
+ True if this is a trusted language, which means that it is believed
+ not to grant access to anything outside the normal SQL execution
+ environment. Only superusers can create functions in untrusted
+ languages.
+
+ For noninternal languages this references the language
+ handler, which is a special function that is responsible for
+ executing all functions that are written in the particular
+ language. Zero for internal languages.
+
+ This references a function that is responsible for executing
+ “inline” anonymous code blocks
+ (DO blocks).
+ Zero if inline blocks are not supported.
+
+ This references a language validator function that is responsible
+ for checking the syntax and validity of new functions when they
+ are created. Zero if no validator is provided.
+
+ lanaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-largeobject-metadata.html b/pgsql/doc/postgresql/html/catalog-pg-largeobject-metadata.html
new file mode 100644
index 0000000000000000000000000000000000000000..ad9c8aba8061ba01242539ea6c722c3b01f3b931
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-largeobject-metadata.html
@@ -0,0 +1,28 @@
+
+53.31. pg_largeobject_metadata
+ Access privileges; see Section 5.7 for details
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-largeobject.html b/pgsql/doc/postgresql/html/catalog-pg-largeobject.html
new file mode 100644
index 0000000000000000000000000000000000000000..dc6681a54282fd0a51ee6dff1cf0b9294184dbfa
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-largeobject.html
@@ -0,0 +1,48 @@
+
+53.30. pg_largeobject
+ The catalog pg_largeobject holds the data making up
+ “large objects”. A large object is identified by an OID
+ assigned when it is created. Each large object is broken into
+ segments or “pages” small enough to be conveniently stored as rows
+ in pg_largeobject.
+ The amount of data per page is defined to be LOBLKSIZE (which is currently
+ BLCKSZ/4, or typically 2 kB).
+
+ Prior to PostgreSQL 9.0, there was no permission structure
+ associated with large objects. As a result,
+ pg_largeobject was publicly readable and could be
+ used to obtain the OIDs (and contents) of all large objects in the system.
+ This is no longer the case; use
+ pg_largeobject_metadata
+ to obtain a list of large object OIDs.
+
+ Identifier of the large object that includes this page
+
+ pagenoint4
+
+
+ Page number of this page within its large object
+ (counting from zero)
+
+ databytea
+
+
+ Actual data stored in the large object.
+ This will never be more than LOBLKSIZE bytes and might be less.
+
+ Each row of pg_largeobject holds data
+ for one page of a large object, beginning at
+ byte offset (pageno * LOBLKSIZE) within the object. The implementation
+ allows sparse storage: pages might be missing, and might be shorter than
+ LOBLKSIZE bytes even if they are not the last page of the object.
+ Missing regions within a large object read as zeroes.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-namespace.html b/pgsql/doc/postgresql/html/catalog-pg-namespace.html
new file mode 100644
index 0000000000000000000000000000000000000000..c1ff1e1472e93aa659a586ad0712945e7fe11679
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-namespace.html
@@ -0,0 +1,33 @@
+
+53.32. pg_namespace
+ The catalog pg_namespace stores namespaces.
+ A namespace is the structure underlying SQL schemas: each namespace
+ can have a separate collection of relations, types, etc. without name
+ conflicts.
+
+ Access privileges; see Section 5.7 for details
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-opclass.html b/pgsql/doc/postgresql/html/catalog-pg-opclass.html
new file mode 100644
index 0000000000000000000000000000000000000000..321ea2f33a15f2efc4b5f870fae3b7f95142ef46
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-opclass.html
@@ -0,0 +1,75 @@
+
+53.33. pg_opclass
+ The catalog pg_opclass defines
+ index access method operator classes. Each operator class defines
+ semantics for index columns of a particular data type and a particular
+ index access method. An operator class essentially specifies that a
+ particular operator family is applicable to a particular indexable column
+ data type. The set of operators from the family that are actually usable
+ with the indexed column are whichever ones accept the column's data type
+ as their left-hand input.
+
+ Operator classes are described at length in Section 38.16.
+
+ Type of data stored in index, or zero if same as opcintype
+
+ An operator class's opcmethod must match the
+ opfmethod of its containing operator family.
+ Also, there must be no more than one pg_opclass
+ row having opcdefault true for any given combination of
+ opcmethod and opcintype.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-operator.html b/pgsql/doc/postgresql/html/catalog-pg-operator.html
new file mode 100644
index 0000000000000000000000000000000000000000..c34d9731c01bf8407c514d960e6c6d07f8680a41
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-operator.html
@@ -0,0 +1,101 @@
+
+53.34. pg_operator
+ Join selectivity estimation function for this operator
+ (zero if none)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-opfamily.html b/pgsql/doc/postgresql/html/catalog-pg-opfamily.html
new file mode 100644
index 0000000000000000000000000000000000000000..f50b5f8deefb605a5e2ab50b1a19464218698eae
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-opfamily.html
@@ -0,0 +1,53 @@
+
+53.35. pg_opfamily
+ The catalog pg_opfamily defines operator families.
+ Each operator family is a collection of operators and associated
+ support routines that implement the semantics specified for a particular
+ index access method. Furthermore, the operators in a family are all
+ “compatible”, in a way that is specified by the access method.
+ The operator family concept allows cross-data-type operators to be used
+ with indexes and to be reasoned about using knowledge of access method
+ semantics.
+
+ Operator families are described at length in Section 38.16.
+
+ The majority of the information defining an operator family is not in its
+ pg_opfamily row, but in the associated rows in
+ pg_amop,
+ pg_amproc,
+ and
+ pg_opclass.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-parameter-acl.html b/pgsql/doc/postgresql/html/catalog-pg-parameter-acl.html
new file mode 100644
index 0000000000000000000000000000000000000000..91e17d5ccfc2434655f5af28b903605db5517842
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-parameter-acl.html
@@ -0,0 +1,31 @@
+
+53.36. pg_parameter_acl
+ The catalog pg_parameter_acl records configuration
+ parameters for which privileges have been granted to one or more roles.
+ No entry is made for parameters that have default privileges.
+
+ Unlike most system catalogs, pg_parameter_acl
+ is shared across all databases of a cluster: there is only one
+ copy of pg_parameter_acl per cluster, not
+ one per database.
+
Table 53.36. pg_parameter_acl Columns
+ Column Type
+
+
+ Description
+
+ oidoid
+
+
+ Row identifier
+
+ parnametext
+
+
+ The name of a configuration parameter for which privileges are granted
+
+ paraclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-partitioned-table.html b/pgsql/doc/postgresql/html/catalog-pg-partitioned-table.html
new file mode 100644
index 0000000000000000000000000000000000000000..75a09adcf92adf62a0db078c428e173f2b40cd88
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-partitioned-table.html
@@ -0,0 +1,71 @@
+
+53.37. pg_partitioned_table
+ The OID of the pg_class entry for the default partition
+ of this partitioned table, or zero if this partitioned table does not
+ have a default partition
+
+ This is an array of partnatts values that
+ indicate which table columns are part of the partition key. For
+ example, a value of 1 3 would mean that the first
+ and the third table columns make up the partition key. A zero in this
+ array indicates that the corresponding partition key column is an
+ expression, rather than a simple column reference.
+
+ For each column in the partition key, this contains the OID of the
+ collation to use for partitioning, or zero if the column is not
+ of a collatable data type.
+
+ partexprspg_node_tree
+
+
+ Expression trees (in nodeToString()
+ representation) for partition key columns that are not simple column
+ references. This is a list with one element for each zero
+ entry in partattrs. Null if all partition key columns
+ are simple references.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-policy.html b/pgsql/doc/postgresql/html/catalog-pg-policy.html
new file mode 100644
index 0000000000000000000000000000000000000000..b4ca18c3d9e3e6bbaab285245c5caea4f13b7592
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-policy.html
@@ -0,0 +1,68 @@
+
+53.38. pg_policy
+ The catalog pg_policy stores row-level
+ security policies for tables. A policy includes the kind of
+ command that it applies to (possibly all commands), the roles that it
+ applies to, the expression to be added as a security-barrier
+ qualification to queries that include the table, and the expression
+ to be added as a WITH CHECK option for queries that attempt to
+ add new records to the table.
+
+ The roles to which the policy is applied;
+ zero means PUBLIC
+ (and normally appears alone in the array)
+
+ polqualpg_node_tree
+
+
+ The expression tree to be added to the security barrier qualifications for queries that use the table
+
+ polwithcheckpg_node_tree
+
+
+ The expression tree to be added to the WITH CHECK qualifications for queries that attempt to add rows to the table
+
Note
+ Policies stored in pg_policy are applied only when
+ pg_class.relrowsecurity is set for
+ their table.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-proc.html b/pgsql/doc/postgresql/html/catalog-pg-proc.html
new file mode 100644
index 0000000000000000000000000000000000000000..c5b180750d503268495178009f0d1f0b5092fa9f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-proc.html
@@ -0,0 +1,256 @@
+
+53.39. pg_proc
+ The catalog pg_proc stores information about
+ functions, procedures, aggregate functions, and window functions
+ (collectively also known as routines). See CREATE FUNCTION, CREATE PROCEDURE, and
+ Section 38.3 for more information.
+
+ If prokind indicates that the entry is for an
+ aggregate function, there should be a matching row in
+ pg_aggregate.
+
+ Planner support function for this function
+ (see Section 38.11), or zero if none
+
+ prokindchar
+
+
+ f for a normal function, p
+ for a procedure, a for an aggregate function, or
+ w for a window function
+
+ prosecdefbool
+
+
+ Function is a security definer (i.e., a “setuid”
+ function)
+
+ proleakproofbool
+
+
+ The function has no side effects. No information about the
+ arguments is conveyed except via the return value. Any function
+ that might throw an error depending on the values of its arguments
+ is not leak-proof.
+
+ proisstrictbool
+
+
+ Function returns null if any call argument is null. In that
+ case the function won't actually be called at all. Functions
+ that are not “strict” must be prepared to handle
+ null inputs.
+
+ proretsetbool
+
+
+ Function returns a set (i.e., multiple values of the specified
+ data type)
+
+ provolatilechar
+
+
+ provolatile tells whether the function's
+ result depends only on its input arguments, or is affected by outside
+ factors.
+ It is i for “immutable” functions,
+ which always deliver the same result for the same inputs.
+ It is s for “stable” functions,
+ whose results (for fixed inputs) do not change within a scan.
+ It is v for “volatile” functions,
+ whose results might change at any time. (Use v also
+ for functions with side-effects, so that calls to them cannot get
+ optimized away.)
+
+ proparallelchar
+
+
+ proparallel tells whether the function
+ can be safely run in parallel mode.
+ It is s for functions which are safe to run in
+ parallel mode without restriction.
+ It is r for functions which can be run in parallel
+ mode, but their execution is restricted to the parallel group leader;
+ parallel worker processes cannot invoke these functions.
+ It is u for functions which are unsafe in parallel
+ mode; the presence of such a function forces a serial execution plan.
+
+ An array of the data types of the function arguments. This includes
+ only input arguments (including INOUT and
+ VARIADIC arguments), and thus represents
+ the call signature of the function.
+
+ An array of the data types of the function arguments. This includes
+ all arguments (including OUT and
+ INOUT arguments); however, if all the
+ arguments are IN arguments, this field will be null.
+ Note that subscripting is 1-based, whereas for historical reasons
+ proargtypes is subscripted from 0.
+
+ proargmodeschar[]
+
+
+ An array of the modes of the function arguments, encoded as
+ i for IN arguments,
+ o for OUT arguments,
+ b for INOUT arguments,
+ v for VARIADIC arguments,
+ t for TABLE arguments.
+ If all the arguments are IN arguments,
+ this field will be null.
+ Note that subscripts correspond to positions of
+ proallargtypes not proargtypes.
+
+ proargnamestext[]
+
+
+ An array of the names of the function arguments.
+ Arguments without a name are set to empty strings in the array.
+ If none of the arguments have a name, this field will be null.
+ Note that subscripts correspond to positions of
+ proallargtypes not proargtypes.
+
+ proargdefaultspg_node_tree
+
+
+ Expression trees (in nodeToString() representation)
+ for default values. This is a list with
+ pronargdefaults elements, corresponding to the last
+ Ninput arguments (i.e., the last
+ Nproargtypes positions).
+ If none of the arguments have defaults, this field will be null.
+
+ An array of the argument/result data type(s) for which to apply
+ transforms (from the function's TRANSFORM
+ clause). Null if none.
+
+ prosrctext
+
+
+ This tells the function handler how to invoke the function. It
+ might be the actual source code of the function for interpreted
+ languages, a link symbol, a file name, or just about anything
+ else, depending on the implementation language/call convention.
+
+ probintext
+
+
+ Additional information about how to invoke the function.
+ Again, the interpretation is language-specific.
+
+ prosqlbodypg_node_tree
+
+
+ Pre-parsed SQL function body. This is used for SQL-language
+ functions when the body is given in SQL-standard notation
+ rather than as a string literal. It's null in other cases.
+
+ proconfigtext[]
+
+
+ Function's local settings for run-time configuration variables
+
+ proaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
+ For compiled functions, both built-in and dynamically loaded,
+ prosrc contains the function's C-language
+ name (link symbol).
+ For SQL-language functions, prosrc contains
+ the function's source text if that is specified as a string literal;
+ but if the function body is specified in SQL-standard style,
+ prosrc is unused (typically it's an empty
+ string) and prosqlbody contains the
+ pre-parsed definition.
+ For all other currently-known language types,
+ prosrc contains the function's source
+ text. probin is null except for
+ dynamically-loaded C functions, for which it gives the name of the
+ shared library file containing the function.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-publication-namespace.html b/pgsql/doc/postgresql/html/catalog-pg-publication-namespace.html
new file mode 100644
index 0000000000000000000000000000000000000000..87e840063e64c771d54f39a20bf9fe453f50c275
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-publication-namespace.html
@@ -0,0 +1,28 @@
+
+53.41. pg_publication_namespace
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-publication-rel.html b/pgsql/doc/postgresql/html/catalog-pg-publication-rel.html
new file mode 100644
index 0000000000000000000000000000000000000000..5025d12faaeb7cf2ff1f1c38936943abe65af520
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-publication-rel.html
@@ -0,0 +1,43 @@
+
+53.42. pg_publication_rel
+ The catalog pg_publication_rel contains the
+ mapping between relations and publications in the database. This is a
+ many-to-many mapping. See also Section 54.17
+ for a more user-friendly view of this information.
+
Expression tree (in nodeToString()
+ representation) for the relation's publication qualifying condition. Null
+ if there is no publication qualifying condition.
+ This is an array of values that indicates which table columns are
+ part of the publication. For example, a value of 1 3
+ would mean that the first and the third table columns are published.
+ A null value indicates that all columns are published.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-publication.html b/pgsql/doc/postgresql/html/catalog-pg-publication.html
new file mode 100644
index 0000000000000000000000000000000000000000..7edd5eab889a74184cbed8ade052e2072ce0ac25
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-publication.html
@@ -0,0 +1,64 @@
+
+53.40. pg_publication
+ If true, this publication automatically includes all tables
+ in the database, including any that will be created in the future.
+
+ pubinsertbool
+
+
+ If true, INSERT operations are replicated for
+ tables in the publication.
+
+ pubupdatebool
+
+
+ If true, UPDATE operations are replicated for
+ tables in the publication.
+
+ pubdeletebool
+
+
+ If true, DELETE operations are replicated for
+ tables in the publication.
+
+ pubtruncatebool
+
+
+ If true, TRUNCATE operations are replicated for
+ tables in the publication.
+
+ pubviarootbool
+
+
+ If true, operations on a leaf partition are replicated using the
+ identity and schema of its topmost partitioned ancestor mentioned in the
+ publication instead of its own.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-range.html b/pgsql/doc/postgresql/html/catalog-pg-range.html
new file mode 100644
index 0000000000000000000000000000000000000000..b9aa03728d5f36abd5a733caa3d679bc5326b83a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-range.html
@@ -0,0 +1,61 @@
+
+53.43. pg_range
+ OID of the function to return the difference between two element
+ values as double precision, or zero if none
+
+ rngsubopc (plus rngcollation, if the
+ element type is collatable) determines the sort ordering used by the range
+ type. rngcanonical is used when the element type is
+ discrete. rngsubdiff is optional but should be supplied to
+ improve performance of GiST indexes on the range type.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-replication-origin.html b/pgsql/doc/postgresql/html/catalog-pg-replication-origin.html
new file mode 100644
index 0000000000000000000000000000000000000000..4c79ecaed82b5a26c9cfb7dd129535e29a5efee6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-replication-origin.html
@@ -0,0 +1,28 @@
+
+53.44. pg_replication_origin
+ The pg_replication_origin catalog contains
+ all replication origins created. For more on replication origins
+ see Chapter 50.
+
+ Unlike most system catalogs, pg_replication_origin
+ is shared across all databases of a cluster: there is only one copy
+ of pg_replication_origin per cluster, not one per
+ database.
+
Table 53.44. pg_replication_origin Columns
+ Column Type
+
+
+ Description
+
+ roidentoid
+
+
+ A unique, cluster-wide identifier for the replication
+ origin. Should never leave the system.
+
+ ronametext
+
+
+ The external, user defined, name of a replication
+ origin.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-rewrite.html b/pgsql/doc/postgresql/html/catalog-pg-rewrite.html
new file mode 100644
index 0000000000000000000000000000000000000000..40e29b9bdbc4235c321f99a3e1d3a013ef95bf74
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-rewrite.html
@@ -0,0 +1,64 @@
+
+53.45. pg_rewrite
+ Controls in which session_replication_role modes
+ the rule fires.
+ O = rule fires in “origin” and “local” modes,
+ D = rule is disabled,
+ R = rule fires in “replica” mode,
+ A = rule fires always.
+
+ is_insteadbool
+
+
+ True if the rule is an INSTEAD rule
+
+ ev_qualpg_node_tree
+
+
+ Expression tree (in the form of a
+ nodeToString() representation) for the
+ rule's qualifying condition
+
+ ev_actionpg_node_tree
+
+
+ Query tree (in the form of a
+ nodeToString() representation) for the
+ rule's action
+
Note
+ pg_class.relhasrules
+ must be true if a table has any rules in this catalog.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-seclabel.html b/pgsql/doc/postgresql/html/catalog-pg-seclabel.html
new file mode 100644
index 0000000000000000000000000000000000000000..77b5fcf7ee9459225bc900d0ff935db6fc561b14
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-seclabel.html
@@ -0,0 +1,46 @@
+
+53.46. pg_seclabel
+ The catalog pg_seclabel stores security
+ labels on database objects. Security labels can be manipulated
+ with the SECURITY LABEL command. For an easier
+ way to view security labels, see Section 54.22.
+
+ See also pg_shseclabel,
+ which performs a similar function for security labels of database objects
+ that are shared across a database cluster.
+
Table 53.46. pg_seclabel Columns
+ Column Type
+
+
+ Description
+
+ objoidoid
+ (references any OID column)
+
+
+ The OID of the object this security label pertains to
+
+ The OID of the system catalog this object appears in
+
+ objsubidint4
+
+
+ For a security label on a table column, this is the column number (the
+ objoid and classoid refer to
+ the table itself). For all other object types, this column is
+ zero.
+
+ providertext
+
+
+ The label provider associated with this label.
+
+ labeltext
+
+
+ The security label applied to this object.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-sequence.html b/pgsql/doc/postgresql/html/catalog-pg-sequence.html
new file mode 100644
index 0000000000000000000000000000000000000000..17d9647904cb8d0238c38da383a9feb18e0e4abe
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-sequence.html
@@ -0,0 +1,54 @@
+
+53.47. pg_sequence
+ The catalog pg_sequence contains information about
+ sequences. Some of the information about sequences, such as the name and
+ the schema, is in
+ pg_class
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-shdepend.html b/pgsql/doc/postgresql/html/catalog-pg-shdepend.html
new file mode 100644
index 0000000000000000000000000000000000000000..3264e47035efae38bf05b94d881cdc6744e2ba21
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-shdepend.html
@@ -0,0 +1,98 @@
+
+53.48. pg_shdepend
+ The catalog pg_shdepend records the
+ dependency relationships between database objects and shared objects,
+ such as roles. This information allows
+ PostgreSQL to ensure that those objects are
+ unreferenced before attempting to delete them.
+
+ See also pg_depend,
+ which performs a similar function for dependencies involving objects
+ within a single database.
+
+ Unlike most system catalogs, pg_shdepend
+ is shared across all databases of a cluster: there is only one
+ copy of pg_shdepend per cluster, not
+ one per database.
+
+ The OID of the system catalog the dependent object is in
+
+ objidoid
+ (references any OID column)
+
+
+ The OID of the specific dependent object
+
+ objsubidint4
+
+
+ For a table column, this is the column number (the
+ objid and classid refer to the
+ table itself). For all other object types, this column is zero.
+
+ The OID of the system catalog the referenced object is in
+ (must be a shared catalog)
+
+ refobjidoid
+ (references any OID column)
+
+
+ The OID of the specific referenced object
+
+ deptypechar
+
+
+ A code defining the specific semantics of this dependency relationship; see text
+
+ In all cases, a pg_shdepend entry indicates that
+ the referenced object cannot be dropped without also dropping the dependent
+ object. However, there are several subflavors identified by
+ deptype:
+
+
SHARED_DEPENDENCY_OWNER (o)
+ The referenced object (which must be a role) is the owner of the
+ dependent object.
+
SHARED_DEPENDENCY_ACL (a)
+ The referenced object (which must be a role) is mentioned in the
+ ACL (access control list, i.e., privileges list) of the
+ dependent object. (A SHARED_DEPENDENCY_ACL entry is
+ not made for the owner of the object, since the owner will have
+ a SHARED_DEPENDENCY_OWNER entry anyway.)
+
SHARED_DEPENDENCY_POLICY (r)
+ The referenced object (which must be a role) is mentioned as the
+ target of a dependent policy object.
+
SHARED_DEPENDENCY_TABLESPACE (t)
+ The referenced object (which must be a tablespace) is mentioned as
+ the tablespace for a relation that doesn't have storage.
+
+
+ Other dependency flavors might be needed in future. Note in particular
+ that the current definition only supports roles and tablespaces as referenced
+ objects.
+
+ As in the pg_depend catalog, most objects
+ created during initdb are
+ considered “pinned”. No entries are made
+ in pg_shdepend that would have a pinned
+ object as either referenced or dependent object.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-shdescription.html b/pgsql/doc/postgresql/html/catalog-pg-shdescription.html
new file mode 100644
index 0000000000000000000000000000000000000000..4b059d4fec6087198763db34773f60a1fb90efae
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-shdescription.html
@@ -0,0 +1,38 @@
+
+53.49. pg_shdescription
+ The catalog pg_shdescription stores optional
+ descriptions (comments) for shared database objects. Descriptions can be
+ manipulated with the COMMENT command and viewed with
+ psql's \d commands.
+
+ See also pg_description,
+ which performs a similar function for descriptions involving objects
+ within a single database.
+
+ Unlike most system catalogs, pg_shdescription
+ is shared across all databases of a cluster: there is only one
+ copy of pg_shdescription per cluster, not
+ one per database.
+
Table 53.49. pg_shdescription Columns
+ Column Type
+
+
+ Description
+
+ objoidoid
+ (references any OID column)
+
+
+ The OID of the object this description pertains to
+
+ The OID of the system catalog this object appears in
+
+ descriptiontext
+
+
+ Arbitrary text that serves as the description of this object
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-shseclabel.html b/pgsql/doc/postgresql/html/catalog-pg-shseclabel.html
new file mode 100644
index 0000000000000000000000000000000000000000..8d7fd8d88841fbe92a2ad2579cbe858ccd95992f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-shseclabel.html
@@ -0,0 +1,43 @@
+
+53.50. pg_shseclabel
+ The catalog pg_shseclabel stores security
+ labels on shared database objects. Security labels can be manipulated
+ with the SECURITY LABEL command. For an easier
+ way to view security labels, see Section 54.22.
+
+ See also pg_seclabel,
+ which performs a similar function for security labels involving objects
+ within a single database.
+
+ Unlike most system catalogs, pg_shseclabel
+ is shared across all databases of a cluster: there is only one
+ copy of pg_shseclabel per cluster, not
+ one per database.
+
Table 53.50. pg_shseclabel Columns
+ Column Type
+
+
+ Description
+
+ objoidoid
+ (references any OID column)
+
+
+ The OID of the object this security label pertains to
+
+ The OID of the system catalog this object appears in
+
+ providertext
+
+
+ The label provider associated with this label.
+
+ labeltext
+
+
+ The security label applied to this object.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-statistic-ext-data.html b/pgsql/doc/postgresql/html/catalog-pg-statistic-ext-data.html
new file mode 100644
index 0000000000000000000000000000000000000000..e9c0cc505e0cf28eb8c3888cfb05146b7bce3638
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-statistic-ext-data.html
@@ -0,0 +1,70 @@
+
+53.53. pg_statistic_ext_data
+ The catalog pg_statistic_ext_data
+ holds data for extended planner statistics defined in
+ pg_statistic_ext.
+ Each row in this catalog corresponds to a statistics object
+ created with CREATE STATISTICS.
+
+ Normally there is one entry, with stxdinherit =
+ false, for each statistics object that has been analyzed.
+ If the table has inheritance children or partitions, a second entry with
+ stxdinherit = true is also created.
+ This row represents the statistics object over the inheritance tree, i.e.,
+ statistics for the data you'd see with
+ SELECT * FROM table*,
+ whereas the stxdinherit = false row
+ represents the results of
+ SELECT * FROM ONLY table.
+
+ Like pg_statistic,
+ pg_statistic_ext_data should not be
+ readable by the public, since the contents might be considered sensitive.
+ (Example: most common combinations of values in columns might be quite
+ interesting.)
+ pg_stats_ext
+ is a publicly readable view
+ on pg_statistic_ext_data (after joining
+ with pg_statistic_ext) that only exposes
+ information about tables the current user owns.
+
+ Extended statistics object containing the definition for this data
+
+ stxdinheritbool
+
+
+ If true, the stats include values from child tables, not just the
+ values in the specified relation
+
+ stxdndistinctpg_ndistinct
+
+
+ N-distinct counts, serialized as pg_ndistinct type
+
+ stxddependenciespg_dependencies
+
+
+ Functional dependency statistics, serialized
+ as pg_dependencies type
+
+ stxdmcvpg_mcv_list
+
+
+ MCV (most-common values) list statistics, serialized as
+ pg_mcv_list type
+
+ stxdexprpg_statistic[]
+
+
+ Per-expression statistics, serialized as an array of
+ pg_statistic type
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-statistic-ext.html b/pgsql/doc/postgresql/html/catalog-pg-statistic-ext.html
new file mode 100644
index 0000000000000000000000000000000000000000..e3467a19257f6e693b986ffdd8bfc3996bf8e35a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-statistic-ext.html
@@ -0,0 +1,88 @@
+
+53.52. pg_statistic_ext
+ The catalog pg_statistic_ext
+ holds definitions of extended planner statistics.
+ Each row in this catalog corresponds to a statistics object
+ created with CREATE STATISTICS.
+
+ stxstattarget controls the level of detail
+ of statistics accumulated for this statistics object by
+ ANALYZE.
+ A zero value indicates that no statistics should be collected.
+ A negative value says to use the maximum of the statistics targets of
+ the referenced columns, if set, or the system default statistics target.
+ Positive values of stxstattarget
+ determine the target number of “most common values”
+ to collect.
+
+ An array of attribute numbers, indicating which table columns are
+ covered by this statistics object;
+ for example a value of 1 3 would
+ mean that the first and the third table columns are covered
+
+ stxkindchar[]
+
+
+ An array containing codes for the enabled statistics kinds;
+ valid values are:
+ d for n-distinct statistics,
+ f for functional dependency statistics,
+ m for most common values (MCV) list statistics, and
+ e for expression statistics
+
+ stxexprspg_node_tree
+
+
+ Expression trees (in nodeToString()
+ representation) for statistics object attributes that are not simple
+ column references. This is a list with one element per expression.
+ Null if all statistics object attributes are simple references.
+
+ The pg_statistic_ext entry is filled in
+ completely during CREATE STATISTICS, but the actual
+ statistical values are not computed then.
+ Subsequent ANALYZE commands compute the desired values
+ and populate an entry in the
+ pg_statistic_ext_data
+ catalog.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-statistic.html b/pgsql/doc/postgresql/html/catalog-pg-statistic.html
new file mode 100644
index 0000000000000000000000000000000000000000..5f5d6ca7229c113f61968082b5a5f46ce06a1be2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-statistic.html
@@ -0,0 +1,134 @@
+
+53.51. pg_statistic
+ The catalog pg_statistic stores
+ statistical data about the contents of the database. Entries are
+ created by ANALYZE
+ and subsequently used by the query planner. Note that all the
+ statistical data is inherently approximate, even assuming that it
+ is up-to-date.
+
+ Normally there is one entry, with stainherit =
+ false, for each table column that has been analyzed.
+ If the table has inheritance children or partitions, a second entry with
+ stainherit = true is also created. This row
+ represents the column's statistics over the inheritance tree, i.e.,
+ statistics for the data you'd see with
+ SELECT column FROM table*,
+ whereas the stainherit = false row represents
+ the results of
+ SELECT column FROM ONLY table.
+
+ pg_statistic also stores statistical data about
+ the values of index expressions. These are described as if they were
+ actual data columns; in particular, starelid
+ references the index. No entry is made for an ordinary non-expression
+ index column, however, since it would be redundant with the entry
+ for the underlying table column. Currently, entries for index expressions
+ always have stainherit = false.
+
+ Since different kinds of statistics might be appropriate for different
+ kinds of data, pg_statistic is designed not
+ to assume very much about what sort of statistics it stores. Only
+ extremely general statistics (such as nullness) are given dedicated
+ columns in pg_statistic. Everything else
+ is stored in “slots”, which are groups of associated columns
+ whose content is identified by a code number in one of the slot's columns.
+ For more information see
+ src/include/catalog/pg_statistic.h.
+
+ pg_statistic should not be readable by the
+ public, since even statistical information about a table's contents
+ might be considered sensitive. (Example: minimum and maximum values
+ of a salary column might be quite interesting.)
+ pg_stats
+ is a publicly readable view on
+ pg_statistic that only exposes information
+ about those tables that are readable by the current user.
+
+ If true, the stats include values from child tables, not just the
+ values in the specified relation
+
+ stanullfracfloat4
+
+
+ The fraction of the column's entries that are null
+
+ stawidthint4
+
+
+ The average stored width, in bytes, of nonnull entries
+
+ stadistinctfloat4
+
+
+ The number of distinct nonnull data values in the column.
+ A value greater than zero is the actual number of distinct values.
+ A value less than zero is the negative of a multiplier for the number
+ of rows in the table; for example, a column in which about 80% of the
+ values are nonnull and each nonnull value appears about twice on
+ average could be represented by stadistinct = -0.4.
+ A zero value means the number of distinct values is unknown.
+
+ stakindNint2
+
+
+ A code number indicating the kind of statistics stored in the
+ Nth “slot” of the
+ pg_statistic row.
+
+ An operator used to derive the statistics stored in the
+ Nth “slot”. For example, a
+ histogram slot would show the < operator
+ that defines the sort order of the data.
+ Zero if the statistics kind does not require an operator.
+
+ The collation used to derive the statistics stored in the
+ Nth “slot”. For example, a
+ histogram slot for a collatable column would show the collation that
+ defines the sort order of the data. Zero for noncollatable data.
+
+ stanumbersNfloat4[]
+
+
+ Numerical statistics of the appropriate kind for the
+ Nth “slot”, or null if the slot
+ kind does not involve numerical values
+
+ stavaluesNanyarray
+
+
+ Column data values of the appropriate kind for the
+ Nth “slot”, or null if the slot
+ kind does not store any data values. Each array's element
+ values are actually of the specific column's data type, or a related
+ type such as an array's element type, so there is no way to define
+ these columns' type more specifically than anyarray.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-subscription-rel.html b/pgsql/doc/postgresql/html/catalog-pg-subscription-rel.html
new file mode 100644
index 0000000000000000000000000000000000000000..798c5a30dc38492d2449150469abe25625d68fa4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-subscription-rel.html
@@ -0,0 +1,45 @@
+
+53.55. pg_subscription_rel
+ State code:
+ i = initialize,
+ d = data is being copied,
+ f = finished table copy,
+ s = synchronized,
+ r = ready (normal replication)
+
+ srsublsnpg_lsn
+
+
+ Remote LSN of the state change used for synchronization coordination
+ when in s or r states,
+ otherwise null
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-subscription.html b/pgsql/doc/postgresql/html/catalog-pg-subscription.html
new file mode 100644
index 0000000000000000000000000000000000000000..804d81e0dbc9c1b5fe857d221bf2410c4b44c754
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-subscription.html
@@ -0,0 +1,130 @@
+
+53.54. pg_subscription
+ The catalog pg_subscription contains all existing
+ logical replication subscriptions. For more information about logical
+ replication see Chapter 31.
+
+ Unlike most system catalogs, pg_subscription is
+ shared across all databases of a cluster: there is only one copy
+ of pg_subscription per cluster, not one per
+ database.
+
+ Access to the column subconninfo is revoked from
+ normal users, because it could contain plain-text passwords.
+
+ If true, the subscription is enabled and should be replicating
+
+ subbinarybool
+
+
+ If true, the subscription will request that the publisher send data
+ in binary format
+
+ substreamchar
+
+
+ Controls how to handle the streaming of in-progress transactions:
+ f = disallow streaming of in-progress transactions,
+ t = spill the changes of in-progress transactions to
+ disk and apply at once after the transaction is committed on the
+ publisher and received by the subscriber,
+ p = apply changes directly using a parallel apply
+ worker if available (same as 't' if no worker is available)
+
+ subtwophasestatechar
+
+
+ State codes for two-phase mode:
+ d = disabled,
+ p = pending enablement,
+ e = enabled
+
+ subdisableonerrbool
+
+
+ If true, the subscription will be disabled if one of its workers
+ detects an error
+
+ subpasswordrequiredbool
+
+
+ If true, the subscription will be required to specify a password
+ for authentication
+
+ subrunasownerbool
+
+
+ If true, the subscription will be run with the permissions
+ of the subscription owner
+
+ subconninfotext
+
+
+ Connection string to the upstream database
+
+ subslotnamename
+
+
+ Name of the replication slot in the upstream database (also used
+ for the local replication origin name);
+ null represents NONE
+
+ subsynccommittext
+
+
+ The synchronous_commit
+ setting for the subscription's workers to use
+
+ subpublicationstext[]
+
+
+ Array of subscribed publication names. These reference
+ publications defined in the upstream database. For more on publications
+ see Section 31.1.
+
+ suborigintext
+
+
+ The origin value must be either none or
+ any. The default is any.
+ If none, the subscription will request the publisher
+ to only send changes that don't have an origin. If
+ any, the publisher sends changes regardless of their
+ origin.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-tablespace.html b/pgsql/doc/postgresql/html/catalog-pg-tablespace.html
new file mode 100644
index 0000000000000000000000000000000000000000..3c07108a2f971b51820cb8002bdf35225164783d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-tablespace.html
@@ -0,0 +1,42 @@
+
+53.56. pg_tablespace
+ The catalog pg_tablespace stores information
+ about the available tablespaces. Tables can be placed in particular
+ tablespaces to aid administration of disk layout.
+
+ Unlike most system catalogs, pg_tablespace
+ is shared across all databases of a cluster: there is only one
+ copy of pg_tablespace per cluster, not
+ one per database.
+
+ Owner of the tablespace, usually the user who created it
+
+ spcaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
+ spcoptionstext[]
+
+
+ Tablespace-level options, as “keyword=value” strings
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-transform.html b/pgsql/doc/postgresql/html/catalog-pg-transform.html
new file mode 100644
index 0000000000000000000000000000000000000000..ee4b586252fd2fa9036758b3bbdd9f9e99c77976
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-transform.html
@@ -0,0 +1,44 @@
+
+53.57. pg_transform
+ The catalog pg_transform stores information about
+ transforms, which are a mechanism to adapt data types to procedural
+ languages. See CREATE TRANSFORM for more information.
+
+ The OID of the function to use when converting the data type for input
+ to the procedural language (e.g., function parameters). Zero is stored
+ if the default behavior should be used.
+
+ The OID of the function to use when converting output from the
+ procedural language (e.g., return values) to the data type. Zero is
+ stored if the default behavior should be used.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-trigger.html b/pgsql/doc/postgresql/html/catalog-pg-trigger.html
new file mode 100644
index 0000000000000000000000000000000000000000..1efa8e33e4837dbddf3ba4ed8dd50d9ff438469b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-trigger.html
@@ -0,0 +1,148 @@
+
+53.58. pg_trigger
+ Parent trigger that this trigger is cloned from (this happens when
+ partitions are created or attached to a partitioned table);
+ zero if not a clone
+
+ tgnamename
+
+
+ Trigger name (must be unique among triggers of same table)
+
+ Bit mask identifying trigger firing conditions
+
+ tgenabledchar
+
+
+ Controls in which session_replication_role modes
+ the trigger fires.
+ O = trigger fires in “origin” and “local” modes,
+ D = trigger is disabled,
+ R = trigger fires in “replica” mode,
+ A = trigger fires always.
+
+ tgisinternalbool
+
+
+ True if trigger is internally generated (usually, to enforce
+ the constraint identified by tgconstraint)
+
+ The index supporting a unique, primary key, referential integrity,
+ or exclusion constraint
+ (zero if trigger is not for one of these types of constraint)
+
+ Column numbers, if trigger is column-specific; otherwise an
+ empty array
+
+ tgargsbytea
+
+
+ Argument strings to pass to trigger, each NULL-terminated
+
+ tgqualpg_node_tree
+
+
+ Expression tree (in nodeToString()
+ representation) for the trigger's WHEN condition, or null
+ if none
+
+ tgoldtablename
+
+
+ REFERENCING clause name for OLD TABLE,
+ or null if none
+
+ tgnewtablename
+
+
+ REFERENCING clause name for NEW TABLE,
+ or null if none
+
+ Currently, column-specific triggering is supported only for
+ UPDATE events, and so tgattr is relevant
+ only for that event type. tgtype might
+ contain bits for other event types as well, but those are presumed
+ to be table-wide regardless of what is in tgattr.
+
Note
+ When tgconstraint is nonzero,
+ tgconstrrelid, tgconstrindid,
+ tgdeferrable, and tginitdeferred are
+ largely redundant with the referenced pg_constraint entry.
+ However, it is possible for a non-deferrable trigger to be associated
+ with a deferrable constraint: foreign key constraints can have some
+ deferrable and some non-deferrable triggers.
+
Note
+ pg_class.relhastriggers
+ must be true if a relation has any triggers in this catalog.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-ts-config-map.html b/pgsql/doc/postgresql/html/catalog-pg-ts-config-map.html
new file mode 100644
index 0000000000000000000000000000000000000000..1a9a8f8b69fe7fe2c44dbcf6a0c6a51d20dddd51
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-ts-config-map.html
@@ -0,0 +1,38 @@
+
+53.60. pg_ts_config_map
+ The pg_ts_config_map catalog contains entries
+ showing which text search dictionaries should be consulted, and in
+ what order, for each output token type of each text search configuration's
+ parser.
+
+ PostgreSQL's text search features are
+ described at length in Chapter 12.
+
+ The OID of the text search dictionary to consult
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-ts-config.html b/pgsql/doc/postgresql/html/catalog-pg-ts-config.html
new file mode 100644
index 0000000000000000000000000000000000000000..ddee01d04b8d2e27210d38b591f74fcd47a6c215
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-ts-config.html
@@ -0,0 +1,45 @@
+
+53.59. pg_ts_config
+ The pg_ts_config catalog contains entries
+ representing text search configurations. A configuration specifies
+ a particular text search parser and a list of dictionaries to use
+ for each of the parser's output token types. The parser is shown
+ in the pg_ts_config entry, but the
+ token-to-dictionary mapping is defined by subsidiary entries in pg_ts_config_map.
+
+ PostgreSQL's text search features are
+ described at length in Chapter 12.
+
+ The OID of the text search parser for this configuration
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-ts-dict.html b/pgsql/doc/postgresql/html/catalog-pg-ts-dict.html
new file mode 100644
index 0000000000000000000000000000000000000000..4b0021aad368c4d83ff4e2192dda072517c831bd
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-ts-dict.html
@@ -0,0 +1,52 @@
+
+53.61. pg_ts_dict
+ The pg_ts_dict catalog contains entries
+ defining text search dictionaries. A dictionary depends on a text
+ search template, which specifies all the implementation functions
+ needed; the dictionary itself provides values for the user-settable
+ parameters supported by the template. This division of labor allows
+ dictionaries to be created by unprivileged users. The parameters
+ are specified by a text string dictinitoption,
+ whose format and meaning vary depending on the template.
+
+ PostgreSQL's text search features are
+ described at length in Chapter 12.
+
+ The OID of the text search template for this dictionary
+
+ dictinitoptiontext
+
+
+ Initialization option string for the template
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-ts-parser.html b/pgsql/doc/postgresql/html/catalog-pg-ts-parser.html
new file mode 100644
index 0000000000000000000000000000000000000000..ac7baacdafeae8668e2f3165bba8c9a3865b3530
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-ts-parser.html
@@ -0,0 +1,62 @@
+
+53.62. pg_ts_parser
+ The pg_ts_parser catalog contains entries
+ defining text search parsers. A parser is responsible for splitting
+ input text into lexemes and assigning a token type to each lexeme.
+ Since a parser must be implemented by C-language-level functions,
+ creation of new parsers is restricted to database superusers.
+
+ PostgreSQL's text search features are
+ described at length in Chapter 12.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-ts-template.html b/pgsql/doc/postgresql/html/catalog-pg-ts-template.html
new file mode 100644
index 0000000000000000000000000000000000000000..696b99e06ffb5abd3a86a9fd06516c648ff7ea6f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-ts-template.html
@@ -0,0 +1,44 @@
+
+53.63. pg_ts_template
+ The pg_ts_template catalog contains entries
+ defining text search templates. A template is the implementation
+ skeleton for a class of text search dictionaries.
+ Since a template must be implemented by C-language-level functions,
+ creation of new templates is restricted to database superusers.
+
+ PostgreSQL's text search features are
+ described at length in Chapter 12.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-type.html b/pgsql/doc/postgresql/html/catalog-pg-type.html
new file mode 100644
index 0000000000000000000000000000000000000000..78653f13885bf2600d7264a7584c226398470a2b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-type.html
@@ -0,0 +1,310 @@
+
+53.64. pg_type
+ The catalog pg_type stores information about data
+ types. Base types and enum types (scalar types) are created with
+ CREATE TYPE, and
+ domains with
+ CREATE DOMAIN.
+ A composite type is automatically created for each table in the database, to
+ represent the row structure of the table. It is also possible to create
+ composite types with CREATE TYPE AS.
+
+ For a fixed-size type, typlen is the number
+ of bytes in the internal representation of the type. But for a
+ variable-length type, typlen is negative.
+ -1 indicates a “varlena” type (one that has a length word),
+ -2 indicates a null-terminated C string.
+
+ typbyvalbool
+
+
+ typbyval determines whether internal
+ routines pass a value of this type by value or by reference.
+ typbyval had better be false if
+ typlen is not 1, 2, or 4 (or 8 on machines
+ where Datum is 8 bytes).
+ Variable-length types are always passed by reference. Note that
+ typbyval can be false even if the
+ length would allow pass-by-value.
+
+ typtypechar
+
+
+ typtype is
+ b for a base type,
+ c for a composite type (e.g., a table's row type),
+ d for a domain,
+ e for an enum type,
+ p for a pseudo-type,
+ r for a range type, or
+ m for a multirange type.
+ See also typrelid and
+ typbasetype.
+
+ typcategorychar
+
+
+ typcategory is an arbitrary classification
+ of data types that is used by the parser to determine which implicit
+ casts should be “preferred”.
+ See Table 53.65.
+
+ typispreferredbool
+
+
+ True if the type is a preferred cast target within its
+ typcategory
+
+ typisdefinedbool
+
+
+ True if the type is defined, false if this is a placeholder
+ entry for a not-yet-defined type. When
+ typisdefined is false, nothing
+ except the type name, namespace, and OID can be relied on.
+
+ typdelimchar
+
+
+ Character that separates two values of this type when parsing
+ array input. Note that the delimiter is associated with the array
+ element data type, not the array data type.
+
+ If this is a composite type (see
+ typtype), then this column points to
+ the pg_class entry that defines the
+ corresponding table. (For a free-standing composite type, the
+ pg_class entry doesn't really represent
+ a table, but it is needed anyway for the type's
+ pg_attribute entries to link to.)
+ Zero for non-composite types.
+
+ Subscripting handler function's OID, or zero if this type doesn't
+ support subscripting. Types that are “true” array
+ types have typsubscript
+ = array_subscript_handler, but other types may
+ have other handler functions to implement specialized subscripting
+ behavior.
+
+ If typelem is not zero then it
+ identifies another row in pg_type,
+ defining the type yielded by subscripting. This should be zero
+ if typsubscript is zero. However, it can
+ be zero when typsubscript isn't zero, if the
+ handler doesn't need typelem to
+ determine the subscripting result type.
+ Note that a typelem dependency is
+ considered to imply physical containment of the element type in
+ this type; so DDL changes on the element type might be restricted
+ by the presence of this type.
+
+ Custom ANALYZE function,
+ or zero to use the standard function
+
+ typalignchar
+
+
+ typalign is the alignment required
+ when storing a value of this type. It applies to storage on
+ disk as well as most representations of the value inside
+ PostgreSQL.
+ When multiple values are stored consecutively, such
+ as in the representation of a complete row on disk, padding is
+ inserted before a datum of this type so that it begins on the
+ specified boundary. The alignment reference is the beginning
+ of the first datum in the sequence.
+ Possible values are:
+
c = char alignment, i.e., no alignment needed.
s = short alignment (2 bytes on most machines).
i = int alignment (4 bytes on most machines).
d = double alignment (8 bytes on many machines, but by no means all).
+
+ typstoragechar
+
+
+ typstorage tells for varlena
+ types (those with typlen = -1) if
+ the type is prepared for toasting and what the default strategy
+ for attributes of this type should be.
+ Possible values are:
+
+ p (plain): Values must always be stored plain
+ (non-varlena types always use this value).
+
+ e (external): Values can be stored in a
+ secondary “TOAST” relation (if relation has one, see
+ pg_class.reltoastrelid).
+
+ m (main): Values can be compressed and stored
+ inline.
+
+ x (extended): Values can be compressed and/or
+ moved to a secondary relation.
+
+ x is the usual choice for toast-able types.
+ Note that m values can also be moved out to
+ secondary storage, but only as a last resort (e
+ and x values are moved first).
+
+ typnotnullbool
+
+
+ typnotnull represents a not-null
+ constraint on a type. Used for domains only.
+
+ If this is a domain (see typtype), then
+ typbasetype identifies the type that this
+ one is based on. Zero if this type is not a domain.
+
+ typtypmodint4
+
+
+ Domains use typtypmod to record the typmod
+ to be applied to their base type (-1 if base type does not use a
+ typmod). -1 if this type is not a domain.
+
+ typndimsint4
+
+
+ typndims is the number of array dimensions
+ for a domain over an array (that is, typbasetype is
+ an array type).
+ Zero for types other than domains over array types.
+
+ typcollation specifies the collation
+ of the type. If the type does not support collations, this will
+ be zero. A base type that supports collations will have a nonzero
+ value here, typically DEFAULT_COLLATION_OID.
+ A domain over a collatable type can have a collation OID different
+ from its base type's, if one was specified for the domain.
+
+ typdefaultbinpg_node_tree
+
+
+ If typdefaultbin is not null, it is the
+ nodeToString()
+ representation of a default expression for the type. This is
+ only used for domains.
+
+ typdefaulttext
+
+
+ typdefault is null if the type has no associated
+ default value. If typdefaultbin is not null,
+ typdefault must contain a human-readable version of the
+ default expression represented by typdefaultbin. If
+ typdefaultbin is null and typdefault is
+ not, then typdefault is the external representation of
+ the type's default value, which can be fed to the type's input
+ converter to produce a constant.
+
+ typaclaclitem[]
+
+
+ Access privileges; see Section 5.7 for details
+
Note
+ For fixed-width types used in system tables, it is critical that the size
+ and alignment defined in pg_type
+ agree with the way that the compiler will lay out the column in
+ a structure representing a table row.
+
+ Table 53.65 lists the system-defined values
+ of typcategory. Any future additions to this list will
+ also be upper-case ASCII letters. All other ASCII characters are reserved
+ for user-defined categories.
+
Table 53.65. typcategory Codes
Code
Category
A
Array types
B
Boolean types
C
Composite types
D
Date/time types
E
Enum types
G
Geometric types
I
Network address types
N
Numeric types
P
Pseudo-types
R
Range types
S
String types
T
Timespan types
U
User-defined types
V
Bit-string types
X
unknown type
Z
Internal-use types
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalog-pg-user-mapping.html b/pgsql/doc/postgresql/html/catalog-pg-user-mapping.html
new file mode 100644
index 0000000000000000000000000000000000000000..3e8e366fa06ad6a0957488cb43b9742674dffd48
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalog-pg-user-mapping.html
@@ -0,0 +1,35 @@
+
+53.65. pg_user_mapping
+ The catalog pg_user_mapping stores
+ the mappings from local user to remote. Access to this catalog is
+ restricted from normal users, use the view
+ pg_user_mappings
+ instead.
+
+ The OID of the foreign server that contains this mapping
+
+ umoptionstext[]
+
+
+ User mapping specific options, as “keyword=value” strings
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalogs-overview.html b/pgsql/doc/postgresql/html/catalogs-overview.html
new file mode 100644
index 0000000000000000000000000000000000000000..0def878d24db301b5a32a597a7be80c9e1fae98d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalogs-overview.html
@@ -0,0 +1,10 @@
+
+53.1. Overview
+ Table 53.1 lists the system catalogs.
+ More detailed documentation of each catalog follows below.
+
+ Most system catalogs are copied from the template database during
+ database creation and are thereafter database-specific. A few
+ catalogs are physically shared across all databases in a cluster;
+ these are noted in the descriptions of the individual catalogs.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/catalogs.html b/pgsql/doc/postgresql/html/catalogs.html
new file mode 100644
index 0000000000000000000000000000000000000000..6931fe3da5d31fb4885735593c6f19c8414a359e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/catalogs.html
@@ -0,0 +1,17 @@
+
+Chapter 53. System Catalogs
+ The system catalogs are the place where a relational database
+ management system stores schema metadata, such as information about
+ tables and columns, and internal bookkeeping information.
+ PostgreSQL's system catalogs are regular
+ tables. You can drop and recreate the tables, add columns, insert
+ and update values, and severely mess up your system that way.
+ Normally, one should not change the system catalogs by hand, there
+ are normally SQL commands to do that. (For example, CREATE
+ DATABASE inserts a row into the
+ pg_database catalog — and actually
+ creates the database on disk.) There are some exceptions for
+ particularly esoteric operations, but many of those have been made
+ available as SQL commands over time, and so the need for direct manipulation
+ of the system catalogs is ever decreasing.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/charset.html b/pgsql/doc/postgresql/html/charset.html
new file mode 100644
index 0000000000000000000000000000000000000000..d948ca3f29612f061e34579134adb2bbf280044c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/charset.html
@@ -0,0 +1,20 @@
+
+Chapter 24. Localization
+ This chapter describes the available localization features from the
+ point of view of the administrator.
+ PostgreSQL supports two localization
+ facilities:
+
+
+ Using the locale features of the operating system to provide
+ locale-specific collation order, number formatting, translated
+ messages, and other aspects.
+ This is covered in Section 24.1 and
+ Section 24.2.
+
+ Providing a number of different character sets to support storing text
+ in all kinds of languages, and providing character set translation
+ between client and server.
+ This is covered in Section 24.3.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/checksums.html b/pgsql/doc/postgresql/html/checksums.html
new file mode 100644
index 0000000000000000000000000000000000000000..28e0756d61304f1b1a888a032f4b7281c8408e41
--- /dev/null
+++ b/pgsql/doc/postgresql/html/checksums.html
@@ -0,0 +1,25 @@
+
+30.2. Data Checksums
+ By default, data pages are not protected by checksums, but this can
+ optionally be enabled for a cluster. When enabled, each data page includes
+ a checksum that is updated when the page is written and verified each time
+ the page is read. Only data pages are protected by checksums; internal data
+ structures and temporary files are not.
+
+ Checksums are normally enabled when the cluster is initialized using initdb.
+ They can also be enabled or disabled at a later time as an offline
+ operation. Data checksums are enabled or disabled at the full cluster
+ level, and cannot be specified individually for databases or tables.
+
+ The current state of checksums in the cluster can be verified by viewing the
+ value of the read-only configuration variable data_checksums by issuing the command SHOW
+ data_checksums.
+
+ When attempting to recover from page corruptions, it may be necessary to
+ bypass the checksum protection. To do this, temporarily set the
+ configuration parameter ignore_checksum_failure.
+
+ The pg_checksums
+ application can be used to enable or disable data checksums, as well as
+ verify checksums, on an offline cluster.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/citext.html b/pgsql/doc/postgresql/html/citext.html
new file mode 100644
index 0000000000000000000000000000000000000000..1eb76395c1dcc5d1ced6c6b6a12940b30d9b3e3f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/citext.html
@@ -0,0 +1,166 @@
+
+F.10. citext — a case-insensitive character string type
F.10. citext — a case-insensitive character string type
+ The citext module provides a case-insensitive
+ character string type, citext. Essentially, it internally calls
+ lower when comparing values. Otherwise, it behaves almost
+ exactly like text.
+
Tip
+ Consider using nondeterministic collations (see
+ Section 24.2.2.4) instead of this module. They
+ can be used for case-insensitive comparisons, accent-insensitive
+ comparisons, and other combinations, and they handle more Unicode special
+ cases correctly.
+
+ This module is considered “trusted”, that is, it can be
+ installed by non-superusers who have CREATE privilege
+ on the current database.
+
+ The standard approach to doing case-insensitive matches
+ in PostgreSQL has been to use the lower
+ function when comparing values, for example
+
+
+SELECT * FROM tab WHERE lower(col) = LOWER(?);
+
+
+ This works reasonably well, but has a number of drawbacks:
+
+ It makes your SQL statements verbose, and you always have to remember to
+ use lower on both the column and the query value.
+
+ It won't use an index, unless you create a functional index using
+ lower.
+
+ If you declare a column as UNIQUE or PRIMARY
+ KEY, the implicitly generated index is case-sensitive. So it's
+ useless for case-insensitive searches, and it won't enforce
+ uniqueness case-insensitively.
+
+ The citext data type allows you to eliminate calls
+ to lower in SQL queries, and allows a primary key to
+ be case-insensitive. citext is locale-aware, just
+ like text, which means that the matching of upper case and
+ lower case characters is dependent on the rules of
+ the database's LC_CTYPE setting. Again, this behavior is
+ identical to the use of lower in queries. But because it's
+ done transparently by the data type, you don't have to remember to do
+ anything special in your queries.
+
+ citext performs comparisons by converting each string to lower
+ case (as though lower were called) and then comparing the
+ results normally. Thus, for example, two strings are considered equal
+ if lower would produce identical results for them.
+
+ In order to emulate a case-insensitive collation as closely as possible,
+ there are citext-specific versions of a number of string-processing
+ operators and functions. So, for example, the regular expression
+ operators ~ and ~* exhibit the same behavior when
+ applied to citext: they both match case-insensitively.
+ The same is true
+ for !~ and !~*, as well as for the
+ LIKE operators ~~ and ~~*, and
+ !~~ and !~~*. If you'd like to match
+ case-sensitively, you can cast the operator's arguments to text.
+
+ Similarly, all of the following functions perform matching
+ case-insensitively if their arguments are citext:
+
+ regexp_match()
+
+ regexp_matches()
+
+ regexp_replace()
+
+ regexp_split_to_array()
+
+ regexp_split_to_table()
+
+ replace()
+
+ split_part()
+
+ strpos()
+
+ translate()
+
+ For the regexp functions, if you want to match case-sensitively, you can
+ specify the “c” flag to force a case-sensitive match. Otherwise,
+ you must cast to text before using one of these functions if
+ you want case-sensitive behavior.
+
+ citext's case-folding behavior depends on
+ the LC_CTYPE setting of your database. How it compares
+ values is therefore determined when the database is created.
+ It is not truly
+ case-insensitive in the terms defined by the Unicode standard.
+ Effectively, what this means is that, as long as you're happy with your
+ collation, you should be happy with citext's comparisons. But
+ if you have data in different languages stored in your database, users
+ of one language may find their query results are not as expected if the
+ collation is for another language.
+
+ As of PostgreSQL 9.1, you can attach a
+ COLLATE specification to citext columns or data
+ values. Currently, citext operators will honor a non-default
+ COLLATE specification while comparing case-folded strings,
+ but the initial folding to lower case is always done according to the
+ database's LC_CTYPE setting (that is, as though
+ COLLATE "default" were given). This may be changed in a
+ future release so that both steps follow the input COLLATE
+ specification.
+
+ citext is not as efficient as text because the
+ operator functions and the B-tree comparison functions must make copies
+ of the data and convert it to lower case for comparisons. Also, only
+ text can support B-Tree deduplication. However,
+ citext is slightly more efficient than using
+ lower to get case-insensitive matching.
+
+ citext doesn't help much if you need data to compare
+ case-sensitively in some contexts and case-insensitively in other
+ contexts. The standard answer is to use the text type and
+ manually use the lower function when you need to compare
+ case-insensitively; this works all right if case-insensitive comparison
+ is needed only infrequently. If you need case-insensitive behavior most
+ of the time and case-sensitive infrequently, consider storing the data
+ as citext and explicitly casting the column to text
+ when you want case-sensitive comparison. In either situation, you will
+ need two indexes if you want both types of searches to be fast.
+
+ The schema containing the citext operators must be
+ in the current search_path (typically public);
+ if it is not, the normal case-sensitive text operators
+ will be invoked instead.
+
+ The approach of lower-casing strings for comparison does not handle some
+ Unicode special cases correctly, for example when one upper-case letter
+ has two lower-case letter equivalents. Unicode distinguishes between
+ case mapping and case
+ folding for this reason. Use nondeterministic collations
+ instead of citext to handle that correctly.
+
+ Inspired by the original citext module by Donald Fraser.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/client-authentication-problems.html b/pgsql/doc/postgresql/html/client-authentication-problems.html
new file mode 100644
index 0000000000000000000000000000000000000000..700417d78617249239193a9ac24094d7055053e3
--- /dev/null
+++ b/pgsql/doc/postgresql/html/client-authentication-problems.html
@@ -0,0 +1,40 @@
+
+21.15. Authentication Problems
+ Authentication failures and related problems generally
+ manifest themselves through error messages like the following:
+
+
+FATAL: no pg_hba.conf entry for host "123.123.123.123", user "andym", database "testdb"
+
+ This is what you are most likely to get if you succeed in contacting
+ the server, but it does not want to talk to you. As the message
+ suggests, the server refused the connection request because it found
+ no matching entry in its pg_hba.conf
+ configuration file.
+
+
+FATAL: password authentication failed for user "andym"
+
+ Messages like this indicate that you contacted the server, and it is
+ willing to talk to you, but not until you pass the authorization
+ method specified in the pg_hba.conf file. Check
+ the password you are providing, or check your Kerberos or ident
+ software if the complaint mentions one of those authentication
+ types.
+
+
+FATAL: user "andym" does not exist
+
+ The indicated database user name was not found.
+
+
+FATAL: database "testdb" does not exist
+
+ The database you are trying to connect to does not exist. Note that
+ if you do not specify a database name, it defaults to the database
+ user name.
+
Tip
+ The server log might contain more information about an
+ authentication failure than is reported to the client. If you are
+ confused about the reason for a failure, check the server log.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/client-authentication.html b/pgsql/doc/postgresql/html/client-authentication.html
new file mode 100644
index 0000000000000000000000000000000000000000..a4936bf2512548a7eca7d28571e0534faaad4337
--- /dev/null
+++ b/pgsql/doc/postgresql/html/client-authentication.html
@@ -0,0 +1,37 @@
+
+Chapter 21. Client Authentication
+ When a client application connects to the database server, it
+ specifies which PostgreSQL database user name it
+ wants to connect as, much the same way one logs into a Unix computer
+ as a particular user. Within the SQL environment the active database
+ user name determines access privileges to database objects — see
+ Chapter 22 for more information. Therefore, it is
+ essential to restrict which database users can connect.
+
Note
+ As explained in Chapter 22,
+ PostgreSQL actually does privilege
+ management in terms of “roles”. In this chapter, we
+ consistently use database user to mean “role with the
+ LOGIN privilege”.
+
+ Authentication is the process by which the
+ database server establishes the identity of the client, and by
+ extension determines whether the client application (or the user
+ who runs the client application) is permitted to connect with the
+ database user name that was requested.
+
+ PostgreSQL offers a number of different
+ client authentication methods. The method used to authenticate a
+ particular client connection can be selected on the basis of
+ (client) host address, database, and user.
+
+ PostgreSQL database user names are logically
+ separate from user names of the operating system in which the server
+ runs. If all the users of a particular server also have accounts on
+ the server's machine, it makes sense to assign database user names
+ that match their operating system user names. However, a server that
+ accepts remote connections might have many database users who have no local
+ operating system
+ account, and in such cases there need be no connection between
+ database user names and OS user names.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/client-interfaces.html b/pgsql/doc/postgresql/html/client-interfaces.html
new file mode 100644
index 0000000000000000000000000000000000000000..86d55e711cfa61b9fe28d93450dc2f2f6157a405
--- /dev/null
+++ b/pgsql/doc/postgresql/html/client-interfaces.html
@@ -0,0 +1,12 @@
+
+Part IV. Client Interfaces
+ This part describes the client programming interfaces distributed
+ with PostgreSQL. Each of these chapters can be
+ read independently. Note that there are many other programming
+ interfaces for client programs that are distributed separately and
+ contain their own documentation (Appendix H
+ lists some of the more popular ones). Readers of this part should be
+ familiar with using SQL commands to manipulate
+ and query the database (see Part II) and of course
+ with the programming language that the interface uses.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/collation.html b/pgsql/doc/postgresql/html/collation.html
new file mode 100644
index 0000000000000000000000000000000000000000..85149e9a3e412a3487ad3a1436520160b6db7aa8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/collation.html
@@ -0,0 +1,603 @@
+
+24.2. Collation Support
+ The collation feature allows specifying the sort order and character
+ classification behavior of data per-column, or even per-operation.
+ This alleviates the restriction that the
+ LC_COLLATE and LC_CTYPE settings
+ of a database cannot be changed after its creation.
+
+ Conceptually, every expression of a collatable data type has a
+ collation. (The built-in collatable data types are
+ text, varchar, and char.
+ User-defined base types can also be marked collatable, and of course
+ a domain over a
+ collatable data type is collatable.) If the
+ expression is a column reference, the collation of the expression is the
+ defined collation of the column. If the expression is a constant, the
+ collation is the default collation of the data type of the
+ constant. The collation of a more complex expression is derived
+ from the collations of its inputs, as described below.
+
+ The collation of an expression can be the “default”
+ collation, which means the locale settings defined for the
+ database. It is also possible for an expression's collation to be
+ indeterminate. In such cases, ordering operations and other
+ operations that need to know the collation will fail.
+
+ When the database system has to perform an ordering or a character
+ classification, it uses the collation of the input expression. This
+ happens, for example, with ORDER BY clauses
+ and function or operator calls such as <.
+ The collation to apply for an ORDER BY clause
+ is simply the collation of the sort key. The collation to apply for a
+ function or operator call is derived from the arguments, as described
+ below. In addition to comparison operators, collations are taken into
+ account by functions that convert between lower and upper case
+ letters, such as lower, upper, and
+ initcap; by pattern matching operators; and by
+ to_char and related functions.
+
+ For a function or operator call, the collation that is derived by
+ examining the argument collations is used at run time for performing
+ the specified operation. If the result of the function or operator
+ call is of a collatable data type, the collation is also used at parse
+ time as the defined collation of the function or operator expression,
+ in case there is a surrounding expression that requires knowledge of
+ its collation.
+
+ The collation derivation of an expression can be
+ implicit or explicit. This distinction affects how collations are
+ combined when multiple different collations appear in an
+ expression. An explicit collation derivation occurs when a
+ COLLATE clause is used; all other collation
+ derivations are implicit. When multiple collations need to be
+ combined, for example in a function call, the following rules are
+ used:
+
+
+ If any input expression has an explicit collation derivation, then
+ all explicitly derived collations among the input expressions must be
+ the same, otherwise an error is raised. If any explicitly
+ derived collation is present, that is the result of the
+ collation combination.
+
+ Otherwise, all input expressions must have the same implicit
+ collation derivation or the default collation. If any non-default
+ collation is present, that is the result of the collation combination.
+ Otherwise, the result is the default collation.
+
+ If there are conflicting non-default implicit collations among the
+ input expressions, then the combination is deemed to have indeterminate
+ collation. This is not an error condition unless the particular
+ function being invoked requires knowledge of the collation it should
+ apply. If it does, an error will be raised at run-time.
+
+
+ For example, consider this table definition:
+
+CREATE TABLE test1 (
+ a text COLLATE "de_DE",
+ b text COLLATE "es_ES",
+ ...
+);
+
+
+ Then in
+
+SELECT a < 'foo' FROM test1;
+
+ the < comparison is performed according to
+ de_DE rules, because the expression combines an
+ implicitly derived collation with the default collation. But in
+
+SELECT a < ('foo' COLLATE "fr_FR") FROM test1;
+
+ the comparison is performed using fr_FR rules,
+ because the explicit collation derivation overrides the implicit one.
+ Furthermore, given
+
+SELECT a < b FROM test1;
+
+ the parser cannot determine which collation to apply, since the
+ a and b columns have conflicting
+ implicit collations. Since the < operator
+ does need to know which collation to use, this will result in an
+ error. The error can be resolved by attaching an explicit collation
+ specifier to either input expression, thus:
+
+SELECT a < b COLLATE "de_DE" FROM test1;
+
+ or equivalently
+
+SELECT a COLLATE "de_DE" < b FROM test1;
+
+ On the other hand, the structurally similar case
+
+SELECT a || b FROM test1;
+
+ does not result in an error, because the || operator
+ does not care about collations: its result is the same regardless
+ of the collation.
+
+ The collation assigned to a function or operator's combined input
+ expressions is also considered to apply to the function or operator's
+ result, if the function or operator delivers a result of a collatable
+ data type. So, in
+
+SELECT * FROM test1 ORDER BY a || 'foo';
+
+ the ordering will be done according to de_DE rules.
+ But this query:
+
+SELECT * FROM test1 ORDER BY a || b;
+
+ results in an error, because even though the || operator
+ doesn't need to know a collation, the ORDER BY clause does.
+ As before, the conflict can be resolved with an explicit collation
+ specifier:
+
+SELECT * FROM test1 ORDER BY a || b COLLATE "fr_FR";
+
+ A collation is an SQL schema object that maps an SQL name to locales
+ provided by libraries installed in the operating system. A collation
+ definition has a provider that specifies which
+ library supplies the locale data. One standard provider name
+ is libc, which uses the locales provided by the
+ operating system C library. These are the locales used by most tools
+ provided by the operating system. Another provider
+ is icu, which uses the external
+ ICU library. ICU locales can only be
+ used if support for ICU was configured when PostgreSQL was built.
+
+ A collation object provided by libc maps to a
+ combination of LC_COLLATE and LC_CTYPE
+ settings, as accepted by the setlocale() system library call. (As
+ the name would suggest, the main purpose of a collation is to set
+ LC_COLLATE, which controls the sort order. But
+ it is rarely necessary in practice to have an
+ LC_CTYPE setting that is different from
+ LC_COLLATE, so it is more convenient to collect
+ these under one concept than to create another infrastructure for
+ setting LC_CTYPE per expression.) Also,
+ a libc collation
+ is tied to a character set encoding (see Section 24.3).
+ The same collation name may exist for different encodings.
+
+ A collation object provided by icu maps to a named
+ collator provided by the ICU library. ICU does not support
+ separate “collate” and “ctype” settings, so
+ they are always the same. Also, ICU collations are independent of the
+ encoding, so there is always only one ICU collation of a given name in
+ a database.
+
+ On all platforms, the collations named default,
+ C, and POSIX are available. Additional
+ collations may be available depending on operating system support.
+ The default collation selects the LC_COLLATE
+ and LC_CTYPE values specified at database creation time.
+ The C and POSIX collations both specify
+ “traditional C” behavior, in which only the ASCII letters
+ “A” through “Z”
+ are treated as letters, and sorting is done strictly by character
+ code byte values.
+
Note
+ The C and POSIX locales may behave
+ differently depending on the database encoding.
+
+ Additionally, two SQL standard collation names are available:
+
+
unicode
+ This collation sorts using the Unicode Collation Algorithm with the
+ Default Unicode Collation Element Table. It is available in all
+ encodings. ICU support is required to use this collation. (This
+ collation has the same behavior as the ICU root locale; see und-x-icu (for “undefined”).)
+
ucs_basic
+ This collation sorts by Unicode code point. It is only available for
+ encoding UTF8. (This collation has the same
+ behavior as the libc locale specification C in
+ UTF8 encoding.)
+
+ If the operating system provides support for using multiple locales
+ within a single program (newlocale and related functions),
+ or if support for ICU is configured,
+ then when a database cluster is initialized, initdb
+ populates the system catalog pg_collation with
+ collations based on all the locales it finds in the operating
+ system at the time.
+
+ To inspect the currently available locales, use the query SELECT
+ * FROM pg_collation, or the command \dOS+
+ in psql.
+
+ For example, the operating system might
+ provide a locale named de_DE.utf8.
+ initdb would then create a collation named
+ de_DE.utf8 for encoding UTF8
+ that has both LC_COLLATE and
+ LC_CTYPE set to de_DE.utf8.
+ It will also create a collation with the .utf8
+ tag stripped off the name. So you could also use the collation
+ under the name de_DE, which is less cumbersome
+ to write and makes the name less encoding-dependent. Note that,
+ nevertheless, the initial set of collation names is
+ platform-dependent.
+
+ The default set of collations provided by libc map
+ directly to the locales installed in the operating system, which can be
+ listed using the command locale -a. In case
+ a libc collation is needed that has different values
+ for LC_COLLATE and LC_CTYPE, or if new
+ locales are installed in the operating system after the database system
+ was initialized, then a new collation may be created using
+ the CREATE COLLATION command.
+ New operating system locales can also be imported en masse using
+ the pg_import_system_collations() function.
+
+ Within any particular database, only collations that use that
+ database's encoding are of interest. Other entries in
+ pg_collation are ignored. Thus, a stripped collation
+ name such as de_DE can be considered unique
+ within a given database even though it would not be unique globally.
+ Use of the stripped collation names is recommended, since it will
+ make one fewer thing you need to change if you decide to change to
+ another database encoding. Note however that the default,
+ C, and POSIX collations can be used regardless of
+ the database encoding.
+
+ PostgreSQL considers distinct collation
+ objects to be incompatible even when they have identical properties.
+ Thus for example,
+
+SELECT a COLLATE "C" < b COLLATE "POSIX" FROM test1;
+
+ will draw an error even though the C and POSIX
+ collations have identical behaviors. Mixing stripped and non-stripped
+ collation names is therefore not recommended.
+
+ With ICU, it is not sensible to enumerate all possible locale names. ICU
+ uses a particular naming system for locales, but there are many more ways
+ to name a locale than there are actually distinct locales.
+ initdb uses the ICU APIs to extract a set of distinct
+ locales to populate the initial set of collations. Collations provided by
+ ICU are created in the SQL environment with names in BCP 47 language tag
+ format, with a “private use”
+ extension -x-icu appended, to distinguish them from
+ libc locales.
+
+ Here are some example collations that might be created:
+
+
+ ICU “root” collation. Use this to get a reasonable
+ language-agnostic sort order.
+
+
+ Some (less frequently used) encodings are not supported by ICU. When the
+ database encoding is one of these, ICU collation entries
+ in pg_collation are ignored. Attempting to use one
+ will draw an error along the lines of “collation "de-x-icu" for
+ encoding "WIN874" does not exist”.
+
+ If the standard and predefined collations are not sufficient, users can
+ create their own collation objects using the SQL
+ command CREATE COLLATION.
+
+ The standard and predefined collations are in the
+ schema pg_catalog, like all predefined objects.
+ User-defined collations should be created in user schemas. This also
+ ensures that they are saved by pg_dump.
+
+CREATE COLLATION german (provider = libc, locale = 'de_DE');
+
+ The exact values that are acceptable for the locale
+ clause in this command depend on the operating system. On Unix-like
+ systems, the command locale -a will show a list.
+
+ Since the predefined libc collations already include all collations
+ defined in the operating system when the database instance is
+ initialized, it is not often necessary to manually create new ones.
+ Reasons might be if a different naming system is desired (in which case
+ see also Section 24.2.2.3.3) or if the operating system has
+ been upgraded to provide new locale definitions (in which case see
+ also pg_import_system_collations()).
+
+CREATE COLLATION german (provider = icu, locale = 'de-DE');
+
+
+ ICU locales are specified as a BCP 47 Language Tag, but can also accept most
+ libc-style locale names. If possible, libc-style locale names are
+ transformed into language tags.
+
+ New ICU collations can customize collation behavior extensively by
+ including collation attributes in the language tag. See Section 24.2.3 for details and examples.
+
+ The command CREATE COLLATION can also be used to
+ create a new collation from an existing collation, which can be useful to
+ be able to use operating-system-independent collation names in
+ applications, create compatibility names, or use an ICU-provided collation
+ under a more readable name. For example:
+
+CREATE COLLATION german FROM "de_DE";
+CREATE COLLATION french FROM "fr-x-icu";
+
+ A collation is either deterministic or
+ nondeterministic. A deterministic collation uses
+ deterministic comparisons, which means that it considers strings to be
+ equal only if they consist of the same byte sequence. Nondeterministic
+ comparison may determine strings to be equal even if they consist of
+ different bytes. Typical situations include case-insensitive comparison,
+ accent-insensitive comparison, as well as comparison of strings in
+ different Unicode normal forms. It is up to the collation provider to
+ actually implement such insensitive comparisons; the deterministic flag
+ only determines whether ties are to be broken using bytewise comparison.
+ See also Unicode Technical
+ Standard 10 for more information on the terminology.
+
+ To create a nondeterministic collation, specify the property
+ deterministic = false to CREATE
+ COLLATION, for example:
+
+ This example would use the standard Unicode collation in a
+ nondeterministic way. In particular, this would allow strings in
+ different normal forms to be compared correctly. More interesting
+ examples make use of the ICU customization facilities explained above.
+ For example:
+
+ All standard and predefined collations are deterministic, all
+ user-defined collations are deterministic by default. While
+ nondeterministic collations give a more “correct” behavior,
+ especially when considering the full power of Unicode and its many
+ special cases, they also have some drawbacks. Foremost, their use leads
+ to a performance penalty. Note, in particular, that B-tree cannot use
+ deduplication with indexes that use a nondeterministic collation. Also,
+ certain operations are not possible with nondeterministic collations,
+ such as pattern matching operations. Therefore, they should be used
+ only in cases where they are specifically wanted.
+
Tip
+ To deal with text in different Unicode normalization forms, it is also
+ an option to use the functions/expressions
+ normalize and is normalized to
+ preprocess or check the strings, instead of using nondeterministic
+ collations. There are different trade-offs for each approach.
+
+ ICU allows extensive control over collation behavior by defining new
+ collations with collation settings as a part of the language tag. These
+ settings can modify the collation order to suit a variety of needs. For
+ instance:
+
+
+ Comparison of two strings (collation) in ICU is determined by a
+ multi-level process, where textual features are grouped into
+ "levels". Treatment of each level is controlled by the collation settings. Higher
+ levels correspond to finer textual features.
+
+ Table 24.1 shows which textual feature
+ differences are considered significant when determining equality at the
+ given level. The Unicode character U+2063 is an
+ invisible separator, and as seen in the table, is ignored for at all
+ levels of comparison less than identic.
+
Table 24.1. ICU Collation Levels
Level
Description
'f' = 'f'
'ab' = U&'a\2063b'
'x-y' = 'x_y'
'g' = 'G'
'n' = 'ñ'
'y' = 'z'
level1
Base Character
true
true
true
true
true
false
level2
Accents
true
true
true
true
false
false
level3
Case/Variants
true
true
true
false
false
false
level4
Punctuation
true
true
false
false
false
false
identic
All
true
false
false
false
false
false
+ At every level, even with full normalization off, basic normalization is
+ performed. For example, 'á' may be composed of the
+ code points U&'\0061\0301' or the single code
+ point U&'\00E1', and those sequences will be
+ considered equal even at the identic level. To treat
+ any difference in code point representation as distinct, use a collation
+ created with deterministic set to
+ true.
+
+ Table 24.2 shows the available
+ collation settings, which can be used as part of a language tag to
+ customize a collation.
+
Table 24.2. ICU Collation Settings
Key
Values
Default
Description
co
emoji, phonebk, standard, ...
standard
+ Collation type. See Section 24.2.3.5 for additional options and details.
+
ka
noignore, shifted
noignore
+ If set to shifted, causes some characters
+ (e.g. punctuation or space) to be ignored in comparison. Key
+ ks must be set to level3 or
+ lower to take effect. Set key kv to control which
+ character classes are ignored.
+
kb
true, false
false
+ Backwards comparison for the level 2 differences. For example,
+ locale und-u-kb sorts 'àe'
+ before 'aé'.
+
kc
true, false
false
+
+ Separates case into a "level 2.5" that falls between accents and
+ other level 3 features.
+
+
+ If set to true and ks is set
+ to level1, will ignore accents but take case
+ into account.
+
+
kf
+ upper, lower,
+ false
+
false
+ If set to upper, upper case sorts before lower
+ case. If set to lower, lower case sorts before
+ upper case. If set to false, the sort depends on
+ the rules of the locale.
+
kn
true, false
false
+ If set to true, numbers within a string are
+ treated as a single numeric value rather than a sequence of
+ digits. For example, 'id-45' sorts before
+ 'id-123'.
+
kk
true, false
false
+
+ Enable full normalization; may affect performance. Basic
+ normalization is performed even when set to
+ false. Locales for languages that require full
+ normalization typically enable it by default.
+
+
+ Full normalization is important in some cases, such as when
+ multiple accents are applied to a single character. For example,
+ the code point sequences U&'\0065\0323\0302'
+ and U&'\0065\0302\0323' represent
+ an e with circumflex and dot-below accents
+ applied in different orders. With full normalization
+ on, these code point sequences are treated as equal; otherwise they
+ are unequal.
+
+ Set to one or more of the valid values, or any BCP 47
+ script-id, e.g. latn
+ ("Latin") or grek ("Greek"). Multiple values are
+ separated by "-".
+
+
+ Redefines the ordering of classes of characters; those characters
+ belonging to a class earlier in the list sort before characters
+ belonging to a class later in the list. For instance, the value
+ digit-currency-space (as part of a language tag
+ like und-u-kr-digit-currency-space) sorts
+ punctuation before digits and spaces.
+
+
ks
level1, level2, level3, level4, identic
level3
+ Sensitivity (or "strength") when determining equality, with
+ level1 the least sensitive to differences and
+ identic the most sensitive to differences. See
+ Table 24.1 for details.
+
kv
+ space, punct,
+ symbol, currency
+
punct
+ Classes of characters ignored during comparison at level 3. Setting
+ to a later value includes earlier values;
+ e.g. symbol also includes
+ punct and space in the
+ characters to be ignored. Key ka must be set to
+ shifted and key ks must be set
+ to level3 or lower to take effect.
+
+ Defaults may depend on locale. The above table is not meant to be
+ complete. See Section 24.2.3.5 for additional
+ options and details.
+
Note
+ For many collation settings, you must create the collation with
+ deterministic set to false for the
+ setting to have the desired effect (see Section 24.2.2.4). Additionally, some settings
+ only take effect when the key ka is set to
+ shifted (see Table 24.2).
+
+ With this rule, the letter “W” is sorted after
+ “V”, but is treated as a secondary difference similar to an
+ accent. Rules like this are contained in the locale definitions of some
+ languages. (Of course, if a locale definition already contains the
+ desired rules, then they don't need to be specified again explicitly.)
+
+ Here is a more complex example. The following statement sets up a
+ collation named ebcdic with rules to sort US-ASCII
+ characters in the order of the EBCDIC encoding.
+
+
+ This section (Section 24.2.3) is only a brief
+ overview of ICU behavior and language tags. Refer to the following
+ documents for technical details, additional options, and new behavior:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/color-when.html b/pgsql/doc/postgresql/html/color-when.html
new file mode 100644
index 0000000000000000000000000000000000000000..689883592105ff76d65279fda7beb67670107e5f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/color-when.html
@@ -0,0 +1,15 @@
+
+N.1. When Color is Used
+ To use colorized output, set the environment variable
+ PG_COLOR
+ as follows:
+
+
+ If the value is always, then color is used.
+
+ If the value is auto and the standard error stream
+ is associated with a terminal device, then color is used.
+
+ Otherwise, color is not used.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/color-which.html b/pgsql/doc/postgresql/html/color-which.html
new file mode 100644
index 0000000000000000000000000000000000000000..e46d02943e521db15f2d6f48f40c8413545a3352
--- /dev/null
+++ b/pgsql/doc/postgresql/html/color-which.html
@@ -0,0 +1,26 @@
+
+N.2. Configuring the Colors
+ The actual colors to be used are configured using the environment variable
+ PG_COLORS
+ (note plural). The value is a colon-separated list of
+ key=value
+ pairs. The keys specify what the color is to be used for. The values are
+ SGR (Select Graphic Rendition) specifications, which are interpreted by the
+ terminal.
+
+ The following keys are currently in use:
+
error
used to highlight the text “error” in error messages
warning
used to highlight the text “warning” in warning
+ messages
note
used to highlight the text “detail” and
+ “hint” in such messages
locus
used to highlight location information (e.g., program name and
+ file name) in messages
+
+ The default value is
+ error=01;31:warning=01;35:note=01;36:locus=01
+ (01;31 = bold red, 01;35 = bold
+ magenta, 01;36 = bold cyan, 01 = bold
+ default color).
+
Tip
+ This color specification format is also used by other software packages
+ such as GCC, GNU
+ coreutils, and GNU grep.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/color.html b/pgsql/doc/postgresql/html/color.html
new file mode 100644
index 0000000000000000000000000000000000000000..d1ddaafefcd08190fb055177b93a894168fa7e16
--- /dev/null
+++ b/pgsql/doc/postgresql/html/color.html
@@ -0,0 +1,5 @@
+
+Appendix N. Color Support
+ Most programs in the PostgreSQL package can produce colorized console
+ output. This appendix describes how that is configured.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/config-setting.html b/pgsql/doc/postgresql/html/config-setting.html
new file mode 100644
index 0000000000000000000000000000000000000000..f0a9b8eb3814b6c41a4ef45610ba6dd5af517d3c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/config-setting.html
@@ -0,0 +1,336 @@
+
+20.1. Setting Parameters
+ All parameter names are case-insensitive. Every parameter takes a
+ value of one of five types: boolean, string, integer, floating point,
+ or enumerated (enum). The type determines the syntax for setting the
+ parameter:
+
+ Boolean:
+ Values can be written as
+ on,
+ off,
+ true,
+ false,
+ yes,
+ no,
+ 1,
+ 0
+ (all case-insensitive) or any unambiguous prefix of one of these.
+
+ String:
+ In general, enclose the value in single quotes, doubling any single
+ quotes within the value. Quotes can usually be omitted if the value
+ is a simple number or identifier, however.
+ (Values that match an SQL keyword require quoting in some contexts.)
+
+ Numeric (integer and floating point):
+ Numeric parameters can be specified in the customary integer and
+ floating-point formats; fractional values are rounded to the nearest
+ integer if the parameter is of integer type. Integer parameters
+ additionally accept hexadecimal input (beginning
+ with 0x) and octal input (beginning
+ with 0), but these formats cannot have a fraction.
+ Do not use thousands separators.
+ Quotes are not required, except for hexadecimal input.
+
+ Numeric with Unit:
+ Some numeric parameters have an implicit unit, because they describe
+ quantities of memory or time. The unit might be bytes, kilobytes, blocks
+ (typically eight kilobytes), milliseconds, seconds, or minutes.
+ An unadorned numeric value for one of these settings will use the
+ setting's default unit, which can be learned from
+ pg_settings.unit.
+ For convenience, settings can be given with a unit specified explicitly,
+ for example '120 ms' for a time value, and they will be
+ converted to whatever the parameter's actual unit is. Note that the
+ value must be written as a string (with quotes) to use this feature.
+ The unit name is case-sensitive, and there can be whitespace between
+ the numeric value and the unit.
+
+
+ Valid memory units are B (bytes),
+ kB (kilobytes),
+ MB (megabytes), GB
+ (gigabytes), and TB (terabytes).
+ The multiplier for memory units is 1024, not 1000.
+
+ Valid time units are
+ us (microseconds),
+ ms (milliseconds),
+ s (seconds), min (minutes),
+ h (hours), and d (days).
+
+
+ If a fractional value is specified with a unit, it will be rounded
+ to a multiple of the next smaller unit if there is one.
+ For example, 30.1 GB will be converted
+ to 30822 MB not 32319628902 B.
+ If the parameter is of integer type, a final rounding to integer
+ occurs after any unit conversion.
+
+ Enumerated:
+ Enumerated-type parameters are written in the same way as string
+ parameters, but are restricted to have one of a limited set of
+ values. The values allowable for such a parameter can be found from
+ pg_settings.enumvals.
+ Enum parameter values are case-insensitive.
+
20.1.2. Parameter Interaction via the Configuration File #
+ The most fundamental way to set these parameters is to edit the file
+ postgresql.conf,
+ which is normally kept in the data directory. A default copy is
+ installed when the database cluster directory is initialized.
+ An example of what this file might look like is:
+
+# This is a comment
+log_connections = yes
+log_destination = 'syslog'
+search_path = '"$user", public'
+shared_buffers = 128MB
+
+ One parameter is specified per line. The equal sign between name and
+ value is optional. Whitespace is insignificant (except within a quoted
+ parameter value) and blank lines are
+ ignored. Hash marks (#) designate the remainder
+ of the line as a comment. Parameter values that are not simple
+ identifiers or numbers must be single-quoted. To embed a single
+ quote in a parameter value, write either two quotes (preferred)
+ or backslash-quote.
+ If the file contains multiple entries for the same parameter,
+ all but the last one are ignored.
+
+ Parameters set in this way provide default values for the cluster.
+ The settings seen by active sessions will be these values unless they
+ are overridden. The following sections describe ways in which the
+ administrator or user can override these defaults.
+
+
+ The configuration file is reread whenever the main server process
+ receives a SIGHUP signal; this signal is most easily
+ sent by running pg_ctl reload from the command line or by
+ calling the SQL function pg_reload_conf(). The main
+ server process also propagates this signal to all currently running
+ server processes, so that existing sessions also adopt the new values
+ (this will happen after they complete any currently-executing client
+ command). Alternatively, you can
+ send the signal to a single server process directly. Some parameters
+ can only be set at server start; any changes to their entries in the
+ configuration file will be ignored until the server is restarted.
+ Invalid parameter settings in the configuration file are likewise
+ ignored (but logged) during SIGHUP processing.
+
+ In addition to postgresql.conf,
+ a PostgreSQL data directory contains a file
+ postgresql.auto.conf,
+ which has the same format as postgresql.conf but
+ is intended to be edited automatically, not manually. This file holds
+ settings provided through the ALTER SYSTEM command.
+ This file is read whenever postgresql.conf is,
+ and its settings take effect in the same way. Settings
+ in postgresql.auto.conf override those
+ in postgresql.conf.
+
+ External tools may also
+ modify postgresql.auto.conf. It is not
+ recommended to do this while the server is running, since a
+ concurrent ALTER SYSTEM command could overwrite
+ such changes. Such tools might simply append new settings to the end,
+ or they might choose to remove duplicate settings and/or comments
+ (as ALTER SYSTEM will).
+
+ The system view
+ pg_file_settings
+ can be helpful for pre-testing changes to the configuration files, or for
+ diagnosing problems if a SIGHUP signal did not have the
+ desired effects.
+
+ PostgreSQL provides three SQL
+ commands to establish configuration defaults.
+ The already-mentioned ALTER SYSTEM command
+ provides an SQL-accessible means of changing global defaults; it is
+ functionally equivalent to editing postgresql.conf.
+ In addition, there are two commands that allow setting of defaults
+ on a per-database or per-role basis:
+
+ The ALTER DATABASE command allows global
+ settings to be overridden on a per-database basis.
+
+ The ALTER ROLE command allows both global and
+ per-database settings to be overridden with user-specific values.
+
+ Values set with ALTER DATABASE and ALTER ROLE
+ are applied only when starting a fresh database session. They
+ override values obtained from the configuration files or server
+ command line, and constitute defaults for the rest of the session.
+ Note that some settings cannot be changed after server start, and
+ so cannot be set with these commands (or the ones listed below).
+
+ Once a client is connected to the database, PostgreSQL
+ provides two additional SQL commands (and equivalent functions) to
+ interact with session-local configuration settings:
+
+ The SHOW command allows inspection of the
+ current value of any parameter. The corresponding SQL function is
+ current_setting(setting_name text)
+ (see Section 9.27.1).
+
+ The SET command allows modification of the
+ current value of those parameters that can be set locally to a
+ session; it has no effect on other sessions.
+ Many parameters can be set this way by any user, but some can
+ only be set by superusers and users who have been
+ granted SET privilege on that parameter.
+ The corresponding SQL function is
+ set_config(setting_name, new_value, is_local)
+ (see Section 9.27.1).
+
+ In addition, the system view pg_settings can be
+ used to view and change session-local values:
+
+ Querying this view is similar to using SHOW ALL but
+ provides more detail. It is also more flexible, since it's possible
+ to specify filter conditions or join against other relations.
+
+ Using UPDATE on this view, specifically
+ updating the setting column, is the equivalent
+ of issuing SET commands. For example, the equivalent of
+
+SET configuration_parameter TO DEFAULT;
+
+ is:
+
+UPDATE pg_settings SET setting = reset_val WHERE name = 'configuration_parameter';
+
+ In addition to setting global defaults or attaching
+ overrides at the database or role level, you can pass settings to
+ PostgreSQL via shell facilities.
+ Both the server and libpq client library
+ accept parameter values via the shell.
+
+ During server startup, parameter settings can be
+ passed to the postgres command via the
+ -c command-line parameter. For example,
+
+ Settings provided in this way override those set via
+ postgresql.conf or ALTER SYSTEM,
+ so they cannot be changed globally without restarting the server.
+
+ When starting a client session via libpq,
+ parameter settings can be
+ specified using the PGOPTIONS environment variable.
+ Settings established in this way constitute defaults for the life
+ of the session, but do not affect other sessions.
+ For historical reasons, the format of PGOPTIONS is
+ similar to that used when launching the postgres
+ command; specifically, the -c flag must be specified.
+ For example,
+
+ Other clients and libraries might provide their own mechanisms,
+ via the shell or otherwise, that allow the user to alter session
+ settings without direct use of SQL commands.
+
+ PostgreSQL provides several features for breaking
+ down complex postgresql.conf files into sub-files.
+ These features are especially useful when managing multiple servers
+ with related, but not identical, configurations.
+
+
+ In addition to individual parameter settings,
+ the postgresql.conf file can contain include
+ directives, which specify another file to read and process as if
+ it were inserted into the configuration file at this point. This
+ feature allows a configuration file to be divided into physically
+ separate parts. Include directives simply look like:
+
+include 'filename'
+
+ If the file name is not an absolute path, it is taken as relative to
+ the directory containing the referencing configuration file.
+ Inclusions can be nested.
+
+
+ There is also an include_if_exists directive, which acts
+ the same as the include directive, except
+ when the referenced file does not exist or cannot be read. A regular
+ include will consider this an error condition, but
+ include_if_exists merely logs a message and continues
+ processing the referencing configuration file.
+
+
+ The postgresql.conf file can also contain
+ include_dir directives, which specify an entire
+ directory of configuration files to include. These look like
+
+include_dir 'directory'
+
+ Non-absolute directory names are taken as relative to the directory
+ containing the referencing configuration file. Within the specified
+ directory, only non-directory files whose names end with the
+ suffix .conf will be included. File names that
+ start with the . character are also ignored, to
+ prevent mistakes since such files are hidden on some platforms. Multiple
+ files within an include directory are processed in file name order
+ (according to C locale rules, i.e., numbers before letters, and
+ uppercase letters before lowercase ones).
+
+ Include files or directories can be used to logically separate portions
+ of the database configuration, rather than having a single large
+ postgresql.conf file. Consider a company that has two
+ database servers, each with a different amount of memory. There are
+ likely elements of the configuration both will share, for things such
+ as logging. But memory-related parameters on the server will vary
+ between the two. And there might be server specific customizations,
+ too. One way to manage this situation is to break the custom
+ configuration changes for your site into three files. You could add
+ this to the end of your postgresql.conf file to include
+ them:
+
+ All systems would have the same shared.conf. Each
+ server with a particular amount of memory could share the
+ same memory.conf; you might have one for all servers
+ with 8GB of RAM, another for those having 16GB. And
+ finally server.conf could have truly server-specific
+ configuration information in it.
+
+ Another possibility is to create a configuration file directory and
+ put this information into files there. For example, a conf.d
+ directory could be referenced at the end of postgresql.conf:
+
+include_dir 'conf.d'
+
+ Then you could name the files in the conf.d directory
+ like this:
+
+00shared.conf
+01memory.conf
+02server.conf
+
+ This naming convention establishes a clear order in which these
+ files will be loaded. This is important because only the last
+ setting encountered for a particular parameter while the server is
+ reading configuration files will be used. In this example,
+ something set in conf.d/02server.conf would override a
+ value set in conf.d/01memory.conf.
+
+ You might instead use this approach to naming the files
+ descriptively:
+
+ This sort of arrangement gives a unique name for each configuration file
+ variation. This can help eliminate ambiguity when several servers have
+ their configurations all stored in one place, such as in a version
+ control repository. (Storing database configuration files under version
+ control is another good practice to consider.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/connect-estab.html b/pgsql/doc/postgresql/html/connect-estab.html
new file mode 100644
index 0000000000000000000000000000000000000000..8704d250ea7c9a5103bd81c79190c7913706a8e7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/connect-estab.html
@@ -0,0 +1,36 @@
+
+52.2. How Connections Are Established
+ PostgreSQL implements a
+ “process per user” client/server model.
+ In this model, every
+ client process
+ connects to exactly one
+ backend process.
+ As we do not know ahead of time how many connections will be made,
+ we have to use a “supervisor process” that spawns a new
+ backend process every time a connection is requested. This supervisor
+ process is called
+ postmaster
+ and listens at a specified TCP/IP port for incoming connections.
+ Whenever it detects a request for a connection, it spawns a new
+ backend process. Those backend processes communicate with each
+ other and with other processes of the
+ instance
+ using semaphores and
+ shared memory
+ to ensure data integrity throughout concurrent data access.
+
+ The client process can be any program that understands the
+ PostgreSQL protocol described in
+ Chapter 55. Many clients are based on the
+ C-language library libpq, but several independent
+ implementations of the protocol exist, such as the Java
+ JDBC driver.
+
+ Once a connection is established, the client process can send a query
+ to the backend process it's connected to. The query is transmitted using
+ plain text, i.e., there is no parsing done in the client. The backend
+ process parses the query, creates an execution plan,
+ executes the plan, and returns the retrieved rows to the client
+ by transmitting them over the established connection.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/continuous-archiving.html b/pgsql/doc/postgresql/html/continuous-archiving.html
new file mode 100644
index 0000000000000000000000000000000000000000..8cb5dc6113d8f98c85e61b503252f21f35f0cb16
--- /dev/null
+++ b/pgsql/doc/postgresql/html/continuous-archiving.html
@@ -0,0 +1,775 @@
+
+26.3. Continuous Archiving and Point-in-Time Recovery (PITR)
26.3. Continuous Archiving and Point-in-Time Recovery (PITR)
+ At all times, PostgreSQL maintains a
+ write ahead log (WAL) in the pg_wal/
+ subdirectory of the cluster's data directory. The log records
+ every change made to the database's data files. This log exists
+ primarily for crash-safety purposes: if the system crashes, the
+ database can be restored to consistency by “replaying” the
+ log entries made since the last checkpoint. However, the existence
+ of the log makes it possible to use a third strategy for backing up
+ databases: we can combine a file-system-level backup with backup of
+ the WAL files. If recovery is needed, we restore the file system backup and
+ then replay from the backed-up WAL files to bring the system to a
+ current state. This approach is more complex to administer than
+ either of the previous approaches, but it has some significant
+ benefits:
+
+ We do not need a perfectly consistent file system backup as the starting point.
+ Any internal inconsistency in the backup will be corrected by log
+ replay (this is not significantly different from what happens during
+ crash recovery). So we do not need a file system snapshot capability,
+ just tar or a similar archiving tool.
+
+ Since we can combine an indefinitely long sequence of WAL files
+ for replay, continuous backup can be achieved simply by continuing to archive
+ the WAL files. This is particularly valuable for large databases, where
+ it might not be convenient to take a full backup frequently.
+
+ It is not necessary to replay the WAL entries all the
+ way to the end. We could stop the replay at any point and have a
+ consistent snapshot of the database as it was at that time. Thus,
+ this technique supports point-in-time recovery: it is
+ possible to restore the database to its state at any time since your base
+ backup was taken.
+
+ If we continuously feed the series of WAL files to another
+ machine that has been loaded with the same base backup file, we
+ have a warm standby system: at any point we can bring up
+ the second machine and it will have a nearly-current copy of the
+ database.
+
+
Note
+ pg_dump and
+ pg_dumpall do not produce file-system-level
+ backups and cannot be used as part of a continuous-archiving solution.
+ Such dumps are logical and do not contain enough
+ information to be used by WAL replay.
+
+ As with the plain file-system-backup technique, this method can only
+ support restoration of an entire database cluster, not a subset.
+ Also, it requires a lot of archival storage: the base backup might be bulky,
+ and a busy system will generate many megabytes of WAL traffic that
+ have to be archived. Still, it is the preferred backup technique in
+ many situations where high reliability is needed.
+
+ To recover successfully using continuous archiving (also called
+ “online backup” by many database vendors), you need a continuous
+ sequence of archived WAL files that extends back at least as far as the
+ start time of your backup. So to get started, you should set up and test
+ your procedure for archiving WAL files before you take your
+ first base backup. Accordingly, we first discuss the mechanics of
+ archiving WAL files.
+
+ In an abstract sense, a running PostgreSQL system
+ produces an indefinitely long sequence of WAL records. The system
+ physically divides this sequence into WAL segment
+ files, which are normally 16MB apiece (although the segment size
+ can be altered during initdb). The segment
+ files are given numeric names that reflect their position in the
+ abstract WAL sequence. When not using WAL archiving, the system
+ normally creates just a few segment files and then
+ “recycles” them by renaming no-longer-needed segment files
+ to higher segment numbers. It's assumed that segment files whose
+ contents precede the last checkpoint are no longer of
+ interest and can be recycled.
+
+ When archiving WAL data, we need to capture the contents of each segment
+ file once it is filled, and save that data somewhere before the segment
+ file is recycled for reuse. Depending on the application and the
+ available hardware, there could be many different ways of “saving
+ the data somewhere”: we could copy the segment files to an NFS-mounted
+ directory on another machine, write them onto a tape drive (ensuring that
+ you have a way of identifying the original name of each file), or batch
+ them together and burn them onto CDs, or something else entirely. To
+ provide the database administrator with flexibility,
+ PostgreSQL tries not to make any assumptions about how
+ the archiving will be done. Instead, PostgreSQL lets
+ the administrator specify a shell command or an archive library to be executed to copy a
+ completed segment file to wherever it needs to go. This could be as simple
+ as a shell command that uses cp, or it could invoke a
+ complex C function — it's all up to you.
+
+ To enable WAL archiving, set the wal_level
+ configuration parameter to replica or higher,
+ archive_mode to on,
+ specify the shell command to use in the archive_command configuration parameter
+ or specify the library to use in the archive_library configuration parameter. In practice
+ these settings will always be placed in the
+ postgresql.conf file.
+
+ In archive_command,
+ %p is replaced by the path name of the file to
+ archive, while %f is replaced by only the file name.
+ (The path name is relative to the current working directory,
+ i.e., the cluster's data directory.)
+ Use %% if you need to embed an actual %
+ character in the command. The simplest useful command is something
+ like:
+
+ which will copy archivable WAL segments to the directory
+ /mnt/server/archivedir. (This is an example, not a
+ recommendation, and might not work on all platforms.) After the
+ %p and %f parameters have been replaced,
+ the actual command executed might look like this:
+
+ A similar command will be generated for each new file to be archived.
+
+ The archive command will be executed under the ownership of the same
+ user that the PostgreSQL server is running as. Since
+ the series of WAL files being archived contains effectively everything
+ in your database, you will want to be sure that the archived data is
+ protected from prying eyes; for example, archive into a directory that
+ does not have group or world read access.
+
+ It is important that the archive command return zero exit status if and
+ only if it succeeds. Upon getting a zero result,
+ PostgreSQL will assume that the file has been
+ successfully archived, and will remove or recycle it. However, a nonzero
+ status tells PostgreSQL that the file was not archived;
+ it will try again periodically until it succeeds.
+
+ Another way to archive is to use a custom archive module as the
+ archive_library. Since such modules are written in
+ C, creating your own may require considerably more effort
+ than writing a shell command. However, archive modules can be more
+ performant than archiving via shell, and they will have access to many
+ useful server resources. For more information about archive modules, see
+ Chapter 51.
+
+ When the archive command is terminated by a signal (other than
+ SIGTERM that is used as part of a server
+ shutdown) or an error by the shell with an exit status greater than
+ 125 (such as command not found), or if the archive function emits an
+ ERROR or FATAL, the archiver process
+ aborts and gets restarted by the postmaster. In such cases, the failure is
+ not reported in pg_stat_archiver.
+
+ Archive commands and libraries should generally be designed to refuse to overwrite
+ any pre-existing archive file. This is an important safety feature to
+ preserve the integrity of your archive in case of administrator error
+ (such as sending the output of two different servers to the same archive
+ directory). It is advisable to test your proposed archive library to ensure
+ that it does not overwrite an existing file.
+
+ In rare cases, PostgreSQL may attempt to
+ re-archive a WAL file that was previously archived. For example, if the
+ system crashes before the server makes a durable record of archival
+ success, the server will attempt to archive the file again after
+ restarting (provided archiving is still enabled). When an archive command or library
+ encounters a pre-existing file, it should return a zero status or true, respectively,
+ if the WAL file has identical contents to the pre-existing archive and the
+ pre-existing archive is fully persisted to storage. If a pre-existing
+ file contains different contents than the WAL file being archived, the
+ archive command or library must return a nonzero status or
+ false, respectively.
+
+ The example command above for Unix avoids overwriting a pre-existing archive
+ by including a separate
+ test step. On some Unix platforms, cp has
+ switches such as -i that can be used to do the same thing
+ less verbosely, but you should not rely on these without verifying that
+ the right exit status is returned. (In particular, GNU cp
+ will return status zero when -i is used and the target file
+ already exists, which is not the desired behavior.)
+
+ While designing your archiving setup, consider what will happen if
+ the archive command or library fails repeatedly because some aspect requires
+ operator intervention or the archive runs out of space. For example, this
+ could occur if you write to tape without an autochanger; when the tape
+ fills, nothing further can be archived until the tape is swapped.
+ You should ensure that any error condition or request to a human operator
+ is reported appropriately so that the situation can be
+ resolved reasonably quickly. The pg_wal/ directory will
+ continue to fill with WAL segment files until the situation is resolved.
+ (If the file system containing pg_wal/ fills up,
+ PostgreSQL will do a PANIC shutdown. No committed
+ transactions will be lost, but the database will remain offline until
+ you free some space.)
+
+ The speed of the archive command or library is unimportant as long as it can keep up
+ with the average rate at which your server generates WAL data. Normal
+ operation continues even if the archiving process falls a little behind.
+ If archiving falls significantly behind, this will increase the amount of
+ data that would be lost in the event of a disaster. It will also mean that
+ the pg_wal/ directory will contain large numbers of
+ not-yet-archived segment files, which could eventually exceed available
+ disk space. You are advised to monitor the archiving process to ensure that
+ it is working as you intend.
+
+ In writing your archive command or library, you should assume that the file names to
+ be archived can be up to 64 characters long and can contain any
+ combination of ASCII letters, digits, and dots. It is not necessary to
+ preserve the original relative path (%p) but it is necessary to
+ preserve the file name (%f).
+
+ Note that although WAL archiving will allow you to restore any
+ modifications made to the data in your PostgreSQL database,
+ it will not restore changes made to configuration files (that is,
+ postgresql.conf, pg_hba.conf and
+ pg_ident.conf), since those are edited manually rather
+ than through SQL operations.
+ You might wish to keep the configuration files in a location that will
+ be backed up by your regular file system backup procedures. See
+ Section 20.2 for how to relocate the
+ configuration files.
+
+ The archive command or function is only invoked on completed WAL segments. Hence,
+ if your server generates only little WAL traffic (or has slack periods
+ where it does so), there could be a long delay between the completion
+ of a transaction and its safe recording in archive storage. To put
+ a limit on how old unarchived data can be, you can set
+ archive_timeout to force the server to switch
+ to a new WAL segment file at least that often. Note that archived
+ files that are archived early due to a forced switch are still the same
+ length as completely full files. It is therefore unwise to set a very
+ short archive_timeout — it will bloat your archive
+ storage. archive_timeout settings of a minute or so are
+ usually reasonable.
+
+ Also, you can force a segment switch manually with
+ pg_switch_wal if you want to ensure that a
+ just-finished transaction is archived as soon as possible. Other utility
+ functions related to WAL management are listed in Table 9.91.
+
+ When wal_level is minimal some SQL commands
+ are optimized to avoid WAL logging, as described in Section 14.4.7. If archiving or streaming replication were
+ turned on during execution of one of these statements, WAL would not
+ contain enough information for archive recovery. (Crash recovery is
+ unaffected.) For this reason, wal_level can only be changed at
+ server start. However, archive_command and archive_library can be changed with a
+ configuration file reload. If you are archiving via shell and wish to
+ temporarily stop archiving,
+ one way to do it is to set archive_command to the empty
+ string ('').
+ This will cause WAL files to accumulate in pg_wal/ until a
+ working archive_command is re-established.
+
+ The easiest way to perform a base backup is to use the
+ pg_basebackup tool. It can create
+ a base backup either as regular files or as a tar archive. If more
+ flexibility than pg_basebackup can provide is
+ required, you can also make a base backup using the low level API
+ (see Section 26.3.3).
+
+ It is not necessary to be concerned about the amount of time it takes
+ to make a base backup. However, if you normally run the
+ server with full_page_writes disabled, you might notice a drop
+ in performance while the backup runs since full_page_writes is
+ effectively forced on during backup mode.
+
+ To make use of the backup, you will need to keep all the WAL
+ segment files generated during and after the file system backup.
+ To aid you in doing this, the base backup process
+ creates a backup history file that is immediately
+ stored into the WAL archive area. This file is named after the first
+ WAL segment file that you need for the file system backup.
+ For example, if the starting WAL file is
+ 0000000100001234000055CD the backup history file will be
+ named something like
+ 0000000100001234000055CD.007C9330.backup. (The second
+ part of the file name stands for an exact position within the WAL
+ file, and can ordinarily be ignored.) Once you have safely archived
+ the file system backup and the WAL segment files used during the
+ backup (as specified in the backup history file), all archived WAL
+ segments with names numerically less are no longer needed to recover
+ the file system backup and can be deleted. However, you should
+ consider keeping several backup sets to be absolutely certain that
+ you can recover your data.
+
+ The backup history file is just a small text file. It contains the
+ label string you gave to pg_basebackup, as well as
+ the starting and ending times and WAL segments of the backup.
+ If you used the label to identify the associated dump file,
+ then the archived history file is enough to tell you which dump file to
+ restore.
+
+ Since you have to keep around all the archived WAL files back to your
+ last base backup, the interval between base backups should usually be
+ chosen based on how much storage you want to expend on archived WAL
+ files. You should also consider how long you are prepared to spend
+ recovering, if recovery should be necessary — the system will have to
+ replay all those WAL segments, and that could take awhile if it has
+ been a long time since the last base backup.
+
26.3.3. Making a Base Backup Using the Low Level API #
+ The procedure for making a base backup using the low level
+ APIs contains a few more steps than
+ the pg_basebackup method, but is relatively
+ simple. It is very important that these steps are executed in
+ sequence, and that the success of a step is verified before
+ proceeding to the next step.
+
+ Multiple backups are able to be run concurrently (both those
+ started using this backup API and those started using
+ pg_basebackup).
+
+
+ Ensure that WAL archiving is enabled and working.
+
+ Connect to the server (it does not matter which database) as a user with
+ rights to run pg_backup_start (superuser,
+ or a user who has been granted EXECUTE on the
+ function) and issue the command:
+
+SELECT pg_backup_start(label => 'label', fast => false);
+
+ where label is any string you want to use to uniquely
+ identify this backup operation. The connection
+ calling pg_backup_start must be maintained until the end of
+ the backup, or the backup will be automatically aborted.
+
+ Online backups are always started at the beginning of a checkpoint.
+ By default, pg_backup_start will wait for the next
+ regularly scheduled checkpoint to complete, which may take a long time (see the
+ configuration parameters checkpoint_timeout and
+ checkpoint_completion_target). This is
+ usually preferable as it minimizes the impact on the running system. If you
+ want to start the backup as soon as possible, pass true as
+ the second parameter to pg_backup_start and it will
+ request an immediate checkpoint, which will finish as fast as possible using
+ as much I/O as possible.
+
+ Perform the backup, using any convenient file-system-backup tool
+ such as tar or cpio (not
+ pg_dump or
+ pg_dumpall). It is neither
+ necessary nor desirable to stop normal operation of the database
+ while you do this. See
+ Section 26.3.3.1 for things to
+ consider during this backup.
+
+ In the same connection as before, issue the command:
+
+SELECT * FROM pg_backup_stop(wait_for_archive => true);
+
+ This terminates backup mode. On a primary, it also performs an automatic
+ switch to the next WAL segment. On a standby, it is not possible to
+ automatically switch WAL segments, so you may wish to run
+ pg_switch_wal on the primary to perform a manual
+ switch. The reason for the switch is to arrange for
+ the last WAL segment file written during the backup interval to be
+ ready to archive.
+
+ pg_backup_stop will return one row with three
+ values. The second of these fields should be written to a file named
+ backup_label in the root directory of the backup. The
+ third field should be written to a file named
+ tablespace_map unless the field is empty. These files are
+ vital to the backup working and must be written byte for byte without
+ modification, which may require opening the file in binary mode.
+
+ Once the WAL segment files active during the backup are archived, you are
+ done. The file identified by pg_backup_stop's first return
+ value is the last segment that is required to form a complete set of
+ backup files. On a primary, if archive_mode is enabled and the
+ wait_for_archive parameter is true,
+ pg_backup_stop does not return until the last segment has
+ been archived.
+ On a standby, archive_mode must be always in order
+ for pg_backup_stop to wait.
+ Archiving of these files happens automatically since you have
+ already configured archive_command or archive_library.
+ In most cases this happens quickly, but you are advised to monitor your
+ archive system to ensure there are no delays.
+ If the archive process has fallen behind because of failures of the
+ archive command or library, it will keep retrying
+ until the archive succeeds and the backup is complete.
+ If you wish to place a time limit on the execution of
+ pg_backup_stop, set an appropriate
+ statement_timeout value, but make note that if
+ pg_backup_stop terminates because of this your backup
+ may not be valid.
+
+ If the backup process monitors and ensures that all WAL segment files
+ required for the backup are successfully archived then the
+ wait_for_archive parameter (which defaults to true) can be set
+ to false to have
+ pg_backup_stop return as soon as the stop backup record is
+ written to the WAL. By default, pg_backup_stop will wait
+ until all WAL has been archived, which can take some time. This option
+ must be used with caution: if WAL archiving is not monitored correctly
+ then the backup might not include all of the WAL files and will
+ therefore be incomplete and not able to be restored.
+
+ Some file system backup tools emit warnings or errors
+ if the files they are trying to copy change while the copy proceeds.
+ When taking a base backup of an active database, this situation is normal
+ and not an error. However, you need to ensure that you can distinguish
+ complaints of this sort from real errors. For example, some versions
+ of rsync return a separate exit code for
+ “vanished source files”, and you can write a driver script to
+ accept this exit code as a non-error case. Also, some versions of
+ GNU tar return an error code indistinguishable from
+ a fatal error if a file was truncated while tar was
+ copying it. Fortunately, GNU tar versions 1.16 and
+ later exit with 1 if a file was changed during the backup,
+ and 2 for other errors. With GNU tar version 1.23 and
+ later, you can use the warning options --warning=no-file-changed
+ --warning=no-file-removed to hide the related warning messages.
+
+ Be certain that your backup includes all of the files under
+ the database cluster directory (e.g., /usr/local/pgsql/data).
+ If you are using tablespaces that do not reside underneath this directory,
+ be careful to include them as well (and be sure that your backup
+ archives symbolic links as links, otherwise the restore will corrupt
+ your tablespaces).
+
+ You should, however, omit from the backup the files within the
+ cluster's pg_wal/ subdirectory. This
+ slight adjustment is worthwhile because it reduces the risk
+ of mistakes when restoring. This is easy to arrange if
+ pg_wal/ is a symbolic link pointing to someplace outside
+ the cluster directory, which is a common setup anyway for performance
+ reasons. You might also want to exclude postmaster.pid
+ and postmaster.opts, which record information
+ about the running postmaster, not about the
+ postmaster which will eventually use this backup.
+ (These files can confuse pg_ctl.)
+
+ It is often a good idea to also omit from the backup the files
+ within the cluster's pg_replslot/ directory, so that
+ replication slots that exist on the primary do not become part of the
+ backup. Otherwise, the subsequent use of the backup to create a standby
+ may result in indefinite retention of WAL files on the standby, and
+ possibly bloat on the primary if hot standby feedback is enabled, because
+ the clients that are using those replication slots will still be connecting
+ to and updating the slots on the primary, not the standby. Even if the
+ backup is only intended for use in creating a new primary, copying the
+ replication slots isn't expected to be particularly useful, since the
+ contents of those slots will likely be badly out of date by the time
+ the new primary comes on line.
+
+ The contents of the directories pg_dynshmem/,
+ pg_notify/, pg_serial/,
+ pg_snapshots/, pg_stat_tmp/,
+ and pg_subtrans/ (but not the directories themselves) can be
+ omitted from the backup as they will be initialized on postmaster startup.
+
+ Any file or directory beginning with pgsql_tmp can be
+ omitted from the backup. These files are removed on postmaster start and
+ the directories will be recreated as needed.
+
+ pg_internal.init files can be omitted from the
+ backup whenever a file of that name is found. These files contain
+ relation cache data that is always rebuilt when recovering.
+
+ The backup label
+ file includes the label string you gave to pg_backup_start,
+ as well as the time at which pg_backup_start was run, and
+ the name of the starting WAL file. In case of confusion it is therefore
+ possible to look inside a backup file and determine exactly which
+ backup session the dump file came from. The tablespace map file includes
+ the symbolic link names as they exist in the directory
+ pg_tblspc/ and the full path of each symbolic link.
+ These files are not merely for your information; their presence and
+ contents are critical to the proper operation of the system's recovery
+ process.
+
+ It is also possible to make a backup while the server is
+ stopped. In this case, you obviously cannot use
+ pg_backup_start or pg_backup_stop, and
+ you will therefore be left to your own devices to keep track of which
+ backup is which and how far back the associated WAL files go.
+ It is generally better to follow the continuous archiving procedure above.
+
26.3.4. Recovering Using a Continuous Archive Backup #
+ Okay, the worst has happened and you need to recover from your backup.
+ Here is the procedure:
+
+ Stop the server, if it's running.
+
+ If you have the space to do so,
+ copy the whole cluster data directory and any tablespaces to a temporary
+ location in case you need them later. Note that this precaution will
+ require that you have enough free space on your system to hold two
+ copies of your existing database. If you do not have enough space,
+ you should at least save the contents of the cluster's pg_wal
+ subdirectory, as it might contain WAL files which
+ were not archived before the system went down.
+
+ Remove all existing files and subdirectories under the cluster data
+ directory and under the root directories of any tablespaces you are using.
+
+ Restore the database files from your file system backup. Be sure that they
+ are restored with the right ownership (the database system user, not
+ root!) and with the right permissions. If you are using
+ tablespaces,
+ you should verify that the symbolic links in pg_tblspc/
+ were correctly restored.
+
+ Remove any files present in pg_wal/; these came from the
+ file system backup and are therefore probably obsolete rather than current.
+ If you didn't archive pg_wal/ at all, then recreate
+ it with proper permissions,
+ being careful to ensure that you re-establish it as a symbolic link
+ if you had it set up that way before.
+
+ If you have unarchived WAL segment files that you saved in step 2,
+ copy them into pg_wal/. (It is best to copy them,
+ not move them, so you still have the unmodified files if a
+ problem occurs and you have to start over.)
+
+ Set recovery configuration settings in
+ postgresql.conf (see Section 20.5.5) and create a file
+ recovery.signal in the cluster
+ data directory. You might
+ also want to temporarily modify pg_hba.conf to prevent
+ ordinary users from connecting until you are sure the recovery was successful.
+
+ Start the server. The server will go into recovery mode and
+ proceed to read through the archived WAL files it needs. Should the
+ recovery be terminated because of an external error, the server can
+ simply be restarted and it will continue recovery. Upon completion
+ of the recovery process, the server will remove
+ recovery.signal (to prevent
+ accidentally re-entering recovery mode later) and then
+ commence normal database operations.
+
+ Inspect the contents of the database to ensure you have recovered to
+ the desired state. If not, return to step 1. If all is well,
+ allow your users to connect by restoring pg_hba.conf to normal.
+
+
+ The key part of all this is to set up a recovery configuration that
+ describes how you want to recover and how far the recovery should
+ run. The one thing that you absolutely must specify is the restore_command,
+ which tells PostgreSQL how to retrieve archived
+ WAL file segments. Like the archive_command, this is
+ a shell command string. It can contain %f, which is
+ replaced by the name of the desired WAL file, and %p,
+ which is replaced by the path name to copy the WAL file to.
+ (The path name is relative to the current working directory,
+ i.e., the cluster's data directory.)
+ Write %% if you need to embed an actual %
+ character in the command. The simplest useful command is
+ something like:
+
+ which will copy previously archived WAL segments from the directory
+ /mnt/server/archivedir. Of course, you can use something
+ much more complicated, perhaps even a shell script that requests the
+ operator to mount an appropriate tape.
+
+ It is important that the command return nonzero exit status on failure.
+ The command will be called requesting files that are not
+ present in the archive; it must return nonzero when so asked. This is not
+ an error condition. An exception is that if the command was terminated by
+ a signal (other than SIGTERM, which is used as
+ part of a database server shutdown) or an error by the shell (such as
+ command not found), then recovery will abort and the server will not start
+ up.
+
+ Not all of the requested files will be WAL segment
+ files; you should also expect requests for files with a suffix of
+ .history. Also be aware that
+ the base name of the %p path will be different from
+ %f; do not expect them to be interchangeable.
+
+ WAL segments that cannot be found in the archive will be sought in
+ pg_wal/; this allows use of recent un-archived segments.
+ However, segments that are available from the archive will be used in
+ preference to files in pg_wal/.
+
+ Normally, recovery will proceed through all available WAL segments,
+ thereby restoring the database to the current point in time (or as
+ close as possible given the available WAL segments). Therefore, a normal
+ recovery will end with a “file not found” message, the exact text
+ of the error message depending upon your choice of
+ restore_command. You may also see an error message
+ at the start of recovery for a file named something like
+ 00000001.history. This is also normal and does not
+ indicate a problem in simple recovery situations; see
+ Section 26.3.5 for discussion.
+
+ If you want to recover to some previous point in time (say, right before
+ the junior DBA dropped your main transaction table), just specify the
+ required stopping point. You can specify
+ the stop point, known as the “recovery target”, either by
+ date/time, named restore point or by completion of a specific transaction
+ ID. As of this writing only the date/time and named restore point options
+ are very usable, since there are no tools to help you identify with any
+ accuracy which transaction ID to use.
+
Note
+ The stop point must be after the ending time of the base backup, i.e.,
+ the end time of pg_backup_stop. You cannot use a base backup
+ to recover to a time when that backup was in progress. (To
+ recover to such a time, you must go back to your previous base backup
+ and roll forward from there.)
+
+ If recovery finds corrupted WAL data, recovery will
+ halt at that point and the server will not start. In such a case the
+ recovery process could be re-run from the beginning, specifying a
+ “recovery target” before the point of corruption so that recovery
+ can complete normally.
+ If recovery fails for an external reason, such as a system crash or
+ if the WAL archive has become inaccessible, then the recovery can simply
+ be restarted and it will restart almost from where it failed.
+ Recovery restart works much like checkpointing in normal operation:
+ the server periodically forces all its state to disk, and then updates
+ the pg_control file to indicate that the already-processed
+ WAL data need not be scanned again.
+
+ The ability to restore the database to a previous point in time creates
+ some complexities that are akin to science-fiction stories about time
+ travel and parallel universes. For example, in the original history of the database,
+ suppose you dropped a critical table at 5:15PM on Tuesday evening, but
+ didn't realize your mistake until Wednesday noon.
+ Unfazed, you get out your backup, restore to the point-in-time 5:14PM
+ Tuesday evening, and are up and running. In this history of
+ the database universe, you never dropped the table. But suppose
+ you later realize this wasn't such a great idea, and would like
+ to return to sometime Wednesday morning in the original history.
+ You won't be able
+ to if, while your database was up-and-running, it overwrote some of the
+ WAL segment files that led up to the time you now wish you
+ could get back to. Thus, to avoid this, you need to distinguish the series of
+ WAL records generated after you've done a point-in-time recovery from
+ those that were generated in the original database history.
+
+ To deal with this problem, PostgreSQL has a notion
+ of timelines. Whenever an archive recovery completes,
+ a new timeline is created to identify the series of WAL records
+ generated after that recovery. The timeline
+ ID number is part of WAL segment file names so a new timeline does
+ not overwrite the WAL data generated by previous timelines.
+ For example, in the WAL file name
+ 0000000100001234000055CD, the leading
+ 00000001 is the timeline ID in hexadecimal. (Note that
+ in other contexts, such as server log messages, timeline IDs are
+ usually printed in decimal.)
+
+ It is
+ in fact possible to archive many different timelines. While that might
+ seem like a useless feature, it's often a lifesaver. Consider the
+ situation where you aren't quite sure what point-in-time to recover to,
+ and so have to do several point-in-time recoveries by trial and error
+ until you find the best place to branch off from the old history. Without
+ timelines this process would soon generate an unmanageable mess. With
+ timelines, you can recover to any prior state, including
+ states in timeline branches that you abandoned earlier.
+
+ Every time a new timeline is created, PostgreSQL creates
+ a “timeline history” file that shows which timeline it branched
+ off from and when. These history files are necessary to allow the system
+ to pick the right WAL segment files when recovering from an archive that
+ contains multiple timelines. Therefore, they are archived into the WAL
+ archive area just like WAL segment files. The history files are just
+ small text files, so it's cheap and appropriate to keep them around
+ indefinitely (unlike the segment files which are large). You can, if
+ you like, add comments to a history file to record your own notes about
+ how and why this particular timeline was created. Such comments will be
+ especially valuable when you have a thicket of different timelines as
+ a result of experimentation.
+
+ The default behavior of recovery is to recover to the latest timeline found
+ in the archive. If you wish to recover to the timeline that was current
+ when the base backup was taken or into a specific child timeline (that
+ is, you want to return to some state that was itself generated after a
+ recovery attempt), you need to specify current or the
+ target timeline ID in recovery_target_timeline. You
+ cannot recover into timelines that branched off earlier than the base backup.
+
+ It is possible to use PostgreSQL's backup facilities to
+ produce standalone hot backups. These are backups that cannot be used
+ for point-in-time recovery, yet are typically much faster to backup and
+ restore than pg_dump dumps. (They are also much larger
+ than pg_dump dumps, so in some cases the speed advantage
+ might be negated.)
+
+ As with base backups, the easiest way to produce a standalone
+ hot backup is to use the pg_basebackup
+ tool. If you include the -X parameter when calling
+ it, all the write-ahead log required to use the backup will be
+ included in the backup automatically, and no special action is
+ required to restore the backup.
+
+ Using a separate script file is advisable any time you want to use
+ more than a single command in the archiving process.
+ This allows all complexity to be managed within the script, which
+ can be written in a popular scripting language such as
+ bash or perl.
+
+ Examples of requirements that might be solved within a script include:
+
+ Copying data to secure off-site data storage
+
+ Batching WAL files so that they are transferred every three hours,
+ rather than one at a time
+
+ Interfacing with other backup and recovery software
+
+ Interfacing with monitoring software to report errors
+
+
Tip
+ When using an archive_command script, it's desirable
+ to enable logging_collector.
+ Any messages written to stderr from the script will then
+ appear in the database server log, allowing complex configurations to
+ be diagnosed easily if they fail.
+
+ At this writing, there are several limitations of the continuous archiving
+ technique. These will probably be fixed in future releases:
+
+
+ If a CREATE DATABASE
+ command is executed while a base backup is being taken, and then
+ the template database that the CREATE DATABASE copied
+ is modified while the base backup is still in progress, it is
+ possible that recovery will cause those modifications to be
+ propagated into the created database as well. This is of course
+ undesirable. To avoid this risk, it is best not to modify any
+ template databases while taking a base backup.
+
+ CREATE TABLESPACE
+ commands are WAL-logged with the literal absolute path, and will
+ therefore be replayed as tablespace creations with the same
+ absolute path. This might be undesirable if the WAL is being
+ replayed on a different machine. It can be dangerous even if the
+ WAL is being replayed on the same machine, but into a new data
+ directory: the replay will still overwrite the contents of the
+ original tablespace. To avoid potential gotchas of this sort,
+ the best practice is to take a new base backup after creating or
+ dropping tablespaces.
+
+
+ It should also be noted that the default WAL
+ format is fairly bulky since it includes many disk page snapshots.
+ These page snapshots are designed to support crash recovery, since
+ we might need to fix partially-written disk pages. Depending on
+ your system hardware and software, the risk of partial writes might
+ be small enough to ignore, in which case you can significantly
+ reduce the total volume of archived WAL files by turning off page
+ snapshots using the full_page_writes
+ parameter. (Read the notes and warnings in Chapter 30
+ before you do so.) Turning off page snapshots does not prevent
+ use of the WAL for PITR operations. An area for future
+ development is to compress archived WAL data by removing
+ unnecessary page copies even when full_page_writes is
+ on. In the meantime, administrators might wish to reduce the number
+ of page snapshots included in WAL by increasing the checkpoint
+ interval parameters as much as feasible.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-build-sql-delete.html b/pgsql/doc/postgresql/html/contrib-dblink-build-sql-delete.html
new file mode 100644
index 0000000000000000000000000000000000000000..b9a5155a0afea53b1a82b9bc1757ff4a3f43d705
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-build-sql-delete.html
@@ -0,0 +1,42 @@
+
+dblink_build_sql_delete
+ dblink_build_sql_delete can be useful in doing selective
+ replication of a local table to a remote database. It builds an SQL
+ DELETE command that will delete the row with the given
+ primary key values.
+
Arguments
relname
+ Name of a local relation, for example foo or
+ myschema.mytab. Include double quotes if the
+ name is mixed-case or contains special characters, for
+ example "FooBar"; without quotes, the string
+ will be folded to lower case.
+
primary_key_attnums
+ Attribute numbers (1-based) of the primary key fields,
+ for example 1 2.
+
num_primary_key_atts
+ The number of primary key fields.
+
tgt_pk_att_vals_array
+ Values of the primary key fields to be used in the resulting
+ DELETE command. Each field is represented in text form.
+
Return Value
Returns the requested SQL statement as text.
Notes
+ As of PostgreSQL 9.0, the attribute numbers in
+ primary_key_attnums are interpreted as logical
+ column numbers, corresponding to the column's position in
+ SELECT * FROM relname. Previous versions interpreted the
+ numbers as physical column positions. There is a difference if any
+ column(s) to the left of the indicated column have been dropped during
+ the lifetime of the table.
+
Examples
+SELECT dblink_build_sql_delete('"MyFoo"', '1 2', 2, '{"1", "b"}');
+ dblink_build_sql_delete
+---------------------------------------------
+ DELETE FROM "MyFoo" WHERE f1='1' AND f2='b'
+(1 row)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-build-sql-insert.html b/pgsql/doc/postgresql/html/contrib-dblink-build-sql-insert.html
new file mode 100644
index 0000000000000000000000000000000000000000..4dac057748a790791cf9edb0f66e894c7b762a22
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-build-sql-insert.html
@@ -0,0 +1,52 @@
+
+dblink_build_sql_insert
dblink_build_sql_insert —
+ builds an INSERT statement using a local tuple, replacing the
+ primary key field values with alternative supplied values
+
+ dblink_build_sql_insert can be useful in doing selective
+ replication of a local table to a remote database. It selects a row
+ from the local table based on primary key, and then builds an SQL
+ INSERT command that will duplicate that row, but with
+ the primary key values replaced by the values in the last argument.
+ (To make an exact copy of the row, just specify the same values for
+ the last two arguments.)
+
Arguments
relname
+ Name of a local relation, for example foo or
+ myschema.mytab. Include double quotes if the
+ name is mixed-case or contains special characters, for
+ example "FooBar"; without quotes, the string
+ will be folded to lower case.
+
primary_key_attnums
+ Attribute numbers (1-based) of the primary key fields,
+ for example 1 2.
+
num_primary_key_atts
+ The number of primary key fields.
+
src_pk_att_vals_array
+ Values of the primary key fields to be used to look up the
+ local tuple. Each field is represented in text form.
+ An error is thrown if there is no local row with these
+ primary key values.
+
tgt_pk_att_vals_array
+ Values of the primary key fields to be placed in the resulting
+ INSERT command. Each field is represented in text form.
+
Return Value
Returns the requested SQL statement as text.
Notes
+ As of PostgreSQL 9.0, the attribute numbers in
+ primary_key_attnums are interpreted as logical
+ column numbers, corresponding to the column's position in
+ SELECT * FROM relname. Previous versions interpreted the
+ numbers as physical column positions. There is a difference if any
+ column(s) to the left of the indicated column have been dropped during
+ the lifetime of the table.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-build-sql-update.html b/pgsql/doc/postgresql/html/contrib-dblink-build-sql-update.html
new file mode 100644
index 0000000000000000000000000000000000000000..631dced7e18e8dcdde63e8013dedd76ecbc95c92
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-build-sql-update.html
@@ -0,0 +1,55 @@
+
+dblink_build_sql_update
+ dblink_build_sql_update can be useful in doing selective
+ replication of a local table to a remote database. It selects a row
+ from the local table based on primary key, and then builds an SQL
+ UPDATE command that will duplicate that row, but with
+ the primary key values replaced by the values in the last argument.
+ (To make an exact copy of the row, just specify the same values for
+ the last two arguments.) The UPDATE command always assigns
+ all fields of the row — the main difference between this and
+ dblink_build_sql_insert is that it's assumed that
+ the target row already exists in the remote table.
+
Arguments
relname
+ Name of a local relation, for example foo or
+ myschema.mytab. Include double quotes if the
+ name is mixed-case or contains special characters, for
+ example "FooBar"; without quotes, the string
+ will be folded to lower case.
+
primary_key_attnums
+ Attribute numbers (1-based) of the primary key fields,
+ for example 1 2.
+
num_primary_key_atts
+ The number of primary key fields.
+
src_pk_att_vals_array
+ Values of the primary key fields to be used to look up the
+ local tuple. Each field is represented in text form.
+ An error is thrown if there is no local row with these
+ primary key values.
+
tgt_pk_att_vals_array
+ Values of the primary key fields to be placed in the resulting
+ UPDATE command. Each field is represented in text form.
+
Return Value
Returns the requested SQL statement as text.
Notes
+ As of PostgreSQL 9.0, the attribute numbers in
+ primary_key_attnums are interpreted as logical
+ column numbers, corresponding to the column's position in
+ SELECT * FROM relname. Previous versions interpreted the
+ numbers as physical column positions. There is a difference if any
+ column(s) to the left of the indicated column have been dropped during
+ the lifetime of the table.
+
Examples
+SELECT dblink_build_sql_update('foo', '1 2', 2, '{"1", "a"}', '{"1", "b"}');
+ dblink_build_sql_update
+-------------------------------------------------------------
+ UPDATE foo SET f1='1',f2='b',f3='1' WHERE f1='1' AND f2='b'
+(1 row)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-cancel-query.html b/pgsql/doc/postgresql/html/contrib-dblink-cancel-query.html
new file mode 100644
index 0000000000000000000000000000000000000000..4c94a021650ac10d2cc86abeae6873c786c9e22e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-cancel-query.html
@@ -0,0 +1,19 @@
+
+dblink_cancel_query
dblink_cancel_query — cancels any active query on the named connection
Synopsis
+dblink_cancel_query(text connname) returns text
+
Description
+ dblink_cancel_query attempts to cancel any query that
+ is in progress on the named connection. Note that this is not
+ certain to succeed (since, for example, the remote query might
+ already have finished). A cancel request simply improves the
+ odds that the query will fail soon. You must still complete the
+ normal query protocol, for example by calling
+ dblink_get_result.
+
Arguments
connname
+ Name of the connection to use.
+
Return Value
+ Returns OK if the cancel request has been sent, or
+ the text of an error message on failure.
+
Examples
+SELECT dblink_cancel_query('dtest1');
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-close.html b/pgsql/doc/postgresql/html/contrib-dblink-close.html
new file mode 100644
index 0000000000000000000000000000000000000000..ff4a9b6fff4ab6782b053a46df9f69e0b1ab5df3
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-close.html
@@ -0,0 +1,42 @@
+
+dblink_close
dblink_close — closes a cursor in a remote database
Synopsis
+dblink_close(text cursorname [, bool fail_on_error]) returns text
+dblink_close(text connname, text cursorname [, bool fail_on_error]) returns text
+
Description
+ dblink_close closes a cursor previously opened with
+ dblink_open.
+
Arguments
connname
+ Name of the connection to use; omit this parameter to use the
+ unnamed connection.
+
cursorname
+ The name of the cursor to close.
+
fail_on_error
+ If true (the default when omitted) then an error thrown on the
+ remote side of the connection causes an error to also be thrown
+ locally. If false, the remote error is locally reported as a NOTICE,
+ and the function's return value is set to ERROR.
+
Return Value
+ Returns status, either OK or ERROR.
+
Notes
+ If dblink_open started an explicit transaction block,
+ and this is the last remaining open cursor in this connection,
+ dblink_close will issue the matching COMMIT.
+
Examples
+SELECT dblink_connect('dbname=postgres options=-csearch_path=');
+ dblink_connect
+----------------
+ OK
+(1 row)
+
+SELECT dblink_open('foo', 'select proname, prosrc from pg_proc');
+ dblink_open
+-------------
+ OK
+(1 row)
+
+SELECT dblink_close('foo');
+ dblink_close
+--------------
+ OK
+(1 row)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-connect-u.html b/pgsql/doc/postgresql/html/contrib-dblink-connect-u.html
new file mode 100644
index 0000000000000000000000000000000000000000..2d99c8a29a4e0366fea866d674c2c35208a6b4da
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-connect-u.html
@@ -0,0 +1,29 @@
+
+dblink_connect_u
dblink_connect_u — opens a persistent connection to a remote database, insecurely
Synopsis
+dblink_connect_u(text connstr) returns text
+dblink_connect_u(text connname, text connstr) returns text
+
Description
+ dblink_connect_u() is identical to
+ dblink_connect(), except that it will allow non-superusers
+ to connect using any authentication method.
+
+ If the remote server selects an authentication method that does not
+ involve a password, then impersonation and subsequent escalation of
+ privileges can occur, because the session will appear to have
+ originated from the user as which the local PostgreSQL
+ server runs. Also, even if the remote server does demand a password,
+ it is possible for the password to be supplied from the server
+ environment, such as a ~/.pgpass file belonging to the
+ server's user. This opens not only a risk of impersonation, but the
+ possibility of exposing a password to an untrustworthy remote server.
+ Therefore, dblink_connect_u() is initially
+ installed with all privileges revoked from PUBLIC,
+ making it un-callable except by superusers. In some situations
+ it may be appropriate to grant EXECUTE permission for
+ dblink_connect_u() to specific users who are considered
+ trustworthy, but this should be done with care. It is also recommended
+ that any ~/.pgpass file belonging to the server's user
+ not contain any records specifying a wildcard host name.
+
+ For further details see dblink_connect().
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-connect.html b/pgsql/doc/postgresql/html/contrib-dblink-connect.html
new file mode 100644
index 0000000000000000000000000000000000000000..34e438133e8a78f93d5785a1afa47546a5268969
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-connect.html
@@ -0,0 +1,106 @@
+
+dblink_connect
dblink_connect — opens a persistent connection to a remote database
Synopsis
+dblink_connect(text connstr) returns text
+dblink_connect(text connname, text connstr) returns text
+
Description
+ dblink_connect() establishes a connection to a remote
+ PostgreSQL database. The server and database to
+ be contacted are identified through a standard libpq
+ connection string. Optionally, a name can be assigned to the
+ connection. Multiple named connections can be open at once, but
+ only one unnamed connection is permitted at a time. The connection
+ will persist until closed or until the database session is ended.
+
+ The connection string may also be the name of an existing foreign
+ server. It is recommended to use the foreign-data wrapper
+ dblink_fdw when defining the foreign
+ server. See the example below, as well as
+ CREATE SERVER and
+ CREATE USER MAPPING.
+
Arguments
connname
+ The name to use for this connection; if omitted, an unnamed
+ connection is opened, replacing any existing unnamed connection.
+
connstr
libpq-style connection info string, for example
+ hostaddr=127.0.0.1 port=5432 dbname=mydb user=postgres
+ password=mypasswd options=-csearch_path=.
+ For details see Section 34.1.1.
+ Alternatively, the name of a foreign server.
+
Return Value
+ Returns status, which is always OK (since any error
+ causes the function to throw an error instead of returning).
+
Notes
+ If untrusted users have access to a database that has not adopted a
+ secure schema usage pattern,
+ begin each session by removing publicly-writable schemas from
+ search_path. One could, for example,
+ add options=-csearch_path= to
+ connstr. This consideration is not specific
+ to dblink; it applies to every interface for
+ executing arbitrary SQL commands.
+
+ Only superusers may use dblink_connect to create
+ non-password-authenticated and non-GSSAPI-authenticated connections.
+ If non-superusers need this capability, use
+ dblink_connect_u instead.
+
+ It is unwise to choose connection names that contain equal signs,
+ as this opens a risk of confusion with connection info strings
+ in other dblink functions.
+
Examples
+SELECT dblink_connect('dbname=postgres options=-csearch_path=');
+ dblink_connect
+----------------
+ OK
+(1 row)
+
+SELECT dblink_connect('myconn', 'dbname=postgres options=-csearch_path=');
+ dblink_connect
+----------------
+ OK
+(1 row)
+
+-- FOREIGN DATA WRAPPER functionality
+-- Note: local connection must require password authentication for this to work properly
+-- Otherwise, you will receive the following error from dblink_connect():
+-- ERROR: password is required
+-- DETAIL: Non-superuser cannot connect if the server does not request a password.
+-- HINT: Target server's authentication method must be changed.
+
+CREATE SERVER fdtest FOREIGN DATA WRAPPER dblink_fdw OPTIONS (hostaddr '127.0.0.1', dbname 'contrib_regression');
+
+CREATE USER regress_dblink_user WITH PASSWORD 'secret';
+CREATE USER MAPPING FOR regress_dblink_user SERVER fdtest OPTIONS (user 'regress_dblink_user', password 'secret');
+GRANT USAGE ON FOREIGN SERVER fdtest TO regress_dblink_user;
+GRANT SELECT ON TABLE foo TO regress_dblink_user;
+
+\set ORIGINAL_USER :USER
+\c - regress_dblink_user
+SELECT dblink_connect('myconn', 'fdtest');
+ dblink_connect
+----------------
+ OK
+(1 row)
+
+SELECT * FROM dblink('myconn', 'SELECT * FROM foo') AS t(a int, b text, c text[]);
+ a | b | c
+----+---+---------------
+ 0 | a | {a0,b0,c0}
+ 1 | b | {a1,b1,c1}
+ 2 | c | {a2,b2,c2}
+ 3 | d | {a3,b3,c3}
+ 4 | e | {a4,b4,c4}
+ 5 | f | {a5,b5,c5}
+ 6 | g | {a6,b6,c6}
+ 7 | h | {a7,b7,c7}
+ 8 | i | {a8,b8,c8}
+ 9 | j | {a9,b9,c9}
+ 10 | k | {a10,b10,c10}
+(11 rows)
+
+\c - :ORIGINAL_USER
+REVOKE USAGE ON FOREIGN SERVER fdtest FROM regress_dblink_user;
+REVOKE SELECT ON TABLE foo FROM regress_dblink_user;
+DROP USER MAPPING FOR regress_dblink_user SERVER fdtest;
+DROP USER regress_dblink_user;
+DROP SERVER fdtest;
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-disconnect.html b/pgsql/doc/postgresql/html/contrib-dblink-disconnect.html
new file mode 100644
index 0000000000000000000000000000000000000000..0069cc00b1ce5972572ff77418f9243d04a466f4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-disconnect.html
@@ -0,0 +1,26 @@
+
+dblink_disconnect
dblink_disconnect — closes a persistent connection to a remote database
Synopsis
+dblink_disconnect() returns text
+dblink_disconnect(text connname) returns text
+
Description
+ dblink_disconnect() closes a connection previously opened
+ by dblink_connect(). The form with no arguments closes
+ an unnamed connection.
+
Arguments
connname
+ The name of a named connection to be closed.
+
Return Value
+ Returns status, which is always OK (since any error
+ causes the function to throw an error instead of returning).
+
Examples
+SELECT dblink_disconnect();
+ dblink_disconnect
+-------------------
+ OK
+(1 row)
+
+SELECT dblink_disconnect('myconn');
+ dblink_disconnect
+-------------------
+ OK
+(1 row)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-error-message.html b/pgsql/doc/postgresql/html/contrib-dblink-error-message.html
new file mode 100644
index 0000000000000000000000000000000000000000..765468f810cdc48ccc946d032c2c8f7ba646bc73
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-error-message.html
@@ -0,0 +1,22 @@
+
+dblink_error_message
dblink_error_message — gets last error message on the named connection
Synopsis
+dblink_error_message(text connname) returns text
+
Description
+ dblink_error_message fetches the most recent remote
+ error message for a given connection.
+
Arguments
connname
+ Name of the connection to use.
+
Return Value
+ Returns last error message, or OK if there has been
+ no error in this connection.
+
Notes
+ When asynchronous queries are initiated by
+ dblink_send_query, the error message associated with
+ the connection might not get updated until the server's response message
+ is consumed. This typically means that dblink_is_busy
+ or dblink_get_result should be called prior to
+ dblink_error_message, so that any error generated by
+ the asynchronous query will be visible.
+
Examples
+SELECT dblink_error_message('dtest1');
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-exec.html b/pgsql/doc/postgresql/html/contrib-dblink-exec.html
new file mode 100644
index 0000000000000000000000000000000000000000..77f919fc9cc3bef1bc97baec0909f0c7994c3578
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-exec.html
@@ -0,0 +1,65 @@
+
+dblink_exec
dblink_exec — executes a command in a remote database
Synopsis
+dblink_exec(text connname, text sql [, bool fail_on_error]) returns text
+dblink_exec(text connstr, text sql [, bool fail_on_error]) returns text
+dblink_exec(text sql [, bool fail_on_error]) returns text
+
Description
+ dblink_exec executes a command (that is, any SQL statement
+ that doesn't return rows) in a remote database.
+
+ When two text arguments are given, the first one is first
+ looked up as a persistent connection's name; if found, the command
+ is executed on that connection. If not found, the first argument
+ is treated as a connection info string as for dblink_connect,
+ and the indicated connection is made just for the duration of this command.
+
Arguments
connname
+ Name of the connection to use; omit this parameter to use the
+ unnamed connection.
+
connstr
+ A connection info string, as previously described for
+ dblink_connect.
+
sql
+ The SQL command that you wish to execute in the remote database,
+ for example
+ insert into foo values(0, 'a', '{"a0","b0","c0"}').
+
fail_on_error
+ If true (the default when omitted) then an error thrown on the
+ remote side of the connection causes an error to also be thrown
+ locally. If false, the remote error is locally reported as a NOTICE,
+ and the function's return value is set to ERROR.
+
Return Value
+ Returns status, either the command's status string or ERROR.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-fetch.html b/pgsql/doc/postgresql/html/contrib-dblink-fetch.html
new file mode 100644
index 0000000000000000000000000000000000000000..6cb7e4645229e8444281cae7878cdebd15591c87
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-fetch.html
@@ -0,0 +1,77 @@
+
+dblink_fetch
dblink_fetch — returns rows from an open cursor in a remote database
Synopsis
+dblink_fetch(text cursorname, int howmany [, bool fail_on_error]) returns setof record
+dblink_fetch(text connname, text cursorname, int howmany [, bool fail_on_error]) returns setof record
+
Description
+ dblink_fetch fetches rows from a cursor previously
+ established by dblink_open.
+
Arguments
connname
+ Name of the connection to use; omit this parameter to use the
+ unnamed connection.
+
cursorname
+ The name of the cursor to fetch from.
+
howmany
+ The maximum number of rows to retrieve. The next howmany
+ rows are fetched, starting at the current cursor position, moving
+ forward. Once the cursor has reached its end, no more rows are produced.
+
fail_on_error
+ If true (the default when omitted) then an error thrown on the
+ remote side of the connection causes an error to also be thrown
+ locally. If false, the remote error is locally reported as a NOTICE,
+ and the function returns no rows.
+
Return Value
+ The function returns the row(s) fetched from the cursor. To use this
+ function, you will need to specify the expected set of columns,
+ as previously discussed for dblink.
+
Notes
+ On a mismatch between the number of return columns specified in the
+ FROM clause, and the actual number of columns returned by the
+ remote cursor, an error will be thrown. In this event, the remote cursor
+ is still advanced by as many rows as it would have been if the error had
+ not occurred. The same is true for any other error occurring in the local
+ query after the remote FETCH has been done.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-function.html b/pgsql/doc/postgresql/html/contrib-dblink-function.html
new file mode 100644
index 0000000000000000000000000000000000000000..690ee11de1e8c1bcc0c5e137ec8a0b019d6abbab
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-function.html
@@ -0,0 +1,143 @@
+
+dblink
+dblink(text connname, text sql [, bool fail_on_error]) returns setof record
+dblink(text connstr, text sql [, bool fail_on_error]) returns setof record
+dblink(text sql [, bool fail_on_error]) returns setof record
+
Description
+ dblink executes a query (usually a SELECT,
+ but it can be any SQL statement that returns rows) in a remote database.
+
+ When two text arguments are given, the first one is first
+ looked up as a persistent connection's name; if found, the command
+ is executed on that connection. If not found, the first argument
+ is treated as a connection info string as for dblink_connect,
+ and the indicated connection is made just for the duration of this command.
+
Arguments
connname
+ Name of the connection to use; omit this parameter to use the
+ unnamed connection.
+
connstr
+ A connection info string, as previously described for
+ dblink_connect.
+
sql
+ The SQL query that you wish to execute in the remote database,
+ for example select * from foo.
+
fail_on_error
+ If true (the default when omitted) then an error thrown on the
+ remote side of the connection causes an error to also be thrown
+ locally. If false, the remote error is locally reported as a NOTICE,
+ and the function returns no rows.
+
Return Value
+ The function returns the row(s) produced by the query. Since
+ dblink can be used with any query, it is declared
+ to return record, rather than specifying any particular
+ set of columns. This means that you must specify the expected
+ set of columns in the calling query — otherwise
+ PostgreSQL would not know what to expect.
+ Here is an example:
+
+
+SELECT *
+ FROM dblink('dbname=mydb options=-csearch_path=',
+ 'select proname, prosrc from pg_proc')
+ AS t1(proname name, prosrc text)
+ WHERE proname LIKE 'bytea%';
+
+
+ The “alias” part of the FROM clause must
+ specify the column names and types that the function will return.
+ (Specifying column names in an alias is actually standard SQL
+ syntax, but specifying column types is a PostgreSQL
+ extension.) This allows the system to understand what
+ * should expand to, and what proname
+ in the WHERE clause refers to, in advance of trying
+ to execute the function. At run time, an error will be thrown
+ if the actual query result from the remote database does not
+ have the same number of columns shown in the FROM clause.
+ The column names need not match, however, and dblink
+ does not insist on exact type matches either. It will succeed
+ so long as the returned data strings are valid input for the
+ column type declared in the FROM clause.
+
Notes
+ A convenient way to use dblink with predetermined
+ queries is to create a view.
+ This allows the column type information to be buried in the view,
+ instead of having to spell it out in every query. For example,
+
+
+CREATE VIEW myremote_pg_proc AS
+ SELECT *
+ FROM dblink('dbname=postgres options=-csearch_path=',
+ 'select proname, prosrc from pg_proc')
+ AS t1(proname name, prosrc text);
+
+SELECT * FROM myremote_pg_proc WHERE proname LIKE 'bytea%';
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-get-connections.html b/pgsql/doc/postgresql/html/contrib-dblink-get-connections.html
new file mode 100644
index 0000000000000000000000000000000000000000..107403134ce74a3ffe8569e2acc83026664df518
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-get-connections.html
@@ -0,0 +1,9 @@
+
+dblink_get_connections
dblink_get_connections — returns the names of all open named dblink connections
Synopsis
+dblink_get_connections() returns text[]
+
Description
+ dblink_get_connections returns an array of the names
+ of all open named dblink connections.
+
Return Value
Returns a text array of connection names, or NULL if none.
Examples
+SELECT dblink_get_connections();
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-get-notify.html b/pgsql/doc/postgresql/html/contrib-dblink-get-notify.html
new file mode 100644
index 0000000000000000000000000000000000000000..77ee0ed438b017b59bfc28025a7003a851ad058f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-get-notify.html
@@ -0,0 +1,33 @@
+
+dblink_get_notify
dblink_get_notify — retrieve async notifications on a connection
Synopsis
+dblink_get_notify() returns setof (notify_name text, be_pid int, extra text)
+dblink_get_notify(text connname) returns setof (notify_name text, be_pid int, extra text)
+
Description
+ dblink_get_notify retrieves notifications on either
+ the unnamed connection, or on a named connection if specified.
+ To receive notifications via dblink, LISTEN must
+ first be issued, using dblink_exec.
+ For details see LISTEN and NOTIFY.
+
Arguments
connname
+ The name of a named connection to get notifications on.
+
Return Value
Returns setof (notify_name text, be_pid int, extra text), or an empty set if none.
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-get-pkey.html b/pgsql/doc/postgresql/html/contrib-dblink-get-pkey.html
new file mode 100644
index 0000000000000000000000000000000000000000..b9334dca5a8bf238d176c966bec6e7eb2e6dd2df
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-get-pkey.html
@@ -0,0 +1,43 @@
+
+dblink_get_pkey
+ dblink_get_pkey provides information about the primary
+ key of a relation in the local database. This is sometimes useful
+ in generating queries to be sent to remote databases.
+
Arguments
relname
+ Name of a local relation, for example foo or
+ myschema.mytab. Include double quotes if the
+ name is mixed-case or contains special characters, for
+ example "FooBar"; without quotes, the string
+ will be folded to lower case.
+
Return Value
+ Returns one row for each primary key field, or no rows if the relation
+ has no primary key. The result row type is defined as
+
+
+CREATE TYPE dblink_pkey_results AS (position int, colname text);
+
+
+ The position column simply runs from 1 to N;
+ it is the number of the field within the primary key, not the number
+ within the table's columns.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-get-result.html b/pgsql/doc/postgresql/html/contrib-dblink-get-result.html
new file mode 100644
index 0000000000000000000000000000000000000000..a5ba67e31618473417104d4d59b190a139a96ed8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-get-result.html
@@ -0,0 +1,98 @@
+
+dblink_get_result
+dblink_get_result(text connname [, bool fail_on_error]) returns setof record
+
Description
+ dblink_get_result collects the results of an
+ asynchronous query previously sent with dblink_send_query.
+ If the query is not already completed, dblink_get_result
+ will wait until it is.
+
Arguments
connname
+ Name of the connection to use.
+
fail_on_error
+ If true (the default when omitted) then an error thrown on the
+ remote side of the connection causes an error to also be thrown
+ locally. If false, the remote error is locally reported as a NOTICE,
+ and the function returns no rows.
+
Return Value
+ For an async query (that is, an SQL statement returning rows),
+ the function returns the row(s) produced by the query. To use this
+ function, you will need to specify the expected set of columns,
+ as previously discussed for dblink.
+
+ For an async command (that is, an SQL statement not returning rows),
+ the function returns a single row with a single text column containing
+ the command's status string. It is still necessary to specify that
+ the result will have a single text column in the calling FROM
+ clause.
+
Notes
+ This function must be called if
+ dblink_send_query returned 1.
+ It must be called once for each query
+ sent, and one additional time to obtain an empty set result,
+ before the connection can be used again.
+
+ When using dblink_send_query and
+ dblink_get_result, dblink fetches the entire
+ remote query result before returning any of it to the local query
+ processor. If the query returns a large number of rows, this can result
+ in transient memory bloat in the local session. It may be better to open
+ such a query as a cursor with dblink_open and then fetch a
+ manageable number of rows at a time. Alternatively, use plain
+ dblink(), which avoids memory bloat by spooling large result
+ sets to disk.
+
Examples
+contrib_regression=# SELECT dblink_connect('dtest1', 'dbname=contrib_regression');
+ dblink_connect
+----------------
+ OK
+(1 row)
+
+contrib_regression=# SELECT * FROM
+contrib_regression-# dblink_send_query('dtest1', 'select * from foo where f1 < 3') AS t1;
+ t1
+----
+ 1
+(1 row)
+
+contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
+ f1 | f2 | f3
+----+----+------------
+ 0 | a | {a0,b0,c0}
+ 1 | b | {a1,b1,c1}
+ 2 | c | {a2,b2,c2}
+(3 rows)
+
+contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
+ f1 | f2 | f3
+----+----+----
+(0 rows)
+
+contrib_regression=# SELECT * FROM
+contrib_regression-# dblink_send_query('dtest1', 'select * from foo where f1 < 3; select * from foo where f1 > 6') AS t1;
+ t1
+----
+ 1
+(1 row)
+
+contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
+ f1 | f2 | f3
+----+----+------------
+ 0 | a | {a0,b0,c0}
+ 1 | b | {a1,b1,c1}
+ 2 | c | {a2,b2,c2}
+(3 rows)
+
+contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
+ f1 | f2 | f3
+----+----+---------------
+ 7 | h | {a7,b7,c7}
+ 8 | i | {a8,b8,c8}
+ 9 | j | {a9,b9,c9}
+ 10 | k | {a10,b10,c10}
+(4 rows)
+
+contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
+ f1 | f2 | f3
+----+----+----
+(0 rows)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-is-busy.html b/pgsql/doc/postgresql/html/contrib-dblink-is-busy.html
new file mode 100644
index 0000000000000000000000000000000000000000..3f3186aae7329bc1f286c4f6c0e0f9072ea91c37
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-is-busy.html
@@ -0,0 +1,14 @@
+
+dblink_is_busy
dblink_is_busy — checks if connection is busy with an async query
Synopsis
+dblink_is_busy(text connname) returns int
+
Description
+ dblink_is_busy tests whether an async query is in progress.
+
Arguments
connname
+ Name of the connection to check.
+
Return Value
+ Returns 1 if connection is busy, 0 if it is not busy.
+ If this function returns 0, it is guaranteed that
+ dblink_get_result will not block.
+
Examples
+SELECT dblink_is_busy('dtest1');
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-open.html b/pgsql/doc/postgresql/html/contrib-dblink-open.html
new file mode 100644
index 0000000000000000000000000000000000000000..b5e1ec7037f40e5d44349cbd94e51e5aa39e9cca
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-open.html
@@ -0,0 +1,48 @@
+
+dblink_open
+dblink_open(text cursorname, text sql [, bool fail_on_error]) returns text
+dblink_open(text connname, text cursorname, text sql [, bool fail_on_error]) returns text
+
Description
+ dblink_open() opens a cursor in a remote database.
+ The cursor can subsequently be manipulated with
+ dblink_fetch() and dblink_close().
+
Arguments
connname
+ Name of the connection to use; omit this parameter to use the
+ unnamed connection.
+
cursorname
+ The name to assign to this cursor.
+
sql
+ The SELECT statement that you wish to execute in the remote
+ database, for example select * from pg_class.
+
fail_on_error
+ If true (the default when omitted) then an error thrown on the
+ remote side of the connection causes an error to also be thrown
+ locally. If false, the remote error is locally reported as a NOTICE,
+ and the function's return value is set to ERROR.
+
Return Value
+ Returns status, either OK or ERROR.
+
Notes
+ Since a cursor can only persist within a transaction,
+ dblink_open starts an explicit transaction block
+ (BEGIN) on the remote side, if the remote side was
+ not already within a transaction. This transaction will be
+ closed again when the matching dblink_close is
+ executed. Note that if
+ you use dblink_exec to change data between
+ dblink_open and dblink_close,
+ and then an error occurs or you use dblink_disconnect before
+ dblink_close, your change will be
+ lost because the transaction will be aborted.
+
Examples
+SELECT dblink_connect('dbname=postgres options=-csearch_path=');
+ dblink_connect
+----------------
+ OK
+(1 row)
+
+SELECT dblink_open('foo', 'select proname, prosrc from pg_proc');
+ dblink_open
+-------------
+ OK
+(1 row)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-dblink-send-query.html b/pgsql/doc/postgresql/html/contrib-dblink-send-query.html
new file mode 100644
index 0000000000000000000000000000000000000000..eb14b55562ef2bbff0663b34b92aa699567b2d0c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-dblink-send-query.html
@@ -0,0 +1,24 @@
+
+dblink_send_query
dblink_send_query — sends an async query to a remote database
Synopsis
+dblink_send_query(text connname, text sql) returns int
+
Description
+ dblink_send_query sends a query to be executed
+ asynchronously, that is, without immediately waiting for the result.
+ There must not be an async query already in progress on the
+ connection.
+
+ After successfully dispatching an async query, completion status
+ can be checked with dblink_is_busy, and the results
+ are ultimately collected with dblink_get_result.
+ It is also possible to attempt to cancel an active async query
+ using dblink_cancel_query.
+
Arguments
connname
+ Name of the connection to use.
+
sql
+ The SQL statement that you wish to execute in the remote database,
+ for example select * from pg_class.
+
Return Value
+ Returns 1 if the query was successfully dispatched, 0 otherwise.
+
Examples
+SELECT dblink_send_query('dtest1', 'SELECT * FROM foo WHERE f1 < 3');
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-prog-client.html b/pgsql/doc/postgresql/html/contrib-prog-client.html
new file mode 100644
index 0000000000000000000000000000000000000000..886a8fb823351797498fa847cdf5905b75727d53
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-prog-client.html
@@ -0,0 +1,9 @@
+
+G.1. Client Applications
oid2name — resolve OIDs and file nodes in a PostgreSQL data directory
vacuumlo — remove orphaned large objects from a PostgreSQL database
+ This section covers PostgreSQL client
+ applications in contrib. They can be run from anywhere,
+ independent of where the database server resides. See
+ also PostgreSQL Client Applications for information about client
+ applications that are part of the core PostgreSQL
+ distribution.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-prog-server.html b/pgsql/doc/postgresql/html/contrib-prog-server.html
new file mode 100644
index 0000000000000000000000000000000000000000..77fad4b458ea6cf4c8f6afddc2d56858ddb80d31
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-prog-server.html
@@ -0,0 +1,7 @@
+
+G.2. Server Applications
+ Some applications run on the PostgreSQL server
+ itself. Currently, no such applications are included in the
+ contrib directory. See also PostgreSQL Server Applications for information about server applications that
+ are part of the core PostgreSQL distribution.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-prog.html b/pgsql/doc/postgresql/html/contrib-prog.html
new file mode 100644
index 0000000000000000000000000000000000000000..e99cb2c59beee690560449157640b25188933d81
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-prog.html
@@ -0,0 +1,15 @@
+
+Appendix G. Additional Supplied Programs
+ This appendix and the previous one contain information regarding the modules that
+ can be found in the contrib directory of the
+ PostgreSQL distribution. See Appendix F for
+ more information about the contrib section in general and
+ server extensions and plug-ins found in contrib
+ specifically.
+
+ This appendix covers utility programs found in contrib.
+ Once installed, either from source or a packaging system, they are found in
+ the bin directory of the
+ PostgreSQL installation and can be used like any
+ other program.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib-spi.html b/pgsql/doc/postgresql/html/contrib-spi.html
new file mode 100644
index 0000000000000000000000000000000000000000..8b23c3db3b83a720e0dc37627a2750bf1cca94c4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib-spi.html
@@ -0,0 +1,82 @@
+
+F.41. spi — Server Programming Interface features/examples
F.41. spi — Server Programming Interface features/examples
+ The spi module provides several workable examples
+ of using the Server Programming Interface
+ (SPI) and triggers. While these functions are of
+ some value in
+ their own right, they are even more useful as examples to modify for
+ your own purposes. The functions are general enough to be used
+ with any table, but you have to specify table and field names (as described
+ below) while creating a trigger.
+
+ Each of the groups of functions described below is provided as a
+ separately-installable extension.
+
F.41.1. refint — Functions for Implementing Referential Integrity #
+ check_primary_key() and
+ check_foreign_key() are used to check foreign key constraints.
+ (This functionality is long since superseded by the built-in foreign
+ key mechanism, of course, but the module is still useful as an example.)
+
+ check_primary_key() checks the referencing table.
+ To use, create a BEFORE INSERT OR UPDATE trigger using this
+ function on a table referencing another table. Specify as the trigger
+ arguments: the referencing table's column name(s) which form the foreign
+ key, the referenced table name, and the column names in the referenced table
+ which form the primary/unique key. To handle multiple foreign
+ keys, create a trigger for each reference.
+
+ check_foreign_key() checks the referenced table.
+ To use, create a BEFORE DELETE OR UPDATE trigger using this
+ function on a table referenced by other table(s). Specify as the trigger
+ arguments: the number of referencing tables for which the function has to
+ perform checking, the action if a referencing key is found
+ (cascade — to delete the referencing row,
+ restrict — to abort transaction if referencing keys
+ exist, setnull — to set referencing key fields to null),
+ the triggered table's column names which form the primary/unique key, then
+ the referencing table name and column names (repeated for as many
+ referencing tables as were specified by first argument). Note that the
+ primary/unique key columns should be marked NOT NULL and should have a
+ unique index.
+
+ There are examples in refint.example.
+
F.41.2. autoinc — Functions for Autoincrementing Fields #
+ autoinc() is a trigger that stores the next value of
+ a sequence into an integer field. This has some overlap with the
+ built-in “serial column” feature, but it is not the same:
+ autoinc() will override attempts to substitute a
+ different field value during inserts, and optionally it can be
+ used to increment the field during updates, too.
+
+ To use, create a BEFORE INSERT (or optionally BEFORE
+ INSERT OR UPDATE) trigger using this function. Specify two
+ trigger arguments: the name of the integer column to be modified,
+ and the name of the sequence object that will supply values.
+ (Actually, you can specify any number of pairs of such names, if
+ you'd like to update more than one autoincrementing column.)
+
+ There is an example in autoinc.example.
+
F.41.3. insert_username — Functions for Tracking Who Changed a Table #
+ insert_username() is a trigger that stores the current
+ user's name into a text field. This can be useful for tracking
+ who last modified a particular row within a table.
+
+ To use, create a BEFORE INSERT and/or UPDATE
+ trigger using this function. Specify a single trigger
+ argument: the name of the text column to be modified.
+
+ There is an example in insert_username.example.
+
F.41.4. moddatetime — Functions for Tracking Last Modification Time #
+ moddatetime() is a trigger that stores the current
+ time into a timestamp field. This can be useful for tracking
+ the last modification time of a particular row within a table.
+
+ To use, create a BEFORE UPDATE
+ trigger using this function. Specify a single trigger
+ argument: the name of the column to be modified.
+ The column must be of type timestamp or timestamp with
+ time zone.
+
+ There is an example in moddatetime.example.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/contrib.html b/pgsql/doc/postgresql/html/contrib.html
new file mode 100644
index 0000000000000000000000000000000000000000..97311f1e0c84c38c43da4354f60ef3af413dc3f3
--- /dev/null
+++ b/pgsql/doc/postgresql/html/contrib.html
@@ -0,0 +1,104 @@
+
+Appendix F. Additional Supplied Modules and Extensions
Appendix F. Additional Supplied Modules and Extensions
dblink_get_pkey — returns the positions and field names of a relation's
+ primary key fields
+
dblink_build_sql_insert —
+ builds an INSERT statement using a local tuple, replacing the
+ primary key field values with alternative supplied values
+
dblink_build_sql_delete — builds a DELETE statement using supplied values for primary
+ key field values
+
dblink_build_sql_update — builds an UPDATE statement using a local tuple, replacing
+ the primary key field values with alternative supplied values
+
+ This appendix and the next one contain information on the
+ optional components
+ found in the contrib directory of the
+ PostgreSQL distribution.
+ These include porting tools, analysis utilities,
+ and plug-in features that are not part of the core PostgreSQL system.
+ They are separate mainly
+ because they address a limited audience or are too experimental
+ to be part of the main source tree. This does not preclude their
+ usefulness.
+
+ This appendix covers extensions and other server plug-in module
+ libraries found in
+ contrib. Appendix G covers utility
+ programs.
+
+ When building from the source distribution, these optional
+ components are not built
+ automatically, unless you build the "world" target
+ (see Step 2).
+ You can build and install all of them by running:
+
+make
+make install
+
+ in the contrib directory of a configured source tree;
+ or to build and install
+ just one selected module, do the same in that module's subdirectory.
+ Many of the modules have regression tests, which can be executed by
+ running:
+
+make check
+
+ before installation or
+
+make installcheck
+
+ once you have a PostgreSQL server running.
+
+ If you are using a pre-packaged version of PostgreSQL,
+ these components are typically made available as a separate subpackage,
+ such as postgresql-contrib.
+
+ Many components supply new user-defined functions, operators, or types,
+ packaged as extensions.
+ To make use of one of these extensions, after you have installed the code
+ you need to register the new SQL objects in the database system.
+ This is done by executing
+ a CREATE EXTENSION command. In a fresh database,
+ you can simply do
+
+
+CREATE EXTENSION extension_name;
+
+
+ This command registers the new SQL objects in the current database only,
+ so you need to run it in every database in which you want
+ the extension's facilities to be available. Alternatively, run it in
+ database template1 so that the extension will be copied into
+ subsequently-created databases by default.
+
+ For all extensions, the CREATE EXTENSION command must be
+ run by a database superuser, unless the extension is
+ considered “trusted”. Trusted extensions can be run by any
+ user who has CREATE privilege on the current
+ database. Extensions that are trusted are identified as such in the
+ sections that follow. Generally, trusted extensions are ones that cannot
+ provide access to outside-the-database functionality.
+
+ The following extensions are trusted in a default installation:
+
+
+ Many extensions allow you to install their objects in a schema of your
+ choice. To do that, add SCHEMA
+ schema_name to the CREATE EXTENSION
+ command. By default, the objects will be placed in your current creation
+ target schema, which in turn defaults to public.
+
+ Note, however, that some of these components are not “extensions”
+ in this sense, but are loaded into the server in some other way, for instance
+ by way of
+ shared_preload_libraries. See the documentation of each
+ component for details.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/creating-cluster.html b/pgsql/doc/postgresql/html/creating-cluster.html
new file mode 100644
index 0000000000000000000000000000000000000000..2dd564190fb53acb78bc6a2cbf7385acb279ac7e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/creating-cluster.html
@@ -0,0 +1,203 @@
+
+19.2. Creating a Database Cluster
+ Before you can do anything, you must initialize a database storage
+ area on disk. We call this a database cluster.
+ (The SQL standard uses the term catalog cluster.) A
+ database cluster is a collection of databases that is managed by a
+ single instance of a running database server. After initialization, a
+ database cluster will contain a database named postgres,
+ which is meant as a default database for use by utilities, users and third
+ party applications. The database server itself does not require the
+ postgres database to exist, but many external utility
+ programs assume it exists. There are two more databases created within
+ each cluster during initialization, named template1
+ and template0. As the names suggest, these will be
+ used as templates for subsequently-created databases; they should not be
+ used for actual work. (See Chapter 23 for
+ information about creating new databases within a cluster.)
+
+ In file system terms, a database cluster is a single directory
+ under which all data will be stored. We call this the data
+ directory or data area. It is
+ completely up to you where you choose to store your data. There is no
+ default, although locations such as
+ /usr/local/pgsql/data or
+ /var/lib/pgsql/data are popular.
+ The data directory must be initialized before being used, using the program
+ initdb
+ which is installed with PostgreSQL.
+
+ If you are using a pre-packaged version
+ of PostgreSQL, it may well have a specific
+ convention for where to place the data directory, and it may also
+ provide a script for creating the data directory. In that case you
+ should use that script in preference to
+ running initdb directly.
+ Consult the package-level documentation for details.
+
+ To initialize a database cluster manually,
+ run initdb and specify the desired
+ file system location of the database cluster with the
+ -D option, for example:
+
+$initdb -D /usr/local/pgsql/data
+
+ Note that you must execute this command while logged into the
+ PostgreSQL user account, which is
+ described in the previous section.
+
Tip
+ As an alternative to the -D option, you can set
+ the environment variable PGDATA.
+
+
+ Alternatively, you can run initdb via
+ the pg_ctl
+ program like so:
+
+$pg_ctl -D /usr/local/pgsql/data initdb
+
+ This may be more intuitive if you are
+ using pg_ctl for starting and stopping the
+ server (see Section 19.3), so
+ that pg_ctl would be the sole command you use
+ for managing the database server instance.
+
+ initdb will attempt to create the directory you
+ specify if it does not already exist. Of course, this will fail if
+ initdb does not have permissions to write in the
+ parent directory. It's generally recommendable that the
+ PostgreSQL user own not just the data
+ directory but its parent directory as well, so that this should not
+ be a problem. If the desired parent directory doesn't exist either,
+ you will need to create it first, using root privileges if the
+ grandparent directory isn't writable. So the process might look
+ like this:
+
+ initdb will refuse to run if the data directory
+ exists and already contains files; this is to prevent accidentally
+ overwriting an existing installation.
+
+ Because the data directory contains all the data stored in the
+ database, it is essential that it be secured from unauthorized
+ access. initdb therefore revokes access
+ permissions from everyone but the
+ PostgreSQL user, and optionally, group.
+ Group access, when enabled, is read-only. This allows an unprivileged
+ user in the same group as the cluster owner to take a backup of the
+ cluster data or perform other operations that only require read access.
+
+ Note that enabling or disabling group access on an existing cluster requires
+ the cluster to be shut down and the appropriate mode to be set on all
+ directories and files before restarting
+ PostgreSQL. Otherwise, a mix of modes might
+ exist in the data directory. For clusters that allow access only by the
+ owner, the appropriate modes are 0700 for directories
+ and 0600 for files. For clusters that also allow
+ reads by the group, the appropriate modes are 0750
+ for directories and 0640 for files.
+
+ However, while the directory contents are secure, the default
+ client authentication setup allows any local user to connect to the
+ database and even become the database superuser. If you do not
+ trust other local users, we recommend you use one of
+ initdb's -W, --pwprompt
+ or --pwfile options to assign a password to the
+ database superuser.
+ Also, specify -A scram-sha-256
+ so that the default trust authentication
+ mode is not used; or modify the generated pg_hba.conf
+ file after running initdb, but
+ before you start the server for the first time. (Other
+ reasonable approaches include using peer authentication
+ or file system permissions to restrict connections. See Chapter 21 for more information.)
+
+ initdb also initializes the default
+ locale for the database cluster.
+ Normally, it will just take the locale settings in the environment
+ and apply them to the initialized database. It is possible to
+ specify a different locale for the database; more information about
+ that can be found in Section 24.1. The default sort order used
+ within the particular database cluster is set by
+ initdb, and while you can create new databases using
+ different sort order, the order used in the template databases that initdb
+ creates cannot be changed without dropping and recreating them.
+ There is also a performance impact for using locales
+ other than C or POSIX. Therefore, it is
+ important to make this choice correctly the first time.
+
+ initdb also sets the default character set encoding
+ for the database cluster. Normally this should be chosen to match the
+ locale setting. For details see Section 24.3.
+
+ Non-C and non-POSIX locales rely on the
+ operating system's collation library for character set ordering.
+ This controls the ordering of keys stored in indexes. For this reason,
+ a cluster cannot switch to an incompatible collation library version,
+ either through snapshot restore, binary streaming replication, a
+ different operating system, or an operating system upgrade.
+
+ Many installations create their database clusters on file systems
+ (volumes) other than the machine's “root” volume. If you
+ choose to do this, it is not advisable to try to use the secondary
+ volume's topmost directory (mount point) as the data directory.
+ Best practice is to create a directory within the mount-point
+ directory that is owned by the PostgreSQL
+ user, and then create the data directory within that. This avoids
+ permissions problems, particularly for operations such
+ as pg_upgrade, and it also ensures clean failures if
+ the secondary volume is taken offline.
+
+ Generally, any file system with POSIX semantics can be used for
+ PostgreSQL. Users prefer different file systems for a variety of reasons,
+ including vendor support, performance, and familiarity. Experience
+ suggests that, all other things being equal, one should not expect major
+ performance or behavior changes merely from switching file systems or
+ making minor file system configuration changes.
+
+ It is possible to use an NFS file system for storing
+ the PostgreSQL data directory.
+ PostgreSQL does nothing special for
+ NFS file systems, meaning it assumes
+ NFS behaves exactly like locally-connected drives.
+ PostgreSQL does not use any functionality that
+ is known to have nonstandard behavior on NFS, such as
+ file locking.
+
+ The only firm requirement for using NFS with
+ PostgreSQL is that the file system is mounted
+ using the hard option. With the
+ hard option, processes can “hang”
+ indefinitely if there are network problems, so this configuration will
+ require a careful monitoring setup. The soft option
+ will interrupt system calls in case of network problems, but
+ PostgreSQL will not repeat system calls
+ interrupted in this way, so any such interruption will result in an I/O
+ error being reported.
+
+ It is not necessary to use the sync mount option. The
+ behavior of the async option is sufficient, since
+ PostgreSQL issues fsync
+ calls at appropriate times to flush the write caches. (This is analogous
+ to how it works on a local file system.) However, it is strongly
+ recommended to use the sync export option on the NFS
+ server on systems where it exists (mainly Linux).
+ Otherwise, an fsync or equivalent on the NFS client is
+ not actually guaranteed to reach permanent storage on the server, which
+ could cause corruption similar to running with the parameter fsync off. The defaults of these mount and export
+ options differ between vendors and versions, so it is recommended to
+ check and perhaps specify them explicitly in any case to avoid any
+ ambiguity.
+
+ In some cases, an external storage product can be accessed either via NFS
+ or a lower-level protocol such as iSCSI. In the latter case, the storage
+ appears as a block device and any available file system can be created on
+ it. That approach might relieve the DBA from having to deal with some of
+ the idiosyncrasies of NFS, but of course the complexity of managing
+ remote storage then happens at other levels.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/cube.html b/pgsql/doc/postgresql/html/cube.html
new file mode 100644
index 0000000000000000000000000000000000000000..3c1addf7381abbf4a037735b19d0e420129158e7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/cube.html
@@ -0,0 +1,391 @@
+
+F.11. cube — a multi-dimensional cube data type
+ Table F.2 shows the valid external
+ representations for the cube
+ type. x, y, etc. denote
+ floating-point numbers.
+
Table F.2. Cube External Representations
External Syntax
Meaning
x
A one-dimensional point
+ (or, zero-length one-dimensional interval)
+
(x)
Same as above
x1,x2,...,xn
A point in n-dimensional space, represented internally as a
+ zero-volume cube
+
(x1,x2,...,xn)
Same as above
(x),(y)
A one-dimensional interval starting at x and ending at y or vice versa; the
+ order does not matter
+
[(x),(y)]
Same as above
(x1,...,xn),(y1,...,yn)
An n-dimensional cube represented by a pair of its diagonally
+ opposite corners
+
[(x1,...,xn),(y1,...,yn)]
Same as above
+ It does not matter which order the opposite corners of a cube are
+ entered in. The cube functions
+ automatically swap values if needed to create a uniform
+ “lower left — upper right” internal representation.
+ When the corners coincide, cube stores only one corner
+ along with an “is point” flag to avoid wasting space.
+
+ White space is ignored on input, so
+ [(x),(y)] is the same as
+ [ ( x ), ( y ) ].
+
+ Values are stored internally as 64-bit floating point numbers. This means
+ that numbers with more than about 16 significant digits will be truncated.
+
+ Table F.3 shows the specialized operators
+ provided for type cube.
+
Table F.3. Cube Operators
+ Operator
+
+
+ Description
+
+ cube&&cube
+ → boolean
+
+
+ Do the cubes overlap?
+
+ cube@>cube
+ → boolean
+
+
+ Does the first cube contain the second?
+
+ cube<@cube
+ → boolean
+
+
+ Is the first cube contained in the second?
+
+ cube->integer
+ → float8
+
+
+ Extracts the n-th coordinate of the cube
+ (counting from 1).
+
+ cube~>integer
+ → float8
+
+
+ Extracts the n-th coordinate of the cube,
+ counting in the following way: n = 2
+ * k - 1 means lower bound
+ of k-th dimension, n = 2
+ * k means upper bound of
+ k-th dimension. Negative
+ n denotes the inverse value of the corresponding
+ positive coordinate. This operator is designed for KNN-GiST support.
+
+ cube<->cube
+ → float8
+
+
+ Computes the Euclidean distance between the two cubes.
+
+ cube<#>cube
+ → float8
+
+
+ Computes the taxicab (L-1 metric) distance between the two cubes.
+
+ cube<=>cube
+ → float8
+
+
+ Computes the Chebyshev (L-inf metric) distance between the two cubes.
+
+ In addition to the above operators, the usual comparison
+ operators shown in Table 9.1 are
+ available for type cube. These
+ operators first compare the first coordinates, and if those are equal,
+ compare the second coordinates, etc. They exist mainly to support the
+ b-tree index operator class for cube, which can be useful for
+ example if you would like a UNIQUE constraint on a cube column.
+ Otherwise, this ordering is not of much practical use.
+
+ The cube module also provides a GiST index operator class for
+ cube values.
+ A cube GiST index can be used to search for values using the
+ =, &&, @>, and
+ <@ operators in WHERE clauses.
+
+ In addition, a cube GiST index can be used to find nearest
+ neighbors using the metric operators
+ <->, <#>, and
+ <=> in ORDER BY clauses.
+ For example, the nearest neighbor of the 3-D point (0.5, 0.5, 0.5)
+ could be found efficiently with:
+
+SELECT c FROM test ORDER BY c <-> cube(array[0.5,0.5,0.5]) LIMIT 1;
+
+
+ The ~> operator can also be used in this way to
+ efficiently retrieve the first few values sorted by a selected coordinate.
+ For example, to get the first few cubes ordered by the first coordinate
+ (lower left corner) ascending one could use the following query:
+
+SELECT c FROM test ORDER BY c ~> 1 LIMIT 5;
+
+ And to get 2-D cubes ordered by the first coordinate of the upper right
+ corner descending:
+
+SELECT c FROM test ORDER BY c ~> 3 DESC LIMIT 5;
+
+ Makes a new cube by adding a dimension on to an existing cube,
+ with the same values for both endpoints of the new coordinate. This
+ is useful for building cubes piece by piece from calculated values.
+
+ Makes a new cube from an existing cube, using a list of
+ dimension indexes from an array. Can be used to extract the endpoints
+ of a single dimension, or to drop dimensions, or to reorder them as
+ desired.
+
+ Increases the size of the cube by the specified
+ radius r in at least n
+ dimensions. If the radius is negative the cube is shrunk instead.
+ All defined dimensions are changed by the
+ radius r. Lower-left coordinates are decreased
+ by r and upper-right coordinates are increased
+ by r. If a lower-left coordinate is increased
+ to more than the corresponding upper-right coordinate (this can only
+ happen when r < 0) than both coordinates are
+ set to their average. If n is greater than the
+ number of defined dimensions and the cube is being enlarged
+ (r > 0), then extra dimensions are added to
+ make n altogether; 0 is used as the initial
+ value for the extra coordinates. This function is useful for creating
+ bounding boxes around a point for searching for nearby points.
+
+ In all binary operations on differently-dimensioned cubes,
+ the lower-dimensional one is assumed to be a Cartesian projection, i. e., having zeroes
+ in place of coordinates omitted in the string representation. The above
+ examples are equivalent to:
+
+ The following containment predicate uses the point syntax,
+ while in fact the second argument is internally represented by a box.
+ This syntax makes it unnecessary to define a separate point type
+ and functions for (box,point) predicates.
+
+ For examples of usage, see the regression test sql/cube.sql.
+
+ To make it harder for people to break things, there
+ is a limit of 100 on the number of dimensions of cubes. This is set
+ in cubedata.h if you need something bigger.
+
+ Original author: Gene Selkov, Jr. <selkovjr@mcs.anl.gov>,
+ Mathematics and Computer Science Division, Argonne National Laboratory.
+
+ My thanks are primarily to Prof. Joe Hellerstein
+ (https://dsf.berkeley.edu/jmh/) for elucidating the
+ gist of the GiST (http://gist.cs.berkeley.edu/), and
+ to his former student Andy Dong for his example written for Illustra.
+ I am also grateful to all Postgres developers, present and past, for
+ enabling myself to create my own world and live undisturbed in it. And I
+ would like to acknowledge my gratitude to Argonne Lab and to the
+ U.S. Department of Energy for the years of faithful support of my database
+ research.
+
+ Minor updates to this package were made by Bruno Wolff III
+ <bruno@wolff.to> in August/September of 2002. These include
+ changing the precision from single precision to double precision and adding
+ some new functions.
+
+ Additional updates were made by Joshua Reich <josh@root.net> in
+ July 2006. These include cube(float8[], float8[]) and
+ cleaning up the code to use the V1 call protocol instead of the deprecated
+ V0 protocol.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/custom-rmgr.html b/pgsql/doc/postgresql/html/custom-rmgr.html
new file mode 100644
index 0000000000000000000000000000000000000000..e2d4a2f9d242d4b1892ee4a80e312397af4fd38c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/custom-rmgr.html
@@ -0,0 +1,85 @@
+
+Chapter 66. Custom WAL Resource Managers
+ This chapter explains the interface between the core
+ PostgreSQL system and custom WAL resource
+ managers, which enable extensions to integrate directly with the WAL.
+
+ An extension, especially a Table Access
+ Method or Index Access Method, may
+ need to use WAL for recovery, replication, and/or Logical Decoding. Custom resource managers
+ are a more flexible alternative to Generic
+ WAL (which does not support logical decoding), but more complex for
+ an extension to implement.
+
+ To create a new custom WAL resource manager, first define an
+ RmgrData structure with implementations for the
+ resource manager methods. Refer to
+ src/backend/access/transam/README and
+ src/include/access/xlog_internal.h in the
+ PostgreSQL source.
+
+/*
+ * Method table for resource managers.
+ *
+ * This struct must be kept in sync with the PG_RMGR definition in
+ * rmgr.c.
+ *
+ * rm_identify must return a name for the record based on xl_info (without
+ * reference to the rmid). For example, XLOG_BTREE_VACUUM would be named
+ * "VACUUM". rm_desc can then be called to obtain additional detail for the
+ * record, if available (e.g. the last block).
+ *
+ * rm_mask takes as input a page modified by the resource manager and masks
+ * out bits that shouldn't be flagged by wal_consistency_checking.
+ *
+ * RmgrTable[] is indexed by RmgrId values (see rmgrlist.h). If rm_name is
+ * NULL, the corresponding RmgrTable entry is considered invalid.
+ */
+typedef struct RmgrData
+{
+ const char *rm_name;
+ void (*rm_redo) (XLogReaderState *record);
+ void (*rm_desc) (StringInfo buf, XLogReaderState *record);
+ const char *(*rm_identify) (uint8 info);
+ void (*rm_startup) (void);
+ void (*rm_cleanup) (void);
+ void (*rm_mask) (char *pagedata, BlockNumber blkno);
+ void (*rm_decode) (struct LogicalDecodingContext *ctx,
+ struct XLogRecordBuffer *buf);
+} RmgrData;
+
+
+ The src/test/modules/test_custom_rmgrs module
+ contains a working example, which demonstrates usage of custom WAL
+ resource managers.
+
+ Then, register your new resource
+ manager.
+
+
+/*
+ * Register a new custom WAL resource manager.
+ *
+ * Resource manager IDs must be globally unique across all extensions. Refer
+ * to https://wiki.postgresql.org/wiki/CustomWALResourceManagers to reserve a
+ * unique RmgrId for your extension, to avoid conflicts with other extension
+ * developers. During development, use RM_EXPERIMENTAL_ID to avoid needlessly
+ * reserving a new ID.
+ */
+extern void RegisterCustomRmgr(RmgrId rmid, const RmgrData *rmgr);
+
+ RegisterCustomRmgr must be called from the
+ extension module's _PG_init function.
+ While developing a new extension, use RM_EXPERIMENTAL_ID
+ for rmid. When you are ready to release the extension
+ to users, reserve a new resource manager ID at the Custom WAL
+ Resource Manager page.
+
+ Place the extension module implementing the custom resource manager in shared_preload_libraries so that it will be loaded early
+ during PostgreSQL startup.
+
Note
+ The extension must remain in shared_preload_libraries as long as any
+ custom WAL records may exist in the system. Otherwise
+ PostgreSQL will not be able to apply or decode
+ the custom WAL records, which may prevent the server from starting.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/custom-scan-execution.html b/pgsql/doc/postgresql/html/custom-scan-execution.html
new file mode 100644
index 0000000000000000000000000000000000000000..511a8d49dd878f12f4259c754f4c2ef43acf043a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/custom-scan-execution.html
@@ -0,0 +1,139 @@
+
+61.3. Executing Custom Scans
+ ss is initialized as for any other scan state,
+ except that if the scan is for a join rather than a base relation,
+ ss.ss_currentRelation is left NULL.
+ flags is a bit mask with the same meaning as in
+ CustomPath and CustomScan.
+ methods must point to a (usually statically allocated)
+ object implementing the required custom scan state methods, which are
+ further detailed below. Typically, a CustomScanState, which
+ need not support copyObject, will actually be a larger
+ structure embedding the above as its first member.
+
+ Complete initialization of the supplied CustomScanState.
+ Standard fields have been initialized by ExecInitCustomScan,
+ but any private fields should be initialized here.
+
+ Fetch the next scan tuple. If any tuples remain, it should fill
+ ps_ResultTupleSlot with the next tuple in the current scan
+ direction, and then return the tuple slot. If not,
+ NULL or an empty slot should be returned.
+
+
+void (*EndCustomScan) (CustomScanState *node);
+
+ Clean up any private data associated with the CustomScanState.
+ This method is required, but it does not need to do anything if there is
+ no associated data or it will be cleaned up automatically.
+
+ Save the current scan position so that it can subsequently be restored
+ by the RestrPosCustomScan callback. This callback is
+ optional, and need only be supplied if the
+ CUSTOMPATH_SUPPORT_MARK_RESTORE flag is set.
+
+ Restore the previous scan position as saved by the
+ MarkPosCustomScan callback. This callback is optional,
+ and need only be supplied if the
+ CUSTOMPATH_SUPPORT_MARK_RESTORE flag is set.
+
+ Estimate the amount of dynamic shared memory that will be required
+ for parallel operation. This may be higher than the amount that will
+ actually be used, but it must not be lower. The return value is in bytes.
+ This callback is optional, and need only be supplied if this custom
+ scan provider supports parallel execution.
+
+ Initialize the dynamic shared memory that will be required for parallel
+ operation. coordinate points to a shared memory area of
+ size equal to the return value of EstimateDSMCustomScan.
+ This callback is optional, and need only be supplied if this custom
+ scan provider supports parallel execution.
+
+ Re-initialize the dynamic shared memory required for parallel operation
+ when the custom-scan plan node is about to be re-scanned.
+ This callback is optional, and need only be supplied if this custom
+ scan provider supports parallel execution.
+ Recommended practice is that this callback reset only shared state,
+ while the ReScanCustomScan callback resets only local
+ state. Currently, this callback will be called
+ before ReScanCustomScan, but it's best not to rely on
+ that ordering.
+
+ Initialize a parallel worker's local state based on the shared state
+ set up by the leader during InitializeDSMCustomScan.
+ This callback is optional, and need only be supplied if this custom
+ scan provider supports parallel execution.
+
+ Release resources when it is anticipated the node will not be executed
+ to completion. This is not called in all cases; sometimes,
+ EndCustomScan may be called without this function having
+ been called first. Since the DSM segment used by parallel query is
+ destroyed just after this callback is invoked, custom scan providers that
+ wish to take some action before the DSM segment goes away should implement
+ this method.
+
+ Output additional information for EXPLAIN of a custom-scan
+ plan node. This callback is optional. Common data stored in the
+ ScanState, such as the target list and scan relation, will
+ be shown even without this callback, but the callback allows the display
+ of additional, private state.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/custom-scan-path.html b/pgsql/doc/postgresql/html/custom-scan-path.html
new file mode 100644
index 0000000000000000000000000000000000000000..72224a01461353229ac3a688e293cecc171b3115
--- /dev/null
+++ b/pgsql/doc/postgresql/html/custom-scan-path.html
@@ -0,0 +1,101 @@
+
+61.1. Creating Custom Scan Paths
+ A custom scan provider will typically add paths for a base relation by
+ setting the following hook, which is called after the core code has
+ generated all the access paths it can for the relation (except for
+ Gather paths, which are made after this call so that they can use
+ partial paths added by the hook):
+
+ Although this hook function can be used to examine, modify, or remove
+ paths generated by the core system, a custom scan provider will typically
+ confine itself to generating CustomPath objects and adding
+ them to rel using add_path. The custom scan
+ provider is responsible for initializing the CustomPath
+ object, which is declared like this:
+
+ path must be initialized as for any other path, including
+ the row-count estimate, start and total cost, and sort ordering provided
+ by this path. flags is a bit mask, which
+ specifies whether the scan provider can support certain optional
+ capabilities. flags should include
+ CUSTOMPATH_SUPPORT_BACKWARD_SCAN if the custom path can support
+ a backward scan, CUSTOMPATH_SUPPORT_MARK_RESTORE if it
+ can support mark and restore,
+ and CUSTOMPATH_SUPPORT_PROJECTION if it can perform
+ projections. (If CUSTOMPATH_SUPPORT_PROJECTION is not
+ set, the scan node will only be asked to produce Vars of the scanned
+ relation; while if that flag is set, the scan node must be able to
+ evaluate scalar expressions over these Vars.)
+ An optional custom_paths is a list of Path
+ nodes used by this custom-path node; these will be transformed into
+ Plan nodes by planner.
+ custom_private can be used to store the custom path's
+ private data. Private data should be stored in a form that can be handled
+ by nodeToString, so that debugging routines that attempt to
+ print the custom path will work as designed. methods must
+ point to a (usually statically allocated) object implementing the required
+ custom path methods, which are further detailed below.
+
+ A custom scan provider can also provide join paths. Just as for base
+ relations, such a path must produce the same output as would normally be
+ produced by the join it replaces. To do this, the join provider should
+ set the following hook, and then within the hook function,
+ create CustomPath path(s) for the join relation.
+
+
+ This hook will be invoked repeatedly for the same join relation, with
+ different combinations of inner and outer relations; it is the
+ responsibility of the hook to minimize duplicated work.
+
+Plan *(*PlanCustomPath) (PlannerInfo *root,
+ RelOptInfo *rel,
+ CustomPath *best_path,
+ List *tlist,
+ List *clauses,
+ List *custom_plans);
+
+ Convert a custom path to a finished plan. The return value will generally
+ be a CustomScan object, which the callback must allocate and
+ initialize. See Section 61.2 for more details.
+
+ This callback is called while converting a path parameterized by the
+ top-most parent of the given child relation child_rel
+ to be parameterized by the child relation. The callback is used to
+ reparameterize any paths or translate any expression nodes saved in the
+ given custom_private member of a
+ CustomPath. The callback may use
+ reparameterize_path_by_child,
+ adjust_appendrel_attrs or
+ adjust_appendrel_attrs_multilevel as required.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/custom-scan-plan.html b/pgsql/doc/postgresql/html/custom-scan-plan.html
new file mode 100644
index 0000000000000000000000000000000000000000..c6bec80ed7d2c1ea86cc1ae18c9c3f848fcc7df9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/custom-scan-plan.html
@@ -0,0 +1,67 @@
+
+61.2. Creating Custom Scan Plans
+ A custom scan is represented in a finished plan tree using the following
+ structure:
+
+typedef struct CustomScan
+{
+ Scan scan;
+ uint32 flags;
+ List *custom_plans;
+ List *custom_exprs;
+ List *custom_private;
+ List *custom_scan_tlist;
+ Bitmapset *custom_relids;
+ const CustomScanMethods *methods;
+} CustomScan;
+
+
+ scan must be initialized as for any other scan, including
+ estimated costs, target lists, qualifications, and so on.
+ flags is a bit mask with the same meaning as in
+ CustomPath.
+ custom_plans can be used to store child
+ Plan nodes.
+ custom_exprs should be used to
+ store expression trees that will need to be fixed up by
+ setrefs.c and subselect.c, while
+ custom_private should be used to store other private data
+ that is only used by the custom scan provider itself.
+ custom_scan_tlist can be NIL when scanning a base
+ relation, indicating that the custom scan returns scan tuples that match
+ the base relation's row type. Otherwise it is a target list describing
+ the actual scan tuples. custom_scan_tlist must be
+ provided for joins, and could be provided for scans if the custom scan
+ provider can compute some non-Var expressions.
+ custom_relids is set by the core code to the set of
+ relations (range table indexes) that this scan node handles; except when
+ this scan is replacing a join, it will have only one member.
+ methods must point to a (usually statically allocated)
+ object implementing the required custom scan methods, which are further
+ detailed below.
+
+ When a CustomScan scans a single relation,
+ scan.scanrelid must be the range table index of the table
+ to be scanned. When it replaces a join, scan.scanrelid
+ should be zero.
+
+ Plan trees must be able to be duplicated using copyObject,
+ so all the data stored within the “custom” fields must consist of
+ nodes that that function can handle. Furthermore, custom scan providers
+ cannot substitute a larger structure that embeds
+ a CustomScan for the structure itself, as would be possible
+ for a CustomPath or CustomScanState.
+
+ Allocate a CustomScanState for this
+ CustomScan. The actual allocation will often be larger than
+ required for an ordinary CustomScanState, because many
+ providers will wish to embed that as the first field of a larger structure.
+ The value returned must have the node tag and methods
+ set appropriately, but other fields should be left as zeroes at this
+ stage; after ExecInitCustomScan performs basic initialization,
+ the BeginCustomScan callback will be invoked to give the
+ custom scan provider a chance to do whatever else is needed.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/custom-scan.html b/pgsql/doc/postgresql/html/custom-scan.html
new file mode 100644
index 0000000000000000000000000000000000000000..3bb866d4d7a624c1841eb91439ee84aa366c9a3e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/custom-scan.html
@@ -0,0 +1,21 @@
+
+Chapter 61. Writing a Custom Scan Provider
+ PostgreSQL supports a set of experimental facilities which
+ are intended to allow extension modules to add new scan types to the system.
+ Unlike a foreign data wrapper, which is only
+ responsible for knowing how to scan its own foreign tables, a custom scan
+ provider can provide an alternative method of scanning any relation in the
+ system. Typically, the motivation for writing a custom scan provider will
+ be to allow the use of some optimization not supported by the core
+ system, such as caching or some form of hardware acceleration. This chapter
+ outlines how to write a new custom scan provider.
+
+ Implementing a new type of custom scan is a three-step process. First,
+ during planning, it is necessary to generate access paths representing a
+ scan using the proposed strategy. Second, if one of those access paths
+ is selected by the planner as the optimal strategy for scanning a
+ particular relation, the access path must be converted to a plan.
+ Finally, it must be possible to execute the plan and generate the same
+ results that would have been generated for any other access path targeting
+ the same relation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/database-roles.html b/pgsql/doc/postgresql/html/database-roles.html
new file mode 100644
index 0000000000000000000000000000000000000000..c308ac737872391831f2bfcd44ce4c9aa718b595
--- /dev/null
+++ b/pgsql/doc/postgresql/html/database-roles.html
@@ -0,0 +1,74 @@
+
+22.1. Database Roles
+ Database roles are conceptually completely separate from
+ operating system users. In practice it might be convenient to
+ maintain a correspondence, but this is not required. Database roles
+ are global across a database cluster installation (and not
+ per individual database). To create a role use the CREATE ROLE SQL command:
+
+CREATE ROLE name;
+
+ name follows the rules for SQL
+ identifiers: either unadorned without special characters, or
+ double-quoted. (In practice, you will usually want to add additional
+ options, such as LOGIN, to the command. More details appear
+ below.) To remove an existing role, use the analogous
+ DROP ROLE command:
+
+DROP ROLE name;
+
+
+ For convenience, the programs createuser
+ and dropuser are provided as wrappers
+ around these SQL commands that can be called from the shell command
+ line:
+
+createuser name
+dropuser name
+
+
+ To determine the set of existing roles, examine the pg_roles
+ system catalog, for example:
+
+SELECT rolname FROM pg_roles;
+
+ or to see just those capable of logging in:
+
+SELECT rolname FROM pg_roles WHERE rolcanlogin;
+
+ The psql program's \du meta-command
+ is also useful for listing the existing roles.
+
+ In order to bootstrap the database system, a freshly initialized
+ system always contains one predefined login-capable role. This role
+ is always a “superuser”, and it will have
+ the same name as the operating system user that initialized the
+ database cluster with initdb unless a different name
+ is specified. This role is often named
+ postgres. In order to create more roles you
+ first have to connect as this initial role.
+
+ Every connection to the database server is made using the name of some
+ particular role, and this role determines the initial access privileges for
+ commands issued in that connection.
+ The role name to use for a particular database
+ connection is indicated by the client that is initiating the
+ connection request in an application-specific fashion. For example,
+ the psql program uses the
+ -U command line option to indicate the role to
+ connect as. Many applications assume the name of the current
+ operating system user by default (including
+ createuser and psql). Therefore it
+ is often convenient to maintain a naming correspondence between
+ roles and operating system users.
+
+ The set of database roles a given client connection can connect as
+ is determined by the client authentication setup, as explained in
+ Chapter 21. (Thus, a client is not
+ limited to connect as the role matching
+ its operating system user, just as a person's login name
+ need not match his or her real name.) Since the role
+ identity determines the set of privileges available to a connected
+ client, it is important to carefully configure privileges when setting up
+ a multiuser environment.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-binary.html b/pgsql/doc/postgresql/html/datatype-binary.html
new file mode 100644
index 0000000000000000000000000000000000000000..0eee11a045b11c49f6f6ec43432500dd66fd7906
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-binary.html
@@ -0,0 +1,132 @@
+
+8.4. Binary Data Types
+ The bytea data type allows storage of binary strings;
+ see Table 8.6.
+
Table 8.6. Binary Data Types
Name
Storage Size
Description
bytea
1 or 4 bytes plus the actual binary string
variable-length binary string
+ A binary string is a sequence of octets (or bytes). Binary
+ strings are distinguished from character strings in two
+ ways. First, binary strings specifically allow storing
+ octets of value zero and other “non-printable”
+ octets (usually, octets outside the decimal range 32 to 126).
+ Character strings disallow zero octets, and also disallow any
+ other octet values and sequences of octet values that are invalid
+ according to the database's selected character set encoding.
+ Second, operations on binary strings process the actual bytes,
+ whereas the processing of character strings depends on locale settings.
+ In short, binary strings are appropriate for storing data that the
+ programmer thinks of as “raw bytes”, whereas character
+ strings are appropriate for storing text.
+
+ The bytea type supports two
+ formats for input and output: “hex” format
+ and PostgreSQL's historical
+ “escape” format. Both
+ of these are always accepted on input. The output format depends
+ on the configuration parameter bytea_output;
+ the default is hex. (Note that the hex format was introduced in
+ PostgreSQL 9.0; earlier versions and some
+ tools don't understand it.)
+
+ The SQL standard defines a different binary
+ string type, called BLOB or BINARY LARGE
+ OBJECT. The input format is different from
+ bytea, but the provided functions and operators are
+ mostly the same.
+
+ The “hex” format encodes binary data as 2 hexadecimal digits
+ per byte, most significant nibble first. The entire string is
+ preceded by the sequence \x (to distinguish it
+ from the escape format). In some contexts, the initial backslash may
+ need to be escaped by doubling it
+ (see Section 4.1.2.1).
+ For input, the hexadecimal digits can
+ be either upper or lower case, and whitespace is permitted between
+ digit pairs (but not within a digit pair nor in the starting
+ \x sequence).
+ The hex format is compatible with a wide
+ range of external applications and protocols, and it tends to be
+ faster to convert than the escape format, so its use is preferred.
+
+ The “escape” format is the traditional
+ PostgreSQL format for the bytea
+ type. It
+ takes the approach of representing a binary string as a sequence
+ of ASCII characters, while converting those bytes that cannot be
+ represented as an ASCII character into special escape sequences.
+ If, from the point of view of the application, representing bytes
+ as characters makes sense, then this representation can be
+ convenient. But in practice it is usually confusing because it
+ fuzzes up the distinction between binary strings and character
+ strings, and also the particular escape mechanism that was chosen is
+ somewhat unwieldy. Therefore, this format should probably be avoided
+ for most new applications.
+
+ When entering bytea values in escape format,
+ octets of certain
+ values must be escaped, while all octet
+ values can be escaped. In
+ general, to escape an octet, convert it into its three-digit
+ octal value and precede it by a backslash.
+ Backslash itself (octet decimal value 92) can alternatively be represented by
+ double backslashes.
+ Table 8.7
+ shows the characters that must be escaped, and gives the alternative
+ escape sequences where applicable.
+
Table 8.7. bytea Literal Escaped Octets
Decimal Octet Value
Description
Escaped Input Representation
Example
Hex Representation
0
zero octet
'\000'
'\000'::bytea
\x00
39
single quote
'''' or '\047'
''''::bytea
\x27
92
backslash
'\\' or '\134'
'\\'::bytea
\x5c
0 to 31 and 127 to 255
“non-printable” octets
'\xxx' (octal value)
'\001'::bytea
\x01
+ The requirement to escape non-printable octets
+ varies depending on locale settings. In some instances you can get away
+ with leaving them unescaped.
+
+ The reason that single quotes must be doubled, as shown
+ in Table 8.7, is that this
+ is true for any string literal in an SQL command. The generic
+ string-literal parser consumes the outermost single quotes
+ and reduces any pair of single quotes to one data character.
+ What the bytea input function sees is just one
+ single quote, which it treats as a plain data character.
+ However, the bytea input function treats
+ backslashes as special, and the other behaviors shown in
+ Table 8.7 are implemented by
+ that function.
+
+ In some contexts, backslashes must be doubled compared to what is
+ shown above, because the generic string-literal parser will also
+ reduce pairs of backslashes to one data character;
+ see Section 4.1.2.1.
+
+ Bytea octets are output in hex
+ format by default. If you change bytea_output
+ to escape,
+ “non-printable” octets are converted to their
+ equivalent three-digit octal value and preceded by one backslash.
+ Most “printable” octets are output by their standard
+ representation in the client character set, e.g.:
+
+
+
+ The octet with decimal value 92 (backslash) is doubled in the output.
+ Details are in Table 8.8.
+
Table 8.8. bytea Output Escaped Octets
Decimal Octet Value
Description
Escaped Output Representation
Example
Output Result
92
backslash
\\
'\134'::bytea
\\
0 to 31 and 127 to 255
“non-printable” octets
\xxx (octal value)
'\001'::bytea
\001
32 to 126
“printable” octets
client character set representation
'\176'::bytea
~
+ Depending on the front end to PostgreSQL you use,
+ you might have additional work to do in terms of escaping and
+ unescaping bytea strings. For example, you might also
+ have to escape line feeds and carriage returns if your interface
+ automatically translates these.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-bit.html b/pgsql/doc/postgresql/html/datatype-bit.html
new file mode 100644
index 0000000000000000000000000000000000000000..c0a9a2ebde95c94390139a47ed9f19b8a4375167
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-bit.html
@@ -0,0 +1,49 @@
+
+8.10. Bit String Types
+ Bit strings are strings of 1's and 0's. They can be used to store
+ or visualize bit masks. There are two SQL bit types:
+ bit(n) and bit
+ varying(n), where
+ n is a positive integer.
+
+ bit type data must match the length
+ n exactly; it is an error to attempt to
+ store shorter or longer bit strings. bit varying data is
+ of variable length up to the maximum length
+ n; longer strings will be rejected.
+ Writing bit without a length is equivalent to
+ bit(1), while bit varying without a length
+ specification means unlimited length.
+
Note
+ If one explicitly casts a bit-string value to
+ bit(n), it will be truncated or
+ zero-padded on the right to be exactly n bits,
+ without raising an error. Similarly,
+ if one explicitly casts a bit-string value to
+ bit varying(n), it will be truncated
+ on the right if it is more than n bits.
+
+ Refer to Section 4.1.2.5 for information about the syntax
+ of bit string constants. Bit-logical operators and string
+ manipulation functions are available; see Section 9.6.
+
Example 8.3. Using the Bit String Types
+CREATE TABLE test (a BIT(3), b BIT VARYING(5));
+INSERT INTO test VALUES (B'101', B'00');
+INSERT INTO test VALUES (B'10', B'101');
+
+ERROR: bit string length 2 does not match type bit(3)
+
+INSERT INTO test VALUES (B'10'::bit(3), B'101');
+SELECT * FROM test;
+
+ a | b
+-----+-----
+ 101 | 00
+ 100 | 101
+
+
+ A bit string value requires 1 byte for each group of 8 bits, plus
+ 5 or 8 bytes overhead depending on the length of the string
+ (but long values may be compressed or moved out-of-line, as explained
+ in Section 8.3 for character strings).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-boolean.html b/pgsql/doc/postgresql/html/datatype-boolean.html
new file mode 100644
index 0000000000000000000000000000000000000000..0e7e18703a1d5c90df44bfb7aaf49598757dda6e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-boolean.html
@@ -0,0 +1,58 @@
+
+8.6. Boolean Type
+ PostgreSQL provides the
+ standard SQL type boolean;
+ see Table 8.19.
+ The boolean type can have several states:
+ “true”, “false”, and a third state,
+ “unknown”, which is represented by the
+ SQL null value.
+
Table 8.19. Boolean Data Type
Name
Storage Size
Description
boolean
1 byte
state of true or false
+ Boolean constants can be represented in SQL queries by the SQL
+ key words TRUE, FALSE,
+ and NULL.
+
+ The datatype input function for type boolean accepts these
+ string representations for the “true” state:
+
true
yes
on
1
+ and these representations for the “false” state:
+
false
no
off
0
+ Unique prefixes of these strings are also accepted, for
+ example t or n.
+ Leading or trailing whitespace is ignored, and case does not matter.
+
+ The datatype output function for type boolean always emits
+ either t or f, as shown in
+ Example 8.2.
+
Example 8.2. Using the boolean Type
+CREATE TABLE test1 (a boolean, b text);
+INSERT INTO test1 VALUES (TRUE, 'sic est');
+INSERT INTO test1 VALUES (FALSE, 'non est');
+SELECT * FROM test1;
+ a | b
+---+---------
+ t | sic est
+ f | non est
+
+SELECT * FROM test1 WHERE a;
+ a | b
+---+---------
+ t | sic est
+
+ The key words TRUE and FALSE are
+ the preferred (SQL-compliant) method for writing
+ Boolean constants in SQL queries. But you can also use the string
+ representations by following the generic string-literal constant syntax
+ described in Section 4.1.2.7, for
+ example 'yes'::boolean.
+
+ Note that the parser automatically understands
+ that TRUE and FALSE are of
+ type boolean, but this is not so
+ for NULL because that can have any type.
+ So in some contexts you might have to cast NULL
+ to boolean explicitly, for
+ example NULL::boolean. Conversely, the cast can be
+ omitted from a string-literal Boolean value in contexts where the parser
+ can deduce that the literal must be of type boolean.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-character.html b/pgsql/doc/postgresql/html/datatype-character.html
new file mode 100644
index 0000000000000000000000000000000000000000..f4d01b59f59a2880d0957a302852bfe1dbf8c200
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-character.html
@@ -0,0 +1,153 @@
+
+8.3. Character Types
+ Table 8.4 shows the
+ general-purpose character types available in
+ PostgreSQL.
+
+ SQL defines two primary character types:
+ character varying(n) and
+ character(n), where n
+ is a positive integer. Both of these types can store strings up to
+ n characters (not bytes) in length. An attempt to store a
+ longer string into a column of these types will result in an
+ error, unless the excess characters are all spaces, in which case
+ the string will be truncated to the maximum length. (This somewhat
+ bizarre exception is required by the SQL
+ standard.)
+ However, if one explicitly casts a value to character
+ varying(n) or
+ character(n), then an over-length
+ value will be truncated to n characters without
+ raising an error. (This too is required by the
+ SQL standard.)
+ If the string to be stored is shorter than the declared
+ length, values of type character will be space-padded;
+ values of type character varying will simply store the
+ shorter
+ string.
+
+ In addition, PostgreSQL provides the
+ text type, which stores strings of any length.
+ Although the text type is not in the
+ SQL standard, several other SQL database
+ management systems have it as well.
+ text is PostgreSQL's native
+ string data type, in that most built-in functions operating on strings
+ are declared to take or return text not character
+ varying. For many purposes, character varying
+ acts as though it were a domain
+ over text.
+
+ The type name varchar is an alias for character
+ varying, while bpchar (with length specifier) and
+ char are aliases for character. The
+ varchar and char aliases are defined in the
+ SQL standard; bpchar is a
+ PostgreSQL extension.
+
+ If specified, the length n must be greater
+ than zero and cannot exceed 10,485,760. If character
+ varying (or varchar) is used without
+ length specifier, the type accepts strings of any length. If
+ bpchar lacks a length specifier, it also accepts strings
+ of any length, but trailing spaces are semantically insignificant.
+ If character (or char) lacks a specifier,
+ it is equivalent to character(1).
+
+ Values of type character are physically padded
+ with spaces to the specified width n, and are
+ stored and displayed that way. However, trailing spaces are treated as
+ semantically insignificant and disregarded when comparing two values
+ of type character. In collations where whitespace
+ is significant, this behavior can produce unexpected results;
+ for example SELECT 'a '::CHAR(2) collate "C" <
+ E'a\n'::CHAR(2) returns true, even though C
+ locale would consider a space to be greater than a newline.
+ Trailing spaces are removed when converting a character value
+ to one of the other string types. Note that trailing spaces
+ are semantically significant in
+ character varying and text values, and
+ when using pattern matching, that is LIKE and
+ regular expressions.
+
+ The characters that can be stored in any of these data types are
+ determined by the database character set, which is selected when
+ the database is created. Regardless of the specific character set,
+ the character with code zero (sometimes called NUL) cannot be stored.
+ For more information refer to Section 24.3.
+
+ The storage requirement for a short string (up to 126 bytes) is 1 byte
+ plus the actual string, which includes the space padding in the case of
+ character. Longer strings have 4 bytes of overhead instead
+ of 1. Long strings are compressed by the system automatically, so
+ the physical requirement on disk might be less. Very long values are also
+ stored in background tables so that they do not interfere with rapid
+ access to shorter column values. In any case, the longest
+ possible character string that can be stored is about 1 GB. (The
+ maximum value that will be allowed for n in the data
+ type declaration is less than that. It wouldn't be useful to
+ change this because with multibyte character encodings the number of
+ characters and bytes can be quite different. If you desire to
+ store long strings with no specific upper limit, use
+ text or character varying without a length
+ specifier, rather than making up an arbitrary length limit.)
+
Tip
+ There is no performance difference among these three types,
+ apart from increased storage space when using the blank-padded
+ type, and a few extra CPU cycles to check the length when storing into
+ a length-constrained column. While
+ character(n) has performance
+ advantages in some other database systems, there is no such advantage in
+ PostgreSQL; in fact
+ character(n) is usually the slowest of
+ the three because of its additional storage costs. In most situations
+ text or character varying should be used
+ instead.
+
+ Refer to Section 4.1.2.1 for information about
+ the syntax of string literals, and to Chapter 9
+ for information about available operators and functions.
+
Example 8.1. Using the Character Types
+CREATE TABLE test1 (a character(4));
+INSERT INTO test1 VALUES ('ok');
+SELECT a, char_length(a) FROM test1; -- (1)
+
+ a | char_length
+------+-------------
+ ok | 2
+
+
+CREATE TABLE test2 (b varchar(5));
+INSERT INTO test2 VALUES ('ok');
+INSERT INTO test2 VALUES ('good ');
+INSERT INTO test2 VALUES ('too long');
+ERROR: value too long for type character varying(5)
+INSERT INTO test2 VALUES ('too long'::varchar(5)); -- explicit truncation
+SELECT b, char_length(b) FROM test2;
+
+ b | char_length
+-------+-------------
+ ok | 2
+ good | 5
+ too l | 5
+
+
+ The char_length function is discussed in
+ Section 9.4.
+
+ There are two other fixed-length character types in
+ PostgreSQL, shown in Table 8.5.
+ These are not intended for general-purpose use, only for use
+ in the internal system catalogs.
+ The name type is used to store identifiers. Its
+ length is currently defined as 64 bytes (63 usable characters plus
+ terminator) but should be referenced using the constant
+ NAMEDATALEN in C source code.
+ The length is set at compile time (and
+ is therefore adjustable for special uses); the default maximum
+ length might change in a future release. The type "char"
+ (note the quotes) is different from char(1) in that it
+ only uses one byte of storage, and therefore can store only a single
+ ASCII character. It is used in the system
+ catalogs as a simplistic enumeration type.
+
Table 8.5. Special Character Types
Name
Storage Size
Description
"char"
1 byte
single-byte internal type
name
64 bytes
internal type for object names
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-datetime.html b/pgsql/doc/postgresql/html/datatype-datetime.html
new file mode 100644
index 0000000000000000000000000000000000000000..c767df3faf2b1acf34f320f539b95bee8840ebc4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-datetime.html
@@ -0,0 +1,557 @@
+
+8.5. Date/Time Types
+ PostgreSQL supports the full set of
+ SQL date and time types, shown in Table 8.9. The operations available
+ on these data types are described in
+ Section 9.9.
+ Dates are counted according to the Gregorian calendar, even in
+ years before that calendar was introduced (see Section B.6 for more information).
+
Table 8.9. Date/Time Types
Name
Storage Size
Description
Low Value
High Value
Resolution
timestamp [ (p) ] [ without time zone ]
8 bytes
both date and time (no time zone)
4713 BC
294276 AD
1 microsecond
timestamp [ (p) ] with time zone
8 bytes
both date and time, with time zone
4713 BC
294276 AD
1 microsecond
date
4 bytes
date (no time of day)
4713 BC
5874897 AD
1 day
time [ (p) ] [ without time zone ]
8 bytes
time of day (no date)
00:00:00
24:00:00
1 microsecond
time [ (p) ] with time zone
12 bytes
time of day (no date), with time zone
00:00:00+1559
24:00:00-1559
1 microsecond
interval [ fields ] [ (p) ]
16 bytes
time interval
-178000000 years
178000000 years
1 microsecond
Note
+ The SQL standard requires that writing just timestamp
+ be equivalent to timestamp without time
+ zone, and PostgreSQL honors that
+ behavior. timestamptz is accepted as an
+ abbreviation for timestamp with time zone; this is a
+ PostgreSQL extension.
+
+ time, timestamp, and
+ interval accept an optional precision value
+ p which specifies the number of
+ fractional digits retained in the seconds field. By default, there
+ is no explicit bound on precision. The allowed range of
+ p is from 0 to 6.
+
+ The interval type has an additional option, which is
+ to restrict the set of stored fields by writing one of these phrases:
+
+YEAR
+MONTH
+DAY
+HOUR
+MINUTE
+SECOND
+YEAR TO MONTH
+DAY TO HOUR
+DAY TO MINUTE
+DAY TO SECOND
+HOUR TO MINUTE
+HOUR TO SECOND
+MINUTE TO SECOND
+
+ Note that if both fields and
+ p are specified, the
+ fields must include SECOND,
+ since the precision applies only to the seconds.
+
+ The type time with time zone is defined by the SQL
+ standard, but the definition exhibits properties which lead to
+ questionable usefulness. In most cases, a combination of
+ date, time, timestamp without time
+ zone, and timestamp with time zone should
+ provide a complete range of date/time functionality required by
+ any application.
+
+ Date and time input is accepted in almost any reasonable format, including
+ ISO 8601, SQL-compatible,
+ traditional POSTGRES, and others.
+ For some formats, ordering of day, month, and year in date input is
+ ambiguous and there is support for specifying the expected
+ ordering of these fields. Set the DateStyle parameter
+ to MDY to select month-day-year interpretation,
+ DMY to select day-month-year interpretation, or
+ YMD to select year-month-day interpretation.
+
+ PostgreSQL is more flexible in
+ handling date/time input than the
+ SQL standard requires.
+ See Appendix B
+ for the exact parsing rules of date/time input and for the
+ recognized text fields including months, days of the week, and
+ time zones.
+
+ Remember that any date or time literal input needs to be enclosed
+ in single quotes, like text strings. Refer to
+ Section 4.1.2.7 for more
+ information.
+ SQL requires the following syntax
+
+type [ (p) ] 'value'
+
+ where p is an optional precision
+ specification giving the number of
+ fractional digits in the seconds field. Precision can be
+ specified for time, timestamp, and
+ interval types, and can range from 0 to 6.
+ If no precision is specified in a constant specification,
+ it defaults to the precision of the literal value (but not
+ more than 6 digits).
+
+ The time-of-day types are time [
+ (p) ] without time zone and
+ time [ (p) ] with time
+ zone. time alone is equivalent to
+ time without time zone.
+
+ Valid input for these types consists of a time of day followed
+ by an optional time zone. (See Table 8.11
+ and Table 8.12.) If a time zone is
+ specified in the input for time without time zone,
+ it is silently ignored. You can also specify a date but it will
+ be ignored, except when you use a time zone name that involves a
+ daylight-savings rule, such as
+ America/New_York. In this case specifying the date
+ is required in order to determine whether standard or daylight-savings
+ time applies. The appropriate time zone offset is recorded in the
+ time with time zone value and is output as stored;
+ it is not adjusted to the active time zone.
+
Table 8.11. Time Input
Example
Description
04:05:06.789
ISO 8601
04:05:06
ISO 8601
04:05
ISO 8601
040506
ISO 8601
04:05 AM
same as 04:05; AM does not affect value
04:05 PM
same as 16:05; input hour must be <= 12
04:05:06.789-8
ISO 8601, with time zone as UTC offset
04:05:06-08:00
ISO 8601, with time zone as UTC offset
04:05-08:00
ISO 8601, with time zone as UTC offset
040506-08
ISO 8601, with time zone as UTC offset
040506+0730
ISO 8601, with fractional-hour time zone as UTC offset
040506+07:30:00
UTC offset specified to seconds (not allowed in ISO 8601)
04:05:06 PST
time zone specified by abbreviation
2003-04-12 04:05:06 America/New_York
time zone specified by full name
Table 8.12. Time Zone Input
Example
Description
PST
Abbreviation (for Pacific Standard Time)
America/New_York
Full time zone name
PST8PDT
POSIX-style time zone specification
-8:00:00
UTC offset for PST
-8:00
UTC offset for PST (ISO 8601 extended format)
-800
UTC offset for PST (ISO 8601 basic format)
-8
UTC offset for PST (ISO 8601 basic format)
zulu
Military abbreviation for UTC
z
Short form of zulu (also in ISO 8601)
+ Refer to Section 8.5.3 for more information on how
+ to specify time zones.
+
+ Valid input for the time stamp types consists of the concatenation
+ of a date and a time, followed by an optional time zone,
+ followed by an optional AD or BC.
+ (Alternatively, AD/BC can appear
+ before the time zone, but this is not the preferred ordering.)
+ Thus:
+
+
+1999-01-08 04:05:06
+
+ and:
+
+1999-01-08 04:05:06 -8:00
+
+
+ are valid values, which follow the ISO 8601
+ standard. In addition, the common format:
+
+January 8 04:05:06 1999 PST
+
+ is supported.
+
+ The SQL standard differentiates
+ timestamp without time zone
+ and timestamp with time zone literals by the presence of a
+ “+” or “-” symbol and time zone offset after
+ the time. Hence, according to the standard,
+
+
+TIMESTAMP '2004-10-19 10:23:54'
+
+
+ is a timestamp without time zone, while
+
+
+TIMESTAMP '2004-10-19 10:23:54+02'
+
+
+ is a timestamp with time zone.
+ PostgreSQL never examines the content of a
+ literal string before determining its type, and therefore will treat
+ both of the above as timestamp without time zone. To
+ ensure that a literal is treated as timestamp with time
+ zone, give it the correct explicit type:
+
+
+TIMESTAMP WITH TIME ZONE '2004-10-19 10:23:54+02'
+
+
+ In a literal that has been determined to be timestamp without time
+ zone, PostgreSQL will silently ignore
+ any time zone indication.
+ That is, the resulting value is derived from the date/time
+ fields in the input value, and is not adjusted for time zone.
+
+ For timestamp with time zone, the internally stored
+ value is always in UTC (Universal
+ Coordinated Time, traditionally known as Greenwich Mean Time,
+ GMT). An input value that has an explicit
+ time zone specified is converted to UTC using the appropriate offset
+ for that time zone. If no time zone is stated in the input string,
+ then it is assumed to be in the time zone indicated by the system's
+ TimeZone parameter, and is converted to UTC using the
+ offset for the timezone zone.
+
+ When a timestamp with time
+ zone value is output, it is always converted from UTC to the
+ current timezone zone, and displayed as local time in that
+ zone. To see the time in another time zone, either change
+ timezone or use the AT TIME ZONE construct
+ (see Section 9.9.4).
+
+ Conversions between timestamp without time zone and
+ timestamp with time zone normally assume that the
+ timestamp without time zone value should be taken or given
+ as timezone local time. A different time zone can
+ be specified for the conversion using AT TIME ZONE.
+
+ PostgreSQL supports several
+ special date/time input values for convenience, as shown in Table 8.13. The values
+ infinity and -infinity
+ are specially represented inside the system and will be displayed
+ unchanged; but the others are simply notational shorthands
+ that will be converted to ordinary date/time values when read.
+ (In particular, now and related strings are converted
+ to a specific time value as soon as they are read.)
+ All of these values need to be enclosed in single quotes when used
+ as constants in SQL commands.
+
Table 8.13. Special Date/Time Inputs
Input String
Valid Types
Description
epoch
date, timestamp
1970-01-01 00:00:00+00 (Unix system time zero)
infinity
date, timestamp
later than all other time stamps
-infinity
date, timestamp
earlier than all other time stamps
now
date, time, timestamp
current transaction's start time
today
date, timestamp
midnight (00:00) today
tomorrow
date, timestamp
midnight (00:00) tomorrow
yesterday
date, timestamp
midnight (00:00) yesterday
allballs
time
00:00:00.00 UTC
+ The following SQL-compatible functions can also
+ be used to obtain the current time value for the corresponding data
+ type:
+ CURRENT_DATE, CURRENT_TIME,
+ CURRENT_TIMESTAMP, LOCALTIME,
+ LOCALTIMESTAMP. (See Section 9.9.5.) Note that these are
+ SQL functions and are not recognized in data input strings.
+
Caution
+ While the input strings now,
+ today, tomorrow,
+ and yesterday are fine to use in interactive SQL
+ commands, they can have surprising behavior when the command is
+ saved to be executed later, for example in prepared statements,
+ views, and function definitions. The string can be converted to a
+ specific time value that continues to be used long after it becomes
+ stale. Use one of the SQL functions instead in such contexts.
+ For example, CURRENT_DATE + 1 is safer than
+ 'tomorrow'::date.
+
+ The output format of the date/time types can be set to one of the four
+ styles ISO 8601,
+ SQL (Ingres), traditional POSTGRES
+ (Unix date format), or
+ German. The default
+ is the ISO format. (The
+ SQL standard requires the use of the ISO 8601
+ format. The name of the “SQL” output format is a
+ historical accident.) Table 8.14 shows examples of each
+ output style. The output of the date and
+ time types is generally only the date or time part
+ in accordance with the given examples. However, the
+ POSTGRES style outputs date-only values in
+ ISO format.
+
Table 8.14. Date/Time Output Styles
Style Specification
Description
Example
ISO
ISO 8601, SQL standard
1997-12-17 07:37:16-08
SQL
traditional style
12/17/1997 07:37:16.00 PST
Postgres
original style
Wed Dec 17 07:37:16 1997 PST
German
regional style
17.12.1997 07:37:16.00 PST
Note
+ ISO 8601 specifies the use of uppercase letter T to separate
+ the date and time. PostgreSQL accepts that format on
+ input, but on output it uses a space rather than T, as shown
+ above. This is for readability and for consistency with
+ RFC 3339 as
+ well as some other database systems.
+
+ In the SQL and POSTGRES styles, day appears before
+ month if DMY field ordering has been specified, otherwise month appears
+ before day.
+ (See Section 8.5.1
+ for how this setting also affects interpretation of input values.)
+ Table 8.15 shows examples.
+
Table 8.15. Date Order Conventions
datestyle Setting
Input Ordering
Example Output
SQL, DMY
day/month/year
17/12/1997 15:37:16.00 CET
SQL, MDY
month/day/year
12/17/1997 07:37:16.00 PST
Postgres, DMY
day/month/year
Wed 17 Dec 07:37:16 1997 PST
+ In the ISO style, the time zone is always shown as
+ a signed numeric offset from UTC, with positive sign used for zones
+ east of Greenwich. The offset will be shown
+ as hh (hours only) if it is an integral
+ number of hours, else
+ as hh:mm if it
+ is an integral number of minutes, else as
+ hh:mm:ss.
+ (The third case is not possible with any modern time zone standard,
+ but it can appear when working with timestamps that predate the
+ adoption of standardized time zones.)
+ In the other date styles, the time zone is shown as an alphabetic
+ abbreviation if one is in common use in the current zone. Otherwise
+ it appears as a signed numeric offset in ISO 8601 basic format
+ (hh or hhmm).
+
+ The date/time style can be selected by the user using the
+ SET datestyle command, the DateStyle parameter in the
+ postgresql.conf configuration file, or the
+ PGDATESTYLE environment variable on the server or
+ client.
+
+ The formatting function to_char
+ (see Section 9.8) is also available as
+ a more flexible way to format date/time output.
+
+ Time zones, and time-zone conventions, are influenced by
+ political decisions, not just earth geometry. Time zones around the
+ world became somewhat standardized during the 1900s,
+ but continue to be prone to arbitrary changes, particularly with
+ respect to daylight-savings rules.
+ PostgreSQL uses the widely-used
+ IANA (Olson) time zone database for information about
+ historical time zone rules. For times in the future, the assumption
+ is that the latest known rules for a given time zone will
+ continue to be observed indefinitely far into the future.
+
+ PostgreSQL endeavors to be compatible with
+ the SQL standard definitions for typical usage.
+ However, the SQL standard has an odd mix of date and
+ time types and capabilities. Two obvious problems are:
+
+
+ Although the date type
+ cannot have an associated time zone, the
+ time type can.
+ Time zones in the real world have little meaning unless
+ associated with a date as well as a time,
+ since the offset can vary through the year with daylight-saving
+ time boundaries.
+
+ The default time zone is specified as a constant numeric offset
+ from UTC. It is therefore impossible to adapt to
+ daylight-saving time when doing date/time arithmetic across
+ DST boundaries.
+
+
+ To address these difficulties, we recommend using date/time types
+ that contain both date and time when using time zones. We
+ do not recommend using the type time with
+ time zone (though it is supported by
+ PostgreSQL for legacy applications and
+ for compliance with the SQL standard).
+ PostgreSQL assumes
+ your local time zone for any type containing only date or time.
+
+ All timezone-aware dates and times are stored internally in
+ UTC. They are converted to local time
+ in the zone specified by the TimeZone configuration
+ parameter before being displayed to the client.
+
+ PostgreSQL allows you to specify time zones in
+ three different forms:
+
+ A full time zone name, for example America/New_York.
+ The recognized time zone names are listed in the
+ pg_timezone_names view (see Section 54.32).
+ PostgreSQL uses the widely-used IANA
+ time zone data for this purpose, so the same time zone
+ names are also recognized by other software.
+
+ A time zone abbreviation, for example PST. Such a
+ specification merely defines a particular offset from UTC, in
+ contrast to full time zone names which can imply a set of daylight
+ savings transition rules as well. The recognized abbreviations
+ are listed in the pg_timezone_abbrevs view (see Section 54.31). You cannot set the
+ configuration parameters TimeZone or
+ log_timezone to a time
+ zone abbreviation, but you can use abbreviations in
+ date/time input values and with the AT TIME ZONE
+ operator.
+
+ In addition to the timezone names and abbreviations,
+ PostgreSQL will accept POSIX-style time zone
+ specifications, as described in
+ Section B.5. This option is not
+ normally preferable to using a named time zone, but it may be
+ necessary if no suitable IANA time zone entry is available.
+
+
+ In short, this is the difference between abbreviations
+ and full names: abbreviations represent a specific offset from UTC,
+ whereas many of the full names imply a local daylight-savings time
+ rule, and so have two possible UTC offsets. As an example,
+ 2014-06-04 12:00 America/New_York represents noon local
+ time in New York, which for this particular date was Eastern Daylight
+ Time (UTC-4). So 2014-06-04 12:00 EDT specifies that
+ same time instant. But 2014-06-04 12:00 EST specifies
+ noon Eastern Standard Time (UTC-5), regardless of whether daylight
+ savings was nominally in effect on that date.
+
+ To complicate matters, some jurisdictions have used the same timezone
+ abbreviation to mean different UTC offsets at different times; for
+ example, in Moscow MSK has meant UTC+3 in some years and
+ UTC+4 in others. PostgreSQL interprets such
+ abbreviations according to whatever they meant (or had most recently
+ meant) on the specified date; but, as with the EST example
+ above, this is not necessarily the same as local civil time on that date.
+
+ In all cases, timezone names and abbreviations are recognized
+ case-insensitively. (This is a change from PostgreSQL
+ versions prior to 8.2, which were case-sensitive in some contexts but
+ not others.)
+
+ Neither timezone names nor abbreviations are hard-wired into the server;
+ they are obtained from configuration files stored under
+ .../share/timezone/ and .../share/timezonesets/
+ of the installation directory
+ (see Section B.4).
+
+ The TimeZone configuration parameter can
+ be set in the file postgresql.conf, or in any of the
+ other standard ways described in Chapter 20.
+ There are also some special ways to set it:
+
+
+ The SQL command SET TIME ZONE
+ sets the time zone for the session. This is an alternative spelling
+ of SET TIMEZONE TO with a more SQL-spec-compatible syntax.
+
+ The PGTZ environment variable is used by
+ libpq clients
+ to send a SET TIME ZONE
+ command to the server upon connection.
+
+ interval values can be written using the following
+ verbose syntax:
+
+
+[@] quantityunit [quantityunit...] [direction]
+
+
+ where quantity is a number (possibly signed);
+ unit is microsecond,
+ millisecond, second,
+ minute, hour, day,
+ week, month, year,
+ decade, century, millennium,
+ or abbreviations or plurals of these units;
+ direction can be ago or
+ empty. The at sign (@) is optional noise. The amounts
+ of the different units are implicitly added with appropriate
+ sign accounting. ago negates all the fields.
+ This syntax is also used for interval output, if
+ IntervalStyle is set to
+ postgres_verbose.
+
+ Quantities of days, hours, minutes, and seconds can be specified without
+ explicit unit markings. For example, '1 12:59:10' is read
+ the same as '1 day 12 hours 59 min 10 sec'. Also,
+ a combination of years and months can be specified with a dash;
+ for example '200-10' is read the same as '200 years
+ 10 months'. (These shorter forms are in fact the only ones allowed
+ by the SQL standard, and are used for output when
+ IntervalStyle is set to sql_standard.)
+
+ Interval values can also be written as ISO 8601 time intervals, using
+ either the “format with designators” of the standard's section
+ 4.4.3.2 or the “alternative format” of section 4.4.3.3. The
+ format with designators looks like this:
+
+P quantityunit [quantityunit ...] [ T [quantityunit ...]]
+
+ The string must start with a P, and may include a
+ T that introduces the time-of-day units. The
+ available unit abbreviations are given in Table 8.16. Units may be
+ omitted, and may be specified in any order, but units smaller than
+ a day must appear after T. In particular, the meaning of
+ M depends on whether it is before or after
+ T.
+
Table 8.16. ISO 8601 Interval Unit Abbreviations
Abbreviation
Meaning
Y
Years
M
Months (in the date part)
W
Weeks
D
Days
H
Hours
M
Minutes (in the time part)
S
Seconds
+ In the alternative format:
+
+P [years-months-days] [ T hours:minutes:seconds]
+
+ the string must begin with P, and a
+ T separates the date and time parts of the interval.
+ The values are given as numbers similar to ISO 8601 dates.
+
+ When writing an interval constant with a fields
+ specification, or when assigning a string to an interval column that was
+ defined with a fields specification, the interpretation of
+ unmarked quantities depends on the fields. For
+ example INTERVAL '1' YEAR is read as 1 year, whereas
+ INTERVAL '1' means 1 second. Also, field values
+ “to the right” of the least significant field allowed by the
+ fields specification are silently discarded. For
+ example, writing INTERVAL '1 day 2:03:04' HOUR TO MINUTE
+ results in dropping the seconds field, but not the day field.
+
+ According to the SQL standard all fields of an interval
+ value must have the same sign, so a leading negative sign applies to all
+ fields; for example the negative sign in the interval literal
+ '-1 2:03:04' applies to both the days and hour/minute/second
+ parts. PostgreSQL allows the fields to have different
+ signs, and traditionally treats each field in the textual representation
+ as independently signed, so that the hour/minute/second part is
+ considered positive in this example. If IntervalStyle is
+ set to sql_standard then a leading sign is considered
+ to apply to all fields (but only if no additional signs appear).
+ Otherwise the traditional PostgreSQL interpretation is
+ used. To avoid ambiguity, it's recommended to attach an explicit sign
+ to each field if any field is negative.
+
+ Internally, interval values are stored as three integral
+ fields: months, days, and microseconds. These fields are kept
+ separate because the number of days in a month varies, while a day
+ can have 23 or 25 hours if a daylight savings time transition is
+ involved. An interval input string that uses other units is
+ normalized into this format, and then reconstructed in a standardized
+ way for output, for example:
+
+
+SELECT '2 years 15 months 100 weeks 99 hours 123456789 milliseconds'::interval;
+ interval
+---------------------------------------
+ 3 years 3 mons 700 days 133:17:36.789
+
+
+ Here weeks, which are understood as “7 days”, have been
+ kept separate, while the smaller and larger time units were
+ combined and normalized.
+
+ Input field values can have fractional parts, for example '1.5
+ weeks' or '01:02:03.45'. However,
+ because interval internally stores only integral fields,
+ fractional values must be converted into smaller
+ units. Fractional parts of units greater than months are rounded to
+ be an integer number of months, e.g. '1.5 years'
+ becomes '1 year 6 mons'. Fractional parts of
+ weeks and days are computed to be an integer number of days and
+ microseconds, assuming 30 days per month and 24 hours per day, e.g.,
+ '1.75 months' becomes 1 mon 22 days
+ 12:00:00. Only seconds will ever be shown as fractional
+ on output.
+
+ Table 8.17 shows some examples
+ of valid interval input.
+
Table 8.17. Interval Input
Example
Description
1-2
SQL standard format: 1 year 2 months
3 4:05:06
SQL standard format: 3 days 4 hours 5 minutes 6 seconds
1 year 2 months 3 days 4 hours 5 minutes 6 seconds
Traditional Postgres format: 1 year 2 months 3 days 4 hours 5 minutes 6 seconds
P1Y2M3DT4H5M6S
ISO 8601 “format with designators”: same meaning as above
P0001-02-03T04:05:06
ISO 8601 “alternative format”: same meaning as above
+ As previously explained, PostgreSQL
+ stores interval values as months, days, and
+ microseconds. For output, the months field is converted to years and
+ months by dividing by 12. The days field is shown as-is. The
+ microseconds field is converted to hours, minutes, seconds, and
+ fractional seconds. Thus months, minutes, and seconds will never be
+ shown as exceeding the ranges 0–11, 0–59, and 0–59
+ respectively, while the displayed years, days, and hours fields can
+ be quite large. (The justify_days
+ and justify_hours
+ functions can be used if it is desirable to transpose large days or
+ hours values into the next higher field.)
+
+ The output format of the interval type can be set to one of the
+ four styles sql_standard, postgres,
+ postgres_verbose, or iso_8601,
+ using the command SET intervalstyle.
+ The default is the postgres format.
+ Table 8.18 shows examples of each
+ output style.
+
+ The sql_standard style produces output that conforms to
+ the SQL standard's specification for interval literal strings, if
+ the interval value meets the standard's restrictions (either year-month
+ only or day-time only, with no mixing of positive
+ and negative components). Otherwise the output looks like a standard
+ year-month literal string followed by a day-time literal string,
+ with explicit signs added to disambiguate mixed-sign intervals.
+
+ The output of the postgres style matches the output of
+ PostgreSQL releases prior to 8.4 when the
+ DateStyle parameter was set to ISO.
+
+ The output of the postgres_verbose style matches the output of
+ PostgreSQL releases prior to 8.4 when the
+ DateStyle parameter was set to non-ISO output.
+
+ The output of the iso_8601 style matches the “format
+ with designators” described in section 4.4.3.2 of the
+ ISO 8601 standard.
+
Table 8.18. Interval Output Style Examples
Style Specification
Year-Month Interval
Day-Time Interval
Mixed Interval
sql_standard
1-2
3 4:05:06
-1-2 +3 -4:05:06
postgres
1 year 2 mons
3 days 04:05:06
-1 year -2 mons +3 days -04:05:06
postgres_verbose
@ 1 year 2 mons
@ 3 days 4 hours 5 mins 6 secs
@ 1 year 2 mons -3 days 4 hours 5 mins 6 secs ago
iso_8601
P1Y2M
P3DT4H5M6S
P-1Y-2M3DT-4H-5M-6S
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-enum.html b/pgsql/doc/postgresql/html/datatype-enum.html
new file mode 100644
index 0000000000000000000000000000000000000000..5f6fd4276640f46e67a67adbafd129f69abf701a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-enum.html
@@ -0,0 +1,115 @@
+
+8.7. Enumerated Types
+ Enumerated (enum) types are data types that
+ comprise a static, ordered set of values.
+ They are equivalent to the enum
+ types supported in a number of programming languages. An example of an enum
+ type might be the days of the week, or a set of status values for
+ a piece of data.
+
+ Enum types are created using the CREATE TYPE command,
+ for example:
+
+
+CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
+
+
+ Once created, the enum type can be used in table and function
+ definitions much like any other type:
+
+CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
+CREATE TABLE person (
+ name text,
+ current_mood mood
+);
+INSERT INTO person VALUES ('Moe', 'happy');
+SELECT * FROM person WHERE current_mood = 'happy';
+ name | current_mood
+------+--------------
+ Moe | happy
+(1 row)
+
+ The ordering of the values in an enum type is the
+ order in which the values were listed when the type was created.
+ All standard comparison operators and related
+ aggregate functions are supported for enums. For example:
+
+
+INSERT INTO person VALUES ('Larry', 'sad');
+INSERT INTO person VALUES ('Curly', 'ok');
+SELECT * FROM person WHERE current_mood > 'sad';
+ name | current_mood
+-------+--------------
+ Moe | happy
+ Curly | ok
+(2 rows)
+
+SELECT * FROM person WHERE current_mood > 'sad' ORDER BY current_mood;
+ name | current_mood
+-------+--------------
+ Curly | ok
+ Moe | happy
+(2 rows)
+
+SELECT name
+FROM person
+WHERE current_mood = (SELECT MIN(current_mood) FROM person);
+ name
+-------
+ Larry
+(1 row)
+
+ Enum labels are case sensitive, so
+ 'happy' is not the same as 'HAPPY'.
+ White space in the labels is significant too.
+
+ Although enum types are primarily intended for static sets of values,
+ there is support for adding new values to an existing enum type, and for
+ renaming values (see ALTER TYPE). Existing values
+ cannot be removed from an enum type, nor can the sort ordering of such
+ values be changed, short of dropping and re-creating the enum type.
+
+ An enum value occupies four bytes on disk. The length of an enum
+ value's textual label is limited by the NAMEDATALEN
+ setting compiled into PostgreSQL; in standard
+ builds this means at most 63 bytes.
+
+ The translations from internal enum values to textual labels are
+ kept in the system catalog
+ pg_enum.
+ Querying this catalog directly can be useful.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-geometric.html b/pgsql/doc/postgresql/html/datatype-geometric.html
new file mode 100644
index 0000000000000000000000000000000000000000..3fd9cb7ae4c01bc89e2a2d2b6b609036919bb3fb
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-geometric.html
@@ -0,0 +1,152 @@
+
+8.8. Geometric Types
+ Geometric data types represent two-dimensional spatial
+ objects. Table 8.20 shows the geometric
+ types available in PostgreSQL.
+
Table 8.20. Geometric Types
Name
Storage Size
Description
Representation
point
16 bytes
Point on a plane
(x,y)
line
32 bytes
Infinite line
{A,B,C}
lseg
32 bytes
Finite line segment
((x1,y1),(x2,y2))
box
32 bytes
Rectangular box
((x1,y1),(x2,y2))
path
16+16n bytes
Closed path (similar to polygon)
((x1,y1),...)
path
16+16n bytes
Open path
[(x1,y1),...]
polygon
40+16n bytes
Polygon (similar to closed path)
((x1,y1),...)
circle
24 bytes
Circle
<(x,y),r> (center point and radius)
+ A rich set of functions and operators is available to perform various geometric
+ operations such as scaling, translation, rotation, and determining
+ intersections. They are explained in Section 9.11.
+
+ Points are the fundamental two-dimensional building block for geometric
+ types. Values of type point are specified using either of
+ the following syntaxes:
+
+
+( x , y )
+ x , y
+
+
+ where x and y are the respective
+ coordinates, as floating-point numbers.
+
+ Lines are represented by the linear
+ equation Ax + By + C = 0,
+ where A and B are not both zero. Values
+ of type line are input and output in the following form:
+
+{ A, B, C }
+
+
+ Alternatively, any of the following forms can be used for input:
+
+
+ Line segments are represented by pairs of points that are the endpoints
+ of the segment. Values of type lseg are specified using any
+ of the following syntaxes:
+
+
+ Boxes are represented by pairs of points that are opposite
+ corners of the box.
+ Values of type box are specified using any of the following
+ syntaxes:
+
+
+
+ where
+ (x1,y1)
+ and
+ (x2,y2)
+ are any two opposite corners of the box.
+
+ Boxes are output using the second syntax.
+
+ Any two opposite corners can be supplied on input, but the values
+ will be reordered as needed to store the
+ upper right and lower left corners, in that order.
+
+ Paths are represented by lists of connected points. Paths can be
+ open, where
+ the first and last points in the list are considered not connected, or
+ closed,
+ where the first and last points are considered connected.
+
+ Values of type path are specified using any of the following
+ syntaxes:
+
+
+
+ where the points are the end points of the line segments
+ comprising the path. Square brackets ([]) indicate
+ an open path, while parentheses (()) indicate a
+ closed path. When the outermost parentheses are omitted, as
+ in the third through fifth syntaxes, a closed path is assumed.
+
+ Paths are output using the first or second syntax, as appropriate.
+
+ Polygons are represented by lists of points (the vertexes of the
+ polygon). Polygons are very similar to closed paths; the essential
+ difference is that a polygon is considered to include the area
+ within it, while a path is not.
+
+ Values of type polygon are specified using any of the
+ following syntaxes:
+
+
+ Circles are represented by a center point and radius.
+ Values of type circle are specified using any of the
+ following syntaxes:
+
+
+< ( x , y ) , r >
+( ( x , y ) , r )
+ ( x , y ) , r
+ x , y , r
+
+
+ where
+ (x,y)
+ is the center point and r is the radius of the
+ circle.
+
+ Circles are output using the first syntax.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-json.html b/pgsql/doc/postgresql/html/datatype-json.html
new file mode 100644
index 0000000000000000000000000000000000000000..85535299ea4a0463539e0f57cac35ba30a3f8d76
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-json.html
@@ -0,0 +1,739 @@
+
+8.14. JSON Types
+ JSON data types are for storing JSON (JavaScript Object Notation)
+ data, as specified in RFC
+ 7159. Such data can also be stored as text, but
+ the JSON data types have the advantage of enforcing that each
+ stored value is valid according to the JSON rules. There are also
+ assorted JSON-specific functions and operators available for data stored
+ in these data types; see Section 9.16.
+
+ PostgreSQL offers two types for storing JSON
+ data: json and jsonb. To implement efficient query
+ mechanisms for these data types, PostgreSQL
+ also provides the jsonpath data type described in
+ Section 8.14.7.
+
+ The json and jsonb data types
+ accept almost identical sets of values as
+ input. The major practical difference is one of efficiency. The
+ json data type stores an exact copy of the input text,
+ which processing functions must reparse on each execution; while
+ jsonb data is stored in a decomposed binary format that
+ makes it slightly slower to input due to added conversion
+ overhead, but significantly faster to process, since no reparsing
+ is needed. jsonb also supports indexing, which can be a
+ significant advantage.
+
+ Because the json type stores an exact copy of the input text, it
+ will preserve semantically-insignificant white space between tokens, as
+ well as the order of keys within JSON objects. Also, if a JSON object
+ within the value contains the same key more than once, all the key/value
+ pairs are kept. (The processing functions consider the last value as the
+ operative one.) By contrast, jsonb does not preserve white
+ space, does not preserve the order of object keys, and does not keep
+ duplicate object keys. If duplicate keys are specified in the input,
+ only the last value is kept.
+
+ In general, most applications should prefer to store JSON data as
+ jsonb, unless there are quite specialized needs, such as
+ legacy assumptions about ordering of object keys.
+
+ RFC 7159 specifies that JSON strings should be encoded in UTF8.
+ It is therefore not possible for the JSON
+ types to conform rigidly to the JSON specification unless the database
+ encoding is UTF8. Attempts to directly include characters that
+ cannot be represented in the database encoding will fail; conversely,
+ characters that can be represented in the database encoding but not
+ in UTF8 will be allowed.
+
+ RFC 7159 permits JSON strings to contain Unicode escape sequences
+ denoted by \uXXXX. In the input
+ function for the json type, Unicode escapes are allowed
+ regardless of the database encoding, and are checked only for syntactic
+ correctness (that is, that four hex digits follow \u).
+ However, the input function for jsonb is stricter: it disallows
+ Unicode escapes for characters that cannot be represented in the database
+ encoding. The jsonb type also
+ rejects \u0000 (because that cannot be represented in
+ PostgreSQL's text type), and it insists
+ that any use of Unicode surrogate pairs to designate characters outside
+ the Unicode Basic Multilingual Plane be correct. Valid Unicode escapes
+ are converted to the equivalent single character for storage;
+ this includes folding surrogate pairs into a single character.
+
Note
+ Many of the JSON processing functions described
+ in Section 9.16 will convert Unicode escapes to
+ regular characters, and will therefore throw the same types of errors
+ just described even if their input is of type json
+ not jsonb. The fact that the json input function does
+ not make these checks may be considered a historical artifact, although
+ it does allow for simple storage (without processing) of JSON Unicode
+ escapes in a database encoding that does not support the represented
+ characters.
+
+ When converting textual JSON input into jsonb, the primitive
+ types described by RFC 7159 are effectively mapped onto
+ native PostgreSQL types, as shown
+ in Table 8.23.
+ Therefore, there are some minor additional constraints on what
+ constitutes valid jsonb data that do not apply to
+ the json type, nor to JSON in the abstract, corresponding
+ to limits on what can be represented by the underlying data type.
+ Notably, jsonb will reject numbers that are outside the
+ range of the PostgreSQLnumeric data
+ type, while json will not. Such implementation-defined
+ restrictions are permitted by RFC 7159. However, in
+ practice such problems are far more likely to occur in other
+ implementations, as it is common to represent JSON's number
+ primitive type as IEEE 754 double precision floating point
+ (which RFC 7159 explicitly anticipates and allows for).
+ When using JSON as an interchange format with such systems, the danger
+ of losing numeric precision compared to data originally stored
+ by PostgreSQL should be considered.
+
+ Conversely, as noted in the table there are some minor restrictions on
+ the input format of JSON primitive types that do not apply to
+ the corresponding PostgreSQL types.
+
Table 8.23. JSON Primitive Types and Corresponding PostgreSQL Types
JSON primitive type
PostgreSQL type
Notes
string
text
\u0000 is disallowed, as are Unicode escapes
+ representing characters not available in the database encoding
number
numeric
NaN and infinity values are disallowed
boolean
boolean
Only lowercase true and false spellings are accepted
+ The input/output syntax for the JSON data types is as specified in
+ RFC 7159.
+
+ The following are all valid json (or jsonb) expressions:
+
+-- Simple scalar/primitive value
+-- Primitive values can be numbers, quoted strings, true, false, or null
+SELECT '5'::json;
+
+-- Array of zero or more elements (elements need not be of same type)
+SELECT '[1, 2, "foo", null]'::json;
+
+-- Object containing pairs of keys and values
+-- Note that object keys must always be quoted strings
+SELECT '{"bar": "baz", "balance": 7.77, "active": false}'::json;
+
+-- Arrays and objects can be nested arbitrarily
+SELECT '{"foo": [true, "bar"], "tags": {"a": 1, "b": null}}'::json;
+
+
+ As previously stated, when a JSON value is input and then printed without
+ any additional processing, json outputs the same text that was
+ input, while jsonb does not preserve semantically-insignificant
+ details such as whitespace. For example, note the differences here:
+
+ One semantically-insignificant detail worth noting is that
+ in jsonb, numbers will be printed according to the behavior of the
+ underlying numeric type. In practice this means that numbers
+ entered with E notation will be printed without it, for
+ example:
+
+ However, jsonb will preserve trailing fractional zeroes, as seen
+ in this example, even though those are semantically insignificant for
+ purposes such as equality checks.
+
+ For the list of built-in functions and operators available for
+ constructing and processing JSON values, see Section 9.16.
+
+ Representing data as JSON can be considerably more flexible than
+ the traditional relational data model, which is compelling in
+ environments where requirements are fluid. It is quite possible
+ for both approaches to co-exist and complement each other within
+ the same application. However, even for applications where maximal
+ flexibility is desired, it is still recommended that JSON documents
+ have a somewhat fixed structure. The structure is typically
+ unenforced (though enforcing some business rules declaratively is
+ possible), but having a predictable structure makes it easier to write
+ queries that usefully summarize a set of “documents” (datums)
+ in a table.
+
+ JSON data is subject to the same concurrency-control
+ considerations as any other data type when stored in a table.
+ Although storing large documents is practicable, keep in mind that
+ any update acquires a row-level lock on the whole row.
+ Consider limiting JSON documents to a
+ manageable size in order to decrease lock contention among updating
+ transactions. Ideally, JSON documents should each
+ represent an atomic datum that business rules dictate cannot
+ reasonably be further subdivided into smaller datums that
+ could be modified independently.
+
+ Testing containment is an important capability of
+ jsonb. There is no parallel set of facilities for the
+ json type. Containment tests whether
+ one jsonb document has contained within it another one.
+ These examples return true except as noted:
+
+-- Simple scalar/primitive values contain only the identical value:
+SELECT '"foo"'::jsonb @> '"foo"'::jsonb;
+
+-- The array on the right side is contained within the one on the left:
+SELECT '[1, 2, 3]'::jsonb @> '[1, 3]'::jsonb;
+
+-- Order of array elements is not significant, so this is also true:
+SELECT '[1, 2, 3]'::jsonb @> '[3, 1]'::jsonb;
+
+-- Duplicate array elements don't matter either:
+SELECT '[1, 2, 3]'::jsonb @> '[1, 2, 2]'::jsonb;
+
+-- The object with a single pair on the right side is contained
+-- within the object on the left side:
+SELECT '{"product": "PostgreSQL", "version": 9.4, "jsonb": true}'::jsonb @> '{"version": 9.4}'::jsonb;
+
+-- The array on the right side is not considered contained within the
+-- array on the left, even though a similar array is nested within it:
+SELECT '[1, 2, [1, 3]]'::jsonb @> '[1, 3]'::jsonb; -- yields false
+
+-- But with a layer of nesting, it is contained:
+SELECT '[1, 2, [1, 3]]'::jsonb @> '[[1, 3]]'::jsonb;
+
+-- Similarly, containment is not reported here:
+SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"bar": "baz"}'::jsonb; -- yields false
+
+-- A top-level key and an empty object is contained:
+SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"foo": {}}'::jsonb;
+
+ The general principle is that the contained object must match the
+ containing object as to structure and data contents, possibly after
+ discarding some non-matching array elements or object key/value pairs
+ from the containing object.
+ But remember that the order of array elements is not significant when
+ doing a containment match, and duplicate array elements are effectively
+ considered only once.
+
+ As a special exception to the general principle that the structures
+ must match, an array may contain a primitive value:
+
+-- This array contains the primitive string value:
+SELECT '["foo", "bar"]'::jsonb @> '"bar"'::jsonb;
+
+-- This exception is not reciprocal -- non-containment is reported here:
+SELECT '"bar"'::jsonb @> '["bar"]'::jsonb; -- yields false
+
+ jsonb also has an existence operator, which is
+ a variation on the theme of containment: it tests whether a string
+ (given as a text value) appears as an object key or array
+ element at the top level of the jsonb value.
+ These examples return true except as noted:
+
+-- String exists as array element:
+SELECT '["foo", "bar", "baz"]'::jsonb ? 'bar';
+
+-- String exists as object key:
+SELECT '{"foo": "bar"}'::jsonb ? 'foo';
+
+-- Object values are not considered:
+SELECT '{"foo": "bar"}'::jsonb ? 'bar'; -- yields false
+
+-- As with containment, existence must match at the top level:
+SELECT '{"foo": {"bar": "baz"}}'::jsonb ? 'bar'; -- yields false
+
+-- A string is considered to exist if it matches a primitive JSON string:
+SELECT '"foo"'::jsonb ? 'foo';
+
+ JSON objects are better suited than arrays for testing containment or
+ existence when there are many keys or elements involved, because
+ unlike arrays they are internally optimized for searching, and do not
+ need to be searched linearly.
+
Tip
+ Because JSON containment is nested, an appropriate query can skip
+ explicit selection of sub-objects. As an example, suppose that we have
+ a doc column containing objects at the top level, with
+ most objects containing tags fields that contain arrays of
+ sub-objects. This query finds entries in which sub-objects containing
+ both "term":"paris" and "term":"food" appear,
+ while ignoring any such keys outside the tags array:
+
+SELECT doc->'site_name' FROM websites
+ WHERE doc @> '{"tags":[{"term":"paris"}, {"term":"food"}]}';
+
+ One could accomplish the same thing with, say,
+
+SELECT doc->'site_name' FROM websites
+ WHERE doc->'tags' @> '[{"term":"paris"}, {"term":"food"}]';
+
+ but that approach is less flexible, and often less efficient as well.
+
+ On the other hand, the JSON existence operator is not nested: it will
+ only look for the specified key or array element at top level of the
+ JSON value.
+
+ The various containment and existence operators, along with all other
+ JSON operators and functions are documented
+ in Section 9.16.
+
+ GIN indexes can be used to efficiently search for
+ keys or key/value pairs occurring within a large number of
+ jsonb documents (datums).
+ Two GIN “operator classes” are provided, offering different
+ performance and flexibility trade-offs.
+
+ The default GIN operator class for jsonb supports queries with
+ the key-exists operators ?, ?|
+ and ?&, the containment operator
+ @>, and the jsonpath match
+ operators @? and @@.
+ (For details of the semantics that these operators
+ implement, see Table 9.46.)
+ An example of creating an index with this operator class is:
+
+CREATE INDEX idxgin ON api USING GIN (jdoc);
+
+ The non-default GIN operator class jsonb_path_ops
+ does not support the key-exists operators, but it does support
+ @>, @? and @@.
+ An example of creating an index with this operator class is:
+
+CREATE INDEX idxginp ON api USING GIN (jdoc jsonb_path_ops);
+
+
+ Consider the example of a table that stores JSON documents
+ retrieved from a third-party web service, with a documented schema
+ definition. A typical document is:
+
+ We store these documents in a table named api,
+ in a jsonb column named jdoc.
+ If a GIN index is created on this column,
+ queries like the following can make use of the index:
+
+-- Find documents in which the key "company" has value "Magnafone"
+SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @> '{"company": "Magnafone"}';
+
+ However, the index could not be used for queries like the
+ following, because though the operator ? is indexable,
+ it is not applied directly to the indexed column jdoc:
+
+-- Find documents in which the key "tags" contains key or array element "qui"
+SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc -> 'tags' ? 'qui';
+
+ Still, with appropriate use of expression indexes, the above
+ query can use an index. If querying for particular items within
+ the "tags" key is common, defining an index like this
+ may be worthwhile:
+
+CREATE INDEX idxgintags ON api USING GIN ((jdoc -> 'tags'));
+
+ Now, the WHERE clause jdoc -> 'tags' ? 'qui'
+ will be recognized as an application of the indexable
+ operator ? to the indexed
+ expression jdoc -> 'tags'.
+ (More information on expression indexes can be found in Section 11.7.)
+
+ Another approach to querying is to exploit containment, for example:
+
+-- Find documents in which the key "tags" contains array element "qui"
+SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @> '{"tags": ["qui"]}';
+
+ A simple GIN index on the jdoc column can support this
+ query. But note that such an index will store copies of every key and
+ value in the jdoc column, whereas the expression index
+ of the previous example stores only data found under
+ the tags key. While the simple-index approach is far more
+ flexible (since it supports queries about any key), targeted expression
+ indexes are likely to be smaller and faster to search than a simple
+ index.
+
+ GIN indexes also support the @?
+ and @@ operators, which
+ perform jsonpath matching. Examples are
+
+SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @? '$.tags[*] ? (@ == "qui")';
+
+
+SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @@ '$.tags[*] == "qui"';
+
+ For these operators, a GIN index extracts clauses of the form
+ accessors_chain
+ = constant out of
+ the jsonpath pattern, and does the index search based on
+ the keys and values mentioned in these clauses. The accessors chain
+ may include .key,
+ [*],
+ and [index] accessors.
+ The jsonb_ops operator class also
+ supports .* and .** accessors,
+ but the jsonb_path_ops operator class does not.
+
+ Although the jsonb_path_ops operator class supports
+ only queries with the @>, @?
+ and @@ operators, it has notable
+ performance advantages over the default operator
+ class jsonb_ops. A jsonb_path_ops
+ index is usually much smaller than a jsonb_ops
+ index over the same data, and the specificity of searches is better,
+ particularly when queries contain keys that appear frequently in the
+ data. Therefore search operations typically perform better
+ than with the default operator class.
+
+ The technical difference between a jsonb_ops
+ and a jsonb_path_ops GIN index is that the former
+ creates independent index items for each key and value in the data,
+ while the latter creates index items only for each value in the
+ data.
+ [7]
+ Basically, each jsonb_path_ops index item is
+ a hash of the value and the key(s) leading to it; for example to index
+ {"foo": {"bar": "baz"}}, a single index item would
+ be created incorporating all three of foo, bar,
+ and baz into the hash value. Thus a containment query
+ looking for this structure would result in an extremely specific index
+ search; but there is no way at all to find out whether foo
+ appears as a key. On the other hand, a jsonb_ops
+ index would create three index items representing foo,
+ bar, and baz separately; then to do the
+ containment query, it would look for rows containing all three of
+ these items. While GIN indexes can perform such an AND search fairly
+ efficiently, it will still be less specific and slower than the
+ equivalent jsonb_path_ops search, especially if
+ there are a very large number of rows containing any single one of the
+ three index items.
+
+ A disadvantage of the jsonb_path_ops approach is
+ that it produces no index entries for JSON structures not containing
+ any values, such as {"a": {}}. If a search for
+ documents containing such a structure is requested, it will require a
+ full-index scan, which is quite slow. jsonb_path_ops is
+ therefore ill-suited for applications that often perform such searches.
+
+ jsonb also supports btree and hash
+ indexes. These are usually useful only if it's important to check
+ equality of complete JSON documents.
+ The btree ordering for jsonb datums is seldom
+ of great interest, but for completeness it is:
+
+Object > Array > Boolean > Number > String > Null
+
+Object with n pairs > object with n - 1 pairs
+
+Array with n elements > array with n - 1 elements
+
+ Objects with equal numbers of pairs are compared in the order:
+
+key-1, value-1, key-2 ...
+
+ Note that object keys are compared in their storage order;
+ in particular, since shorter keys are stored before longer keys, this
+ can lead to results that might be unintuitive, such as:
+
+{ "aa": 1, "c": 1} > {"b": 1, "d": 1}
+
+ Similarly, arrays with equal numbers of elements are compared in the
+ order:
+
+element-1, element-2 ...
+
+ Primitive JSON values are compared using the same
+ comparison rules as for the underlying
+ PostgreSQL data type. Strings are
+ compared using the default database collation.
+
+ The jsonb data type supports array-style subscripting expressions
+ to extract and modify elements. Nested values can be indicated by chaining
+ subscripting expressions, following the same rules as the path
+ argument in the jsonb_set function. If a jsonb
+ value is an array, numeric subscripts start at zero, and negative integers count
+ backwards from the last element of the array. Slice expressions are not supported.
+ The result of a subscripting expression is always of the jsonb data type.
+
+ UPDATE statements may use subscripting in the
+ SET clause to modify jsonb values. Subscript
+ paths must be traversable for all affected values insofar as they exist. For
+ instance, the path val['a']['b']['c'] can be traversed all
+ the way to c if every val,
+ val['a'], and val['a']['b'] is an
+ object. If any val['a'] or val['a']['b']
+ is not defined, it will be created as an empty object and filled as
+ necessary. However, if any val itself or one of the
+ intermediary values is defined as a non-object such as a string, number, or
+ jsonbnull, traversal cannot proceed so
+ an error is raised and the transaction aborted.
+
+ An example of subscripting syntax:
+
+
+
+-- Extract object value by key
+SELECT ('{"a": 1}'::jsonb)['a'];
+
+-- Extract nested object value by key path
+SELECT ('{"a": {"b": {"c": 1}}}'::jsonb)['a']['b']['c'];
+
+-- Extract array element by index
+SELECT ('[1, "2", null]'::jsonb)[1];
+
+-- Update object value by key. Note the quotes around '1': the assigned
+-- value must be of the jsonb type as well
+UPDATE table_name SET jsonb_field['key'] = '1';
+
+-- This will raise an error if any record's jsonb_field['a']['b'] is something
+-- other than an object. For example, the value {"a": 1} has a numeric value
+-- of the key 'a'.
+UPDATE table_name SET jsonb_field['a']['b']['c'] = '1';
+
+-- Filter records using a WHERE clause with subscripting. Since the result of
+-- subscripting is jsonb, the value we compare it against must also be jsonb.
+-- The double quotes make "value" also a valid jsonb string.
+SELECT * FROM table_name WHERE jsonb_field['key'] = '"value"';
+
+
+ jsonb assignment via subscripting handles a few edge cases
+ differently from jsonb_set. When a source jsonb
+ value is NULL, assignment via subscripting will proceed
+ as if it was an empty JSON value of the type (object or array) implied by the
+ subscript key:
+
+
+-- Where jsonb_field was NULL, it is now {"a": 1}
+UPDATE table_name SET jsonb_field['a'] = '1';
+
+-- Where jsonb_field was NULL, it is now [1]
+UPDATE table_name SET jsonb_field[0] = '1';
+
+
+ If an index is specified for an array containing too few elements,
+ NULL elements will be appended until the index is reachable
+ and the value can be set.
+
+
+-- Where jsonb_field was [], it is now [null, null, 2];
+-- where jsonb_field was [0], it is now [0, null, 2]
+UPDATE table_name SET jsonb_field[2] = '2';
+
+
+ A jsonb value will accept assignments to nonexistent subscript
+ paths as long as the last existing element to be traversed is an object or
+ array, as implied by the corresponding subscript (the element indicated by
+ the last subscript in the path is not traversed and may be anything). Nested
+ array and object structures will be created, and in the former case
+ null-padded, as specified by the subscript path until the
+ assigned value can be placed.
+
+
+-- Where jsonb_field was {}, it is now {"a": [{"b": 1}]}
+UPDATE table_name SET jsonb_field['a'][0]['b'] = '1';
+
+-- Where jsonb_field was [], it is now [null, {"a": 1}]
+UPDATE table_name SET jsonb_field[1]['a'] = '1';
+
+ Additional extensions are available that implement transforms for the
+ jsonb type for different procedural languages.
+
+ The extensions for PL/Perl are called jsonb_plperl and
+ jsonb_plperlu. If you use them, jsonb
+ values are mapped to Perl arrays, hashes, and scalars, as appropriate.
+
+ The extension for PL/Python is called jsonb_plpython3u.
+ If you use it, jsonb values are mapped to Python
+ dictionaries, lists, and scalars, as appropriate.
+
+ Of these extensions, jsonb_plperl is
+ considered “trusted”, that is, it can be installed by
+ non-superusers who have CREATE privilege on the
+ current database. The rest require superuser privilege to install.
+
+ The jsonpath type implements support for the SQL/JSON path language
+ in PostgreSQL to efficiently query JSON data.
+ It provides a binary representation of the parsed SQL/JSON path
+ expression that specifies the items to be retrieved by the path
+ engine from the JSON data for further processing with the
+ SQL/JSON query functions.
+
+ The semantics of SQL/JSON path predicates and operators generally follow SQL.
+ At the same time, to provide a natural way of working with JSON data,
+ SQL/JSON path syntax uses some JavaScript conventions:
+
+ Dot (.) is used for member access.
+
+ Square brackets ([]) are used for array access.
+
+ SQL/JSON arrays are 0-relative, unlike regular SQL arrays that start from 1.
+
+ Numeric literals in SQL/JSON path expressions follow JavaScript rules,
+ which are different from both SQL and JSON in some minor details. For
+ example, SQL/JSON path allows .1 and
+ 1., which are invalid in JSON. Non-decimal integer
+ literals and underscore separators are supported, for example,
+ 1_000_000, 0x1EEE_FFFF,
+ 0o273, 0b100101. In SQL/JSON path
+ (and in JavaScript, but not in SQL proper), there must not be an underscore
+ separator directly after the radix prefix.
+
+ An SQL/JSON path expression is typically written in an SQL query as an
+ SQL character string literal, so it must be enclosed in single quotes,
+ and any single quotes desired within the value must be doubled
+ (see Section 4.1.2.1).
+ Some forms of path expressions require string literals within them.
+ These embedded string literals follow JavaScript/ECMAScript conventions:
+ they must be surrounded by double quotes, and backslash escapes may be
+ used within them to represent otherwise-hard-to-type characters.
+ In particular, the way to write a double quote within an embedded string
+ literal is \", and to write a backslash itself, you
+ must write \\. Other special backslash sequences
+ include those recognized in JavaScript strings:
+ \b,
+ \f,
+ \n,
+ \r,
+ \t,
+ \v
+ for various ASCII control characters,
+ \xNN for a character code
+ written with only two hex digits,
+ \uNNNN for a Unicode
+ character identified by its 4-hex-digit code point, and
+ \u{N...} for a Unicode
+ character code point written with 1 to 6 hex digits.
+
+ A path expression consists of a sequence of path elements,
+ which can be any of the following:
+
+ Path literals of JSON primitive types:
+ Unicode text, numeric, true, false, or null.
+
+ jsonpath operators and methods listed
+ in Section 9.16.2.2.
+
+ Parentheses, which can be used to provide filter expressions
+ or define the order of path evaluation.
+
+
+ For details on using jsonpath expressions with SQL/JSON
+ query functions, see Section 9.16.2.
+
Table 8.24. jsonpath Variables
Variable
Description
$
A variable representing the JSON value being queried
+ (the context item).
+
$varname
+ A named variable. Its value can be set by the parameter
+ vars of several JSON processing functions;
+ see Table 9.49 for details.
+
+
@
A variable representing the result of path evaluation
+ in filter expressions.
+
Table 8.25. jsonpath Accessors
Accessor Operator
Description
+
+ .key
+
+
+ ."$varname"
+
+
+
+ Member accessor that returns an object member with
+ the specified key. If the key name matches some named variable
+ starting with $ or does not meet the
+ JavaScript rules for an identifier, it must be enclosed in
+ double quotes to make it a string literal.
+
+
+
+ .*
+
+
+
+ Wildcard member accessor that returns the values of all
+ members located at the top level of the current object.
+
+
+
+ .**
+
+
+
+ Recursive wildcard member accessor that processes all levels
+ of the JSON hierarchy of the current object and returns all
+ the member values, regardless of their nesting level. This
+ is a PostgreSQL extension of
+ the SQL/JSON standard.
+
+
+
+ .**{level}
+
+
+ .**{start_level to
+ end_level}
+
+
+
+ Like .**, but selects only the specified
+ levels of the JSON hierarchy. Nesting levels are specified as integers.
+ Level zero corresponds to the current object. To access the lowest
+ nesting level, you can use the last keyword.
+ This is a PostgreSQL extension of
+ the SQL/JSON standard.
+
+
+
+ [subscript, ...]
+
+
+
+ Array element accessor.
+ subscript can be
+ given in two forms: index
+ or start_index to end_index.
+ The first form returns a single array element by its index. The second
+ form returns an array slice by the range of indexes, including the
+ elements that correspond to the provided
+ start_index and end_index.
+
+
+ The specified index can be an integer, as
+ well as an expression returning a single numeric value, which is
+ automatically cast to integer. Index zero corresponds to the first
+ array element. You can also use the last keyword
+ to denote the last array element, which is useful for handling arrays
+ of unknown length.
+
+
+
+ [*]
+
+
+
+ Wildcard array element accessor that returns all array elements.
+
+
[7]
+ For this purpose, the term “value” includes array elements,
+ though JSON terminology sometimes considers array elements distinct
+ from values within objects.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-money.html b/pgsql/doc/postgresql/html/datatype-money.html
new file mode 100644
index 0000000000000000000000000000000000000000..d518f33e159c12e1623037871bfe6282a2869b2b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-money.html
@@ -0,0 +1,44 @@
+
+8.2. Monetary Types
+ The money type stores a currency amount with a fixed
+ fractional precision; see Table 8.3. The fractional precision is
+ determined by the database's lc_monetary setting.
+ The range shown in the table assumes there are two fractional digits.
+ Input is accepted in a variety of formats, including integer and
+ floating-point literals, as well as typical
+ currency formatting, such as '$1,000.00'.
+ Output is generally in the latter form but depends on the locale.
+
Table 8.3. Monetary Types
Name
Storage Size
Description
Range
money
8 bytes
currency amount
-92233720368547758.08 to +92233720368547758.07
+ Since the output of this data type is locale-sensitive, it might not
+ work to load money data into a database that has a different
+ setting of lc_monetary. To avoid problems, before
+ restoring a dump into a new database make sure lc_monetary has
+ the same or equivalent value as in the database that was dumped.
+
+ Values of the numeric, int, and
+ bigint data types can be cast to money.
+ Conversion from the real and double precision
+ data types can be done by casting to numeric first, for
+ example:
+
+SELECT '12.34'::float8::numeric::money;
+
+ However, this is not recommended. Floating point numbers should not be
+ used to handle money due to the potential for rounding errors.
+
+ A money value can be cast to numeric without
+ loss of precision. Conversion to other types could potentially lose
+ precision, and must also be done in two stages:
+
+SELECT '52093.89'::money::numeric::float8;
+
+
+ Division of a money value by an integer value is performed
+ with truncation of the fractional part towards zero. To get a rounded
+ result, divide by a floating-point value, or cast the money
+ value to numeric before dividing and back to money
+ afterwards. (The latter is preferable to avoid risking precision loss.)
+ When a money value is divided by another money
+ value, the result is double precision (i.e., a pure number,
+ not money); the currency units cancel each other out in the division.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-net-types.html b/pgsql/doc/postgresql/html/datatype-net-types.html
new file mode 100644
index 0000000000000000000000000000000000000000..f26f6f2eaec75190324f64dcf866b5bbe094f428
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-net-types.html
@@ -0,0 +1,132 @@
+
+8.9. Network Address Types
+ PostgreSQL offers data types to store IPv4, IPv6, and MAC
+ addresses, as shown in Table 8.21. It
+ is better to use these types instead of plain text types to store
+ network addresses, because
+ these types offer input error checking and specialized
+ operators and functions (see Section 9.12).
+
Table 8.21. Network Address Types
Name
Storage Size
Description
cidr
7 or 19 bytes
IPv4 and IPv6 networks
inet
7 or 19 bytes
IPv4 and IPv6 hosts and networks
macaddr
6 bytes
MAC addresses
macaddr8
8 bytes
MAC addresses (EUI-64 format)
+ When sorting inet or cidr data types,
+ IPv4 addresses will always sort before IPv6 addresses, including
+ IPv4 addresses encapsulated or mapped to IPv6 addresses, such as
+ ::10.2.3.4 or ::ffff:10.4.3.2.
+
+ The inet type holds an IPv4 or IPv6 host address, and
+ optionally its subnet, all in one field.
+ The subnet is represented by the number of network address bits
+ present in the host address (the
+ “netmask”). If the netmask is 32 and the address is IPv4,
+ then the value does not indicate a subnet, only a single host.
+ In IPv6, the address length is 128 bits, so 128 bits specify a
+ unique host address. Note that if you
+ want to accept only networks, you should use the
+ cidr type rather than inet.
+
+ The input format for this type is
+ address/y
+ where
+ address
+ is an IPv4 or IPv6 address and
+ y
+ is the number of bits in the netmask. If the
+ /y
+ portion is omitted, the
+ netmask is taken to be 32 for IPv4 or 128 for IPv6,
+ so the value represents
+ just a single host. On display, the
+ /y
+ portion is suppressed if the netmask specifies a single host.
+
+ The cidr type holds an IPv4 or IPv6 network specification.
+ Input and output formats follow Classless Internet Domain Routing
+ conventions.
+ The format for specifying networks is address/y where address is the network's lowest
+ address represented as an
+ IPv4 or IPv6 address, and y is the number of bits in the netmask. If
+ y is omitted, it is calculated
+ using assumptions from the older classful network numbering system, except
+ it will be at least large enough to include all of the octets
+ written in the input. It is an error to specify a network address
+ that has bits set to the right of the specified netmask.
+
+ The essential difference between inet and cidr
+ data types is that inet accepts values with nonzero bits to
+ the right of the netmask, whereas cidr does not. For
+ example, 192.168.0.1/24 is valid for inet
+ but not for cidr.
+
Tip
+ If you do not like the output format for inet or
+ cidr values, try the functions host,
+ text, and abbrev.
+
+ The macaddr type stores MAC addresses, known for example
+ from Ethernet card hardware addresses (although MAC addresses are
+ used for other purposes as well). Input is accepted in the
+ following formats:
+
+
'08:00:2b:01:02:03'
'08-00-2b-01-02-03'
'08002b:010203'
'08002b-010203'
'0800.2b01.0203'
'0800-2b01-0203'
'08002b010203'
+
+ These examples all specify the same address. Upper and
+ lower case is accepted for the digits
+ a through f. Output is always in the
+ first of the forms shown.
+
+ IEEE Standard 802-2001 specifies the second form shown (with hyphens)
+ as the canonical form for MAC addresses, and specifies the first
+ form (with colons) as used with bit-reversed, MSB-first notation, so that
+ 08-00-2b-01-02-03 = 10:00:D4:80:40:C0. This convention is widely
+ ignored nowadays, and it is relevant only for obsolete network
+ protocols (such as Token Ring). PostgreSQL makes no provisions
+ for bit reversal; all accepted formats use the canonical LSB
+ order.
+
+ The remaining five input formats are not part of any standard.
+
+ The macaddr8 type stores MAC addresses in EUI-64
+ format, known for example from Ethernet card hardware addresses
+ (although MAC addresses are used for other purposes as well).
+ This type can accept both 6 and 8 byte length MAC addresses
+ and stores them in 8 byte length format. MAC addresses given
+ in 6 byte format will be stored in 8 byte length format with the
+ 4th and 5th bytes set to FF and FE, respectively.
+
+ Note that IPv6 uses a modified EUI-64 format where the 7th bit
+ should be set to one after the conversion from EUI-48. The
+ function macaddr8_set7bit is provided to make this
+ change.
+
+ Generally speaking, any input which is comprised of pairs of hex
+ digits (on byte boundaries), optionally separated consistently by
+ one of ':', '-' or '.', is
+ accepted. The number of hex digits must be either 16 (8 bytes) or
+ 12 (6 bytes). Leading and trailing whitespace is ignored.
+
+ The following are examples of input formats that are accepted:
+
+
'08:00:2b:01:02:03:04:05'
'08-00-2b-01-02-03-04-05'
'08002b:0102030405'
'08002b-0102030405'
'0800.2b01.0203.0405'
'0800-2b01-0203-0405'
'08002b01:02030405'
'08002b0102030405'
+
+ These examples all specify the same address. Upper and
+ lower case is accepted for the digits
+ a through f. Output is always in the
+ first of the forms shown.
+
+ The last six input formats shown above are not part of any standard.
+
+ To convert a traditional 48 bit MAC address in EUI-48 format to
+ modified EUI-64 format to be included as the host portion of an
+ IPv6 address, use macaddr8_set7bit as shown:
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-numeric.html b/pgsql/doc/postgresql/html/datatype-numeric.html
new file mode 100644
index 0000000000000000000000000000000000000000..867e097e06c6117921e41461df44182d27474185
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-numeric.html
@@ -0,0 +1,370 @@
+
+8.1. Numeric Types
+ Numeric types consist of two-, four-, and eight-byte integers,
+ four- and eight-byte floating-point numbers, and selectable-precision
+ decimals. Table 8.2 lists the
+ available types.
+
Table 8.2. Numeric Types
Name
Storage Size
Description
Range
smallint
2 bytes
small-range integer
-32768 to +32767
integer
4 bytes
typical choice for integer
-2147483648 to +2147483647
bigint
8 bytes
large-range integer
-9223372036854775808 to +9223372036854775807
decimal
variable
user-specified precision, exact
up to 131072 digits before the decimal point; up to 16383 digits after the decimal point
numeric
variable
user-specified precision, exact
up to 131072 digits before the decimal point; up to 16383 digits after the decimal point
real
4 bytes
variable-precision, inexact
6 decimal digits precision
double precision
8 bytes
variable-precision, inexact
15 decimal digits precision
smallserial
2 bytes
small autoincrementing integer
1 to 32767
serial
4 bytes
autoincrementing integer
1 to 2147483647
bigserial
8 bytes
large autoincrementing integer
1 to 9223372036854775807
+ The syntax of constants for the numeric types is described in
+ Section 4.1.2. The numeric types have a
+ full set of corresponding arithmetic operators and
+ functions. Refer to Chapter 9 for more
+ information. The following sections describe the types in detail.
+
+ The types smallint, integer, and
+ bigint store whole numbers, that is, numbers without
+ fractional components, of various ranges. Attempts to store
+ values outside of the allowed range will result in an error.
+
+ The type integer is the common choice, as it offers
+ the best balance between range, storage size, and performance.
+ The smallint type is generally only used if disk
+ space is at a premium. The bigint type is designed to be
+ used when the range of the integer type is insufficient.
+
+ SQL only specifies the integer types
+ integer (or int),
+ smallint, and bigint. The
+ type names int2, int4, and
+ int8 are extensions, which are also used by some
+ other SQL database systems.
+
+ The type numeric can store numbers with a
+ very large number of digits. It is especially recommended for
+ storing monetary amounts and other quantities where exactness is
+ required. Calculations with numeric values yield exact
+ results where possible, e.g., addition, subtraction, multiplication.
+ However, calculations on numeric values are very slow
+ compared to the integer types, or to the floating-point types
+ described in the next section.
+
+ We use the following terms below: The
+ precision of a numeric
+ is the total count of significant digits in the whole number,
+ that is, the number of digits to both sides of the decimal point.
+ The scale of a numeric is the
+ count of decimal digits in the fractional part, to the right of the
+ decimal point. So the number 23.5141 has a precision of 6 and a
+ scale of 4. Integers can be considered to have a scale of zero.
+
+ Both the maximum precision and the maximum scale of a
+ numeric column can be
+ configured. To declare a column of type numeric use
+ the syntax:
+
+NUMERIC(precision, scale)
+
+ The precision must be positive, while the scale may be positive or
+ negative (see below). Alternatively:
+
+NUMERIC(precision)
+
+ selects a scale of 0. Specifying:
+
+NUMERIC
+
+ without any precision or scale creates an “unconstrained
+ numeric” column in which numeric values of any length can be
+ stored, up to the implementation limits. A column of this kind will
+ not coerce input values to any particular scale, whereas
+ numeric columns with a declared scale will coerce
+ input values to that scale. (The SQL standard
+ requires a default scale of 0, i.e., coercion to integer
+ precision. We find this a bit useless. If you're concerned
+ about portability, always specify the precision and scale
+ explicitly.)
+
Note
+ The maximum precision that can be explicitly specified in
+ a numeric type declaration is 1000. An
+ unconstrained numeric column is subject to the limits
+ described in Table 8.2.
+
+ If the scale of a value to be stored is greater than the declared
+ scale of the column, the system will round the value to the specified
+ number of fractional digits. Then, if the number of digits to the
+ left of the decimal point exceeds the declared precision minus the
+ declared scale, an error is raised.
+ For example, a column declared as
+
+NUMERIC(3, 1)
+
+ will round values to 1 decimal place and can store values between
+ -99.9 and 99.9, inclusive.
+
+ Beginning in PostgreSQL 15, it is allowed
+ to declare a numeric column with a negative scale. Then
+ values will be rounded to the left of the decimal point. The
+ precision still represents the maximum number of non-rounded digits.
+ Thus, a column declared as
+
+NUMERIC(2, -3)
+
+ will round values to the nearest thousand and can store values
+ between -99000 and 99000, inclusive.
+ It is also allowed to declare a scale larger than the declared
+ precision. Such a column can only hold fractional values, and it
+ requires the number of zero digits just to the right of the decimal
+ point to be at least the declared scale minus the declared precision.
+ For example, a column declared as
+
+NUMERIC(3, 5)
+
+ will round values to 5 decimal places and can store values between
+ -0.00999 and 0.00999, inclusive.
+
Note
+ PostgreSQL permits the scale in a
+ numeric type declaration to be any value in the range
+ -1000 to 1000. However, the SQL standard requires
+ the scale to be in the range 0 to precision.
+ Using scales outside that range may not be portable to other database
+ systems.
+
+ Numeric values are physically stored without any extra leading or
+ trailing zeroes. Thus, the declared precision and scale of a column
+ are maximums, not fixed allocations. (In this sense the numeric
+ type is more akin to varchar(n)
+ than to char(n).) The actual storage
+ requirement is two bytes for each group of four decimal digits,
+ plus three to eight bytes overhead.
+
+ In addition to ordinary numeric values, the numeric type
+ has several special values:
+
+Infinity
+-Infinity
+NaN
+
+ These are adapted from the IEEE 754 standard, and represent
+ “infinity”, “negative infinity”, and
+ “not-a-number”, respectively. When writing these values
+ as constants in an SQL command, you must put quotes around them,
+ for example UPDATE table SET x = '-Infinity'.
+ On input, these strings are recognized in a case-insensitive manner.
+ The infinity values can alternatively be spelled inf
+ and -inf.
+
+ The infinity values behave as per mathematical expectations. For
+ example, Infinity plus any finite value equals
+ Infinity, as does Infinity
+ plus Infinity; but Infinity
+ minus Infinity yields NaN (not a
+ number), because it has no well-defined interpretation. Note that an
+ infinity can only be stored in an unconstrained numeric
+ column, because it notionally exceeds any finite precision limit.
+
+ The NaN (not a number) value is used to represent
+ undefined calculational results. In general, any operation with
+ a NaN input yields another NaN.
+ The only exception is when the operation's other inputs are such that
+ the same output would be obtained if the NaN were to
+ be replaced by any finite or infinite numeric value; then, that output
+ value is used for NaN too. (An example of this
+ principle is that NaN raised to the zero power
+ yields one.)
+
Note
+ In most implementations of the “not-a-number” concept,
+ NaN is not considered equal to any other numeric
+ value (including NaN). In order to allow
+ numeric values to be sorted and used in tree-based
+ indexes, PostgreSQL treats NaN
+ values as equal, and greater than all non-NaN
+ values.
+
+ The types decimal and numeric are
+ equivalent. Both types are part of the SQL
+ standard.
+
+ When rounding values, the numeric type rounds ties away
+ from zero, while (on most machines) the real
+ and double precision types round ties to the nearest even
+ number. For example:
+
+
+ The data types real and double precision are
+ inexact, variable-precision numeric types. On all currently supported
+ platforms, these types are implementations of IEEE
+ Standard 754 for Binary Floating-Point Arithmetic (single and double
+ precision, respectively), to the extent that the underlying processor,
+ operating system, and compiler support it.
+
+ Inexact means that some values cannot be converted exactly to the
+ internal format and are stored as approximations, so that storing
+ and retrieving a value might show slight discrepancies.
+ Managing these errors and how they propagate through calculations
+ is the subject of an entire branch of mathematics and computer
+ science and will not be discussed here, except for the
+ following points:
+
+ If you require exact storage and calculations (such as for
+ monetary amounts), use the numeric type instead.
+
+ If you want to do complicated calculations with these types
+ for anything important, especially if you rely on certain
+ behavior in boundary cases (infinity, underflow), you should
+ evaluate the implementation carefully.
+
+ Comparing two floating-point values for equality might not
+ always work as expected.
+
+
+ On all currently supported platforms, the real type has a
+ range of around 1E-37 to 1E+37 with a precision of at least 6 decimal
+ digits. The double precision type has a range of around
+ 1E-307 to 1E+308 with a precision of at least 15 digits. Values that are
+ too large or too small will cause an error. Rounding might take place if
+ the precision of an input number is too high. Numbers too close to zero
+ that are not representable as distinct from zero will cause an underflow
+ error.
+
+ By default, floating point values are output in text form in their
+ shortest precise decimal representation; the decimal value produced is
+ closer to the true stored binary value than to any other value
+ representable in the same binary precision. (However, the output value is
+ currently never exactly midway between two
+ representable values, in order to avoid a widespread bug where input
+ routines do not properly respect the round-to-nearest-even rule.) This value will
+ use at most 17 significant decimal digits for float8
+ values, and at most 9 digits for float4 values.
+
Note
+ This shortest-precise output format is much faster to generate than the
+ historical rounded format.
+
+ For compatibility with output generated by older versions
+ of PostgreSQL, and to allow the output
+ precision to be reduced, the extra_float_digits
+ parameter can be used to select rounded decimal output instead. Setting a
+ value of 0 restores the previous default of rounding the value to 6
+ (for float4) or 15 (for float8)
+ significant decimal digits. Setting a negative value reduces the number
+ of digits further; for example -2 would round output to 4 or 13 digits
+ respectively.
+
+ Any value of extra_float_digits greater than 0
+ selects the shortest-precise format.
+
Note
+ Applications that wanted precise values have historically had to set
+ extra_float_digits to 3 to obtain them. For
+ maximum compatibility between versions, they should continue to do so.
+
+ In addition to ordinary numeric values, the floating-point types
+ have several special values:
+
+Infinity
+-Infinity
+NaN
+
+ These represent the IEEE 754 special values
+ “infinity”, “negative infinity”, and
+ “not-a-number”, respectively. When writing these values
+ as constants in an SQL command, you must put quotes around them,
+ for example UPDATE table SET x = '-Infinity'. On input,
+ these strings are recognized in a case-insensitive manner.
+ The infinity values can alternatively be spelled inf
+ and -inf.
+
Note
+ IEEE 754 specifies that NaN should not compare equal
+ to any other floating-point value (including NaN).
+ In order to allow floating-point values to be sorted and used
+ in tree-based indexes, PostgreSQL treats
+ NaN values as equal, and greater than all
+ non-NaN values.
+
+ PostgreSQL also supports the SQL-standard
+ notations float and
+ float(p) for specifying
+ inexact numeric types. Here, p specifies
+ the minimum acceptable precision in binary digits.
+ PostgreSQL accepts
+ float(1) to float(24) as selecting the
+ real type, while
+ float(25) to float(53) select
+ double precision. Values of p
+ outside the allowed range draw an error.
+ float with no precision specified is taken to mean
+ double precision.
+
+ This section describes a PostgreSQL-specific way to create an
+ autoincrementing column. Another way is to use the SQL-standard
+ identity column feature, described at CREATE TABLE.
+
+ The data types smallserial, serial and
+ bigserial are not true types, but merely
+ a notational convenience for creating unique identifier columns
+ (similar to the AUTO_INCREMENT property
+ supported by some other databases). In the current
+ implementation, specifying:
+
+
+CREATE TABLE tablename (
+ colname SERIAL
+);
+
+
+ is equivalent to specifying:
+
+
+CREATE SEQUENCE tablename_colname_seq AS integer;
+CREATE TABLE tablename (
+ colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
+);
+ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
+
+
+ Thus, we have created an integer column and arranged for its default
+ values to be assigned from a sequence generator. A NOT NULL
+ constraint is applied to ensure that a null value cannot be
+ inserted. (In most cases you would also want to attach a
+ UNIQUE or PRIMARY KEY constraint to prevent
+ duplicate values from being inserted by accident, but this is
+ not automatic.) Lastly, the sequence is marked as “owned by”
+ the column, so that it will be dropped if the column or table is dropped.
+
Note
+ Because smallserial, serial and
+ bigserial are implemented using sequences, there may
+ be "holes" or gaps in the sequence of values which appears in the
+ column, even if no rows are ever deleted. A value allocated
+ from the sequence is still "used up" even if a row containing that
+ value is never successfully inserted into the table column. This
+ may happen, for example, if the inserting transaction rolls back.
+ See nextval() in Section 9.17
+ for details.
+
+ To insert the next value of the sequence into the serial
+ column, specify that the serial
+ column should be assigned its default value. This can be done
+ either by excluding the column from the list of columns in
+ the INSERT statement, or through the use of
+ the DEFAULT key word.
+
+ The type names serial and serial4 are
+ equivalent: both create integer columns. The type
+ names bigserial and serial8 work
+ the same way, except that they create a bigint
+ column. bigserial should be used if you anticipate
+ the use of more than 231 identifiers over the
+ lifetime of the table. The type names smallserial and
+ serial2 also work the same way, except that they
+ create a smallint column.
+
+ The sequence created for a serial column is
+ automatically dropped when the owning column is dropped.
+ You can drop the sequence without dropping the column, but this
+ will force removal of the column default expression.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-oid.html b/pgsql/doc/postgresql/html/datatype-oid.html
new file mode 100644
index 0000000000000000000000000000000000000000..660d9ffb67e3f70156343a1a86585455b0d9e8f6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-oid.html
@@ -0,0 +1,167 @@
+
+8.19. Object Identifier Types
+ Object identifiers (OIDs) are used internally by
+ PostgreSQL as primary keys for various
+ system tables.
+ Type oid represents an object identifier. There are also
+ several alias types for oid, each
+ named regsomething.
+ Table 8.26 shows an
+ overview.
+
+ The oid type is currently implemented as an unsigned
+ four-byte integer. Therefore, it is not large enough to provide
+ database-wide uniqueness in large databases, or even in large
+ individual tables.
+
+ The oid type itself has few operations beyond comparison.
+ It can be cast to integer, however, and then manipulated using the
+ standard integer operators. (Beware of possible
+ signed-versus-unsigned confusion if you do this.)
+
+ The OID alias types have no operations of their own except
+ for specialized input and output routines. These routines are able
+ to accept and display symbolic names for system objects, rather than
+ the raw numeric value that type oid would use. The alias
+ types allow simplified lookup of OID values for objects. For example,
+ to examine the pg_attribute rows related to a table
+ mytable, one could write:
+
+SELECT * FROM pg_attribute WHERE attrelid = 'mytable'::regclass;
+
+ rather than:
+
+SELECT * FROM pg_attribute
+ WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'mytable');
+
+ While that doesn't look all that bad by itself, it's still oversimplified.
+ A far more complicated sub-select would be needed to
+ select the right OID if there are multiple tables named
+ mytable in different schemas.
+ The regclass input converter handles the table lookup according
+ to the schema path setting, and so it does the “right thing”
+ automatically. Similarly, casting a table's OID to
+ regclass is handy for symbolic display of a numeric OID.
+
Table 8.26. Object Identifier Types
Name
References
Description
Value Example
oid
any
numeric object identifier
564182
regclass
pg_class
relation name
pg_type
regcollation
pg_collation
collation name
"POSIX"
regconfig
pg_ts_config
text search configuration
english
regdictionary
pg_ts_dict
text search dictionary
simple
regnamespace
pg_namespace
namespace name
pg_catalog
regoper
pg_operator
operator name
+
regoperator
pg_operator
operator with argument types
*(integer,integer)
+ or -(NONE,integer)
regproc
pg_proc
function name
sum
regprocedure
pg_proc
function with argument types
sum(int4)
regrole
pg_authid
role name
smithee
regtype
pg_type
data type name
integer
+ All of the OID alias types for objects that are grouped by namespace
+ accept schema-qualified names, and will
+ display schema-qualified names on output if the object would not
+ be found in the current search path without being qualified.
+ For example, myschema.mytable is acceptable input
+ for regclass (if there is such a table). That value
+ might be output as myschema.mytable, or
+ just mytable, depending on the current search path.
+ The regproc and regoper alias types will only
+ accept input names that are unique (not overloaded), so they are
+ of limited use; for most uses regprocedure or
+ regoperator are more appropriate. For regoperator,
+ unary operators are identified by writing NONE for the unused
+ operand.
+
+ The input functions for these types allow whitespace between tokens,
+ and will fold upper-case letters to lower case, except within double
+ quotes; this is done to make the syntax rules similar to the way
+ object names are written in SQL. Conversely, the output functions
+ will use double quotes if needed to make the output be a valid SQL
+ identifier. For example, the OID of a function
+ named Foo (with upper case F)
+ taking two integer arguments could be entered as
+ ' "Foo" ( int, integer ) '::regprocedure. The
+ output would look like "Foo"(integer,integer).
+ Both the function name and the argument type names could be
+ schema-qualified, too.
+
+ Many built-in PostgreSQL functions accept
+ the OID of a table, or another kind of database object, and for
+ convenience are declared as taking regclass (or the
+ appropriate OID alias type). This means you do not have to look up
+ the object's OID by hand, but can just enter its name as a string
+ literal. For example, the nextval(regclass) function
+ takes a sequence relation's OID, so you could call it like this:
+
+nextval('foo') operates on sequence foo
+nextval('FOO') same as above
+nextval('"Foo"') operates on sequence Foo
+nextval('myschema.foo') operates on myschema.foo
+nextval('"myschema".foo') same as above
+nextval('foo') searches search path for foo
+
+
Note
+ When you write the argument of such a function as an unadorned
+ literal string, it becomes a constant of type regclass
+ (or the appropriate type).
+ Since this is really just an OID, it will track the originally
+ identified object despite later renaming, schema reassignment,
+ etc. This “early binding” behavior is usually desirable for
+ object references in column defaults and views. But sometimes you might
+ want “late binding” where the object reference is resolved
+ at run time. To get late-binding behavior, force the constant to be
+ stored as a text constant instead of regclass:
+
+nextval('foo'::text) foo is looked up at runtime
+
+ The to_regclass() function and its siblings
+ can also be used to perform run-time lookups. See
+ Table 9.72.
+
+ Another practical example of use of regclass
+ is to look up the OID of a table listed in
+ the information_schema views, which don't supply
+ such OIDs directly. One might for example wish to call
+ the pg_relation_size() function, which requires
+ the table OID. Taking the above rules into account, the correct way
+ to do that is
+
+ is not recommended, because it will fail for
+ tables that are outside your search path or have names that require
+ quoting.
+
+ An additional property of most of the OID alias types is the creation of
+ dependencies. If a
+ constant of one of these types appears in a stored expression
+ (such as a column default expression or view), it creates a dependency
+ on the referenced object. For example, if a column has a default
+ expression nextval('my_seq'::regclass),
+ PostgreSQL
+ understands that the default expression depends on the sequence
+ my_seq, so the system will not let the sequence
+ be dropped without first removing the default expression. The
+ alternative of nextval('my_seq'::text) does not
+ create a dependency.
+ (regrole is an exception to this property. Constants of this
+ type are not allowed in stored expressions.)
+
+ Another identifier type used by the system is xid, or transaction
+ (abbreviated xact) identifier. This is the data type of the system columns
+ xmin and xmax. Transaction identifiers are 32-bit quantities.
+ In some contexts, a 64-bit variant xid8 is used. Unlike
+ xid values, xid8 values increase strictly
+ monotonically and cannot be reused in the lifetime of a database
+ cluster. See Section 74.1 for more details.
+
+ A third identifier type used by the system is cid, or
+ command identifier. This is the data type of the system columns
+ cmin and cmax. Command identifiers are also 32-bit quantities.
+
+ A final identifier type used by the system is tid, or tuple
+ identifier (row identifier). This is the data type of the system column
+ ctid. A tuple ID is a pair
+ (block number, tuple index within block) that identifies the
+ physical location of the row within its table.
+
+ (The system columns are further explained in Section 5.5.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-pg-lsn.html b/pgsql/doc/postgresql/html/datatype-pg-lsn.html
new file mode 100644
index 0000000000000000000000000000000000000000..7f1937c91ef78879789fa654784d6ea6ca2f6ec6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-pg-lsn.html
@@ -0,0 +1,22 @@
+
+8.20. pg_lsn Type
+ The pg_lsn data type can be used to store LSN (Log Sequence
+ Number) data which is a pointer to a location in the WAL. This type is a
+ representation of XLogRecPtr and an internal system type of
+ PostgreSQL.
+
+ Internally, an LSN is a 64-bit integer, representing a byte position in
+ the write-ahead log stream. It is printed as two hexadecimal numbers of
+ up to 8 digits each, separated by a slash; for example,
+ 16/B374D848. The pg_lsn type supports the
+ standard comparison operators, like = and
+ >. Two LSNs can be subtracted using the
+ - operator; the result is the number of bytes separating
+ those write-ahead log locations. Also the number of bytes can be
+ added into and subtracted from LSN using the
+ +(pg_lsn,numeric) and
+ -(pg_lsn,numeric) operators, respectively. Note that
+ the calculated LSN should be in the range of pg_lsn type,
+ i.e., between 0/0 and
+ FFFFFFFF/FFFFFFFF.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-pseudo.html b/pgsql/doc/postgresql/html/datatype-pseudo.html
new file mode 100644
index 0000000000000000000000000000000000000000..aed6d95dcd193a3760f739ad2694a36253fa0222
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-pseudo.html
@@ -0,0 +1,59 @@
+
+8.21. Pseudo-Types
+ The PostgreSQL type system contains a
+ number of special-purpose entries that are collectively called
+ pseudo-types. A pseudo-type cannot be used as a
+ column data type, but it can be used to declare a function's
+ argument or result type. Each of the available pseudo-types is
+ useful in situations where a function's behavior does not
+ correspond to simply taking or returning a value of a specific
+ SQL data type. Table 8.27 lists the existing
+ pseudo-types.
+
Table 8.27. Pseudo-Types
Name
Description
any
Indicates that a function accepts any input data type.
anyelement
Indicates that a function accepts any data type
+ (see Section 38.2.5).
anyarray
Indicates that a function accepts any array data type
+ (see Section 38.2.5).
anynonarray
Indicates that a function accepts any non-array data type
+ (see Section 38.2.5).
Indicates that a function accepts any data type,
+ with automatic promotion of multiple arguments to a common data type
+ (see Section 38.2.5).
anycompatiblearray
Indicates that a function accepts any array data type,
+ with automatic promotion of multiple arguments to a common data type
+ (see Section 38.2.5).
anycompatiblenonarray
Indicates that a function accepts any non-array data type,
+ with automatic promotion of multiple arguments to a common data type
+ (see Section 38.2.5).
anycompatiblerange
Indicates that a function accepts any range data type,
+ with automatic promotion of multiple arguments to a common data type
+ (see Section 38.2.5 and
+ Section 8.17).
anycompatiblemultirange
Indicates that a function accepts any multirange data type,
+ with automatic promotion of multiple arguments to a common data type
+ (see Section 38.2.5 and
+ Section 8.17).
cstring
Indicates that a function accepts or returns a null-terminated C string.
internal
Indicates that a function accepts or returns a server-internal
+ data type.
language_handler
A procedural language call handler is declared to return language_handler.
fdw_handler
A foreign-data wrapper handler is declared to return fdw_handler.
table_am_handler
A table access method handler is declared to return table_am_handler.
index_am_handler
An index access method handler is declared to return index_am_handler.
tsm_handler
A tablesample method handler is declared to return tsm_handler.
record
Identifies a function taking or returning an unspecified row type.
trigger
A trigger function is declared to return trigger.
event_trigger
An event trigger function is declared to return event_trigger.
pg_ddl_command
Identifies a representation of DDL commands that is available to event triggers.
void
Indicates that a function returns no value.
unknown
Identifies a not-yet-resolved type, e.g., of an undecorated
+ string literal.
+ Functions coded in C (whether built-in or dynamically loaded) can be
+ declared to accept or return any of these pseudo-types. It is up to
+ the function author to ensure that the function will behave safely
+ when a pseudo-type is used as an argument type.
+
+ Functions coded in procedural languages can use pseudo-types only as
+ allowed by their implementation languages. At present most procedural
+ languages forbid use of a pseudo-type as an argument type, and allow
+ only void and record as a result type (plus
+ trigger or event_trigger when the function is used
+ as a trigger or event trigger). Some also support polymorphic functions
+ using the polymorphic pseudo-types, which are shown above and discussed
+ in detail in Section 38.2.5.
+
+ The internal pseudo-type is used to declare functions
+ that are meant only to be called internally by the database
+ system, and not by direct invocation in an SQL
+ query. If a function has at least one internal-type
+ argument then it cannot be called from SQL. To
+ preserve the type safety of this restriction it is important to
+ follow this coding rule: do not create any function that is
+ declared to return internal unless it has at least one
+ internal argument.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-textsearch.html b/pgsql/doc/postgresql/html/datatype-textsearch.html
new file mode 100644
index 0000000000000000000000000000000000000000..a9706159766195184afc4bb94fe50d6cef1ad77b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-textsearch.html
@@ -0,0 +1,196 @@
+
+8.11. Text Search Types
+ PostgreSQL provides two data types that
+ are designed to support full text search, which is the activity of
+ searching through a collection of natural-language documents
+ to locate those that best match a query.
+ The tsvector type represents a document in a form optimized
+ for text search; the tsquery type similarly represents
+ a text query.
+ Chapter 12 provides a detailed explanation of this
+ facility, and Section 9.13 summarizes the
+ related functions and operators.
+
+ A tsvector value is a sorted list of distinct
+ lexemes, which are words that have been
+ normalized to merge different variants of the same word
+ (see Chapter 12 for details). Sorting and
+ duplicate-elimination are done automatically during input, as shown in
+ this example:
+
+
+SELECT 'a fat cat sat on a mat and ate a fat rat'::tsvector;
+ tsvector
+----------------------------------------------------
+ 'a' 'and' 'ate' 'cat' 'fat' 'mat' 'on' 'rat' 'sat'
+
+
+ To represent
+ lexemes containing whitespace or punctuation, surround them with quotes:
+
+
+
+ (We use dollar-quoted string literals in this example and the next one
+ to avoid the confusion of having to double quote marks within the
+ literals.) Embedded quotes and backslashes must be doubled:
+
+
+
+ A position normally indicates the source word's location in the
+ document. Positional information can be used for
+ proximity ranking. Position values can
+ range from 1 to 16383; larger numbers are silently set to 16383.
+ Duplicate positions for the same lexeme are discarded.
+
+ Lexemes that have positions can further be labeled with a
+ weight, which can be A,
+ B, C, or D.
+ D is the default and hence is not shown on output:
+
+
+
+ Weights are typically used to reflect document structure, for example
+ by marking title words differently from body words. Text search
+ ranking functions can assign different priorities to the different
+ weight markers.
+
+ It is important to understand that the
+ tsvector type itself does not perform any word
+ normalization; it assumes the words it is given are normalized
+ appropriately for the application. For example,
+
+
+
+ For most English-text-searching applications the above words would
+ be considered non-normalized, but tsvector doesn't care.
+ Raw document text should usually be passed through
+ to_tsvector to normalize the words appropriately
+ for searching:
+
+
+ A tsquery value stores lexemes that are to be
+ searched for, and can combine them using the Boolean operators
+ & (AND), | (OR), and
+ ! (NOT), as well as the phrase search operator
+ <-> (FOLLOWED BY). There is also a variant
+ <N> of the FOLLOWED BY
+ operator, where N is an integer constant that
+ specifies the distance between the two lexemes being searched
+ for. <-> is equivalent to <1>.
+
+ Parentheses can be used to enforce grouping of these operators.
+ In the absence of parentheses, ! (NOT) binds most tightly,
+ <-> (FOLLOWED BY) next most tightly, then
+ & (AND), with | (OR) binding
+ the least tightly.
+
+ Optionally, lexemes in a tsquery can be labeled with
+ one or more weight letters, which restricts them to match only
+ tsvector lexemes with one of those weights:
+
+
+ This query will match any word in a tsvector that begins
+ with “super”.
+
+ Quoting rules for lexemes are the same as described previously for
+ lexemes in tsvector; and, as with tsvector,
+ any required normalization of words must be done before converting
+ to the tsquery type. The to_tsquery
+ function is convenient for performing such normalization:
+
+
+ which will match the stemmed form of postgraduate.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-uuid.html b/pgsql/doc/postgresql/html/datatype-uuid.html
new file mode 100644
index 0000000000000000000000000000000000000000..f45fab6d007c4e886e09ca07de6dbd4d7b844a52
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-uuid.html
@@ -0,0 +1,39 @@
+
+8.12. UUID Type
+ The data type uuid stores Universally Unique Identifiers
+ (UUID) as defined by RFC 4122,
+ ISO/IEC 9834-8:2005, and related standards.
+ (Some systems refer to this data type as a globally unique identifier, or
+ GUID, instead.) This
+ identifier is a 128-bit quantity that is generated by an algorithm chosen
+ to make it very unlikely that the same identifier will be generated by
+ anyone else in the known universe using the same algorithm. Therefore,
+ for distributed systems, these identifiers provide a better uniqueness
+ guarantee than sequence generators, which
+ are only unique within a single database.
+
+ A UUID is written as a sequence of lower-case hexadecimal digits,
+ in several groups separated by hyphens, specifically a group of 8
+ digits followed by three groups of 4 digits followed by a group of
+ 12 digits, for a total of 32 digits representing the 128 bits. An
+ example of a UUID in this standard form is:
+
+a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11
+
+ PostgreSQL also accepts the following
+ alternative forms for input:
+ use of upper-case digits, the standard format surrounded by
+ braces, omitting some or all hyphens, adding a hyphen after any
+ group of four digits. Examples are:
+
+ See Section 9.14 for how to generate a UUID in
+ PostgreSQL.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype-xml.html b/pgsql/doc/postgresql/html/datatype-xml.html
new file mode 100644
index 0000000000000000000000000000000000000000..780f1117dbd0102191f3fec672702684434acd6c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype-xml.html
@@ -0,0 +1,156 @@
+
+8.13. XML Type
+ The xml data type can be used to store XML data. Its
+ advantage over storing XML data in a text field is that it
+ checks the input values for well-formedness, and there are support
+ functions to perform type-safe operations on it; see Section 9.15. Use of this data type requires the
+ installation to have been built with configure
+ --with-libxml.
+
+ The xml type can store well-formed
+ “documents”, as defined by the XML standard, as well
+ as “content” fragments, which are defined by reference
+ to the more permissive
+ “document node”
+ of the XQuery and XPath data model.
+ Roughly, this means that content fragments can have
+ more than one top-level element or character node. The expression
+ xmlvalue IS DOCUMENT
+ can be used to evaluate whether a particular xml
+ value is a full document or only a content fragment.
+
+ Limits and compatibility notes for the xml data type
+ can be found in Section D.3.
+
+ While this is the only way to convert character strings into XML
+ values according to the SQL standard, the PostgreSQL-specific
+ syntaxes:
+
+xml '<foo>bar</foo>'
+'<foo>bar</foo>'::xml
+
+ can also be used.
+
+ The xml type does not validate input values
+ against a document type declaration
+ (DTD),
+ even when the input value specifies a DTD.
+ There is also currently no built-in support for validating against
+ other XML schema languages such as XML Schema.
+
+ The inverse operation, producing a character string value from
+ xml, uses the function
+ xmlserialize:
+
+XMLSERIALIZE ( { DOCUMENT | CONTENT } value AS type [ [ NO ] INDENT ] )
+
+ type can be
+ character, character varying, or
+ text (or an alias for one of those). Again, according
+ to the SQL standard, this is the only way to convert between type
+ xml and character types, but PostgreSQL also allows
+ you to simply cast the value.
+
+ The INDENT option causes the result to be
+ pretty-printed, while NO INDENT (which is the
+ default) just emits the original input string. Casting to a character
+ type likewise produces the original string.
+
+ When a character string value is cast to or from type
+ xml without going through XMLPARSE or
+ XMLSERIALIZE, respectively, the choice of
+ DOCUMENT versus CONTENT is
+ determined by the “XML option”
+
+ session configuration parameter, which can be set using the
+ standard command:
+
+SET XML OPTION { DOCUMENT | CONTENT };
+
+ or the more PostgreSQL-like syntax
+
+SET xmloption TO { DOCUMENT | CONTENT };
+
+ The default is CONTENT, so all forms of XML
+ data are allowed.
+
+ Care must be taken when dealing with multiple character encodings
+ on the client, server, and in the XML data passed through them.
+ When using the text mode to pass queries to the server and query
+ results to the client (which is the normal mode), PostgreSQL
+ converts all character data passed between the client and the
+ server and vice versa to the character encoding of the respective
+ end; see Section 24.3. This includes string
+ representations of XML values, such as in the above examples.
+ This would ordinarily mean that encoding declarations contained in
+ XML data can become invalid as the character data is converted
+ to other encodings while traveling between client and server,
+ because the embedded encoding declaration is not changed. To cope
+ with this behavior, encoding declarations contained in
+ character strings presented for input to the xml type
+ are ignored, and content is assumed
+ to be in the current server encoding. Consequently, for correct
+ processing, character strings of XML data must be sent
+ from the client in the current client encoding. It is the
+ responsibility of the client to either convert documents to the
+ current client encoding before sending them to the server, or to
+ adjust the client encoding appropriately. On output, values of
+ type xml will not have an encoding declaration, and
+ clients should assume all data is in the current client
+ encoding.
+
+ When using binary mode to pass query parameters to the server
+ and query results back to the client, no encoding conversion
+ is performed, so the situation is different. In this case, an
+ encoding declaration in the XML data will be observed, and if it
+ is absent, the data will be assumed to be in UTF-8 (as required by
+ the XML standard; note that PostgreSQL does not support UTF-16).
+ On output, data will have an encoding declaration
+ specifying the client encoding, unless the client encoding is
+ UTF-8, in which case it will be omitted.
+
+ Needless to say, processing XML data with PostgreSQL will be less
+ error-prone and more efficient if the XML data encoding, client encoding,
+ and server encoding are the same. Since XML data is internally
+ processed in UTF-8, computations will be most efficient if the
+ server encoding is also UTF-8.
+
Caution
+ Some XML-related functions may not work at all on non-ASCII data
+ when the server encoding is not UTF-8. This is known to be an
+ issue for xmltable() and xpath() in particular.
+
+ The xml data type is unusual in that it does not
+ provide any comparison operators. This is because there is no
+ well-defined and universally useful comparison algorithm for XML
+ data. One consequence of this is that you cannot retrieve rows by
+ comparing an xml column against a search value. XML
+ values should therefore typically be accompanied by a separate key
+ field such as an ID. An alternative solution for comparing XML
+ values is to convert them to character strings first, but note
+ that character string comparison has little to do with a useful
+ XML comparison method.
+
+ Since there are no comparison operators for the xml
+ data type, it is not possible to create an index directly on a
+ column of this type. If speedy searches in XML data are desired,
+ possible workarounds include casting the expression to a
+ character string type and indexing that, or indexing an XPath
+ expression. Of course, the actual query would have to be adjusted
+ to search by the indexed expression.
+
+ The text-search functionality in PostgreSQL can also be used to speed
+ up full-document searches of XML data. The necessary
+ preprocessing support is, however, not yet available in the PostgreSQL
+ distribution.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datatype.html b/pgsql/doc/postgresql/html/datatype.html
new file mode 100644
index 0000000000000000000000000000000000000000..a72dce5bace5615c52b501c3a2594a6d8cd212ca
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datatype.html
@@ -0,0 +1,36 @@
+
+Chapter 8. Data Types
+ PostgreSQL has a rich set of native data
+ types available to users. Users can add new types to
+ PostgreSQL using the CREATE TYPE command.
+
+ Table 8.1 shows all the built-in general-purpose data
+ types. Most of the alternative names listed in the
+ “Aliases” column are the names used internally by
+ PostgreSQL for historical reasons. In
+ addition, some internally used or deprecated types are available,
+ but are not listed here.
+
Table 8.1. Data Types
Name
Aliases
Description
bigint
int8
signed eight-byte integer
bigserial
serial8
autoincrementing eight-byte integer
bit [ (n) ]
fixed-length bit string
bit varying [ (n) ]
varbit [ (n) ]
variable-length bit string
boolean
bool
logical Boolean (true/false)
box
rectangular box on a plane
bytea
binary data (“byte array”)
character [ (n) ]
char [ (n) ]
fixed-length character string
character varying [ (n) ]
varchar [ (n) ]
variable-length character string
cidr
IPv4 or IPv6 network address
circle
circle on a plane
date
calendar date (year, month, day)
double precision
float8
double precision floating-point number (8 bytes)
inet
IPv4 or IPv6 host address
integer
int, int4
signed four-byte integer
interval [ fields ] [ (p) ]
time span
json
textual JSON data
jsonb
binary JSON data, decomposed
line
infinite line on a plane
lseg
line segment on a plane
macaddr
MAC (Media Access Control) address
macaddr8
MAC (Media Access Control) address (EUI-64 format)
money
currency amount
numeric [ (p,
+ s) ]
decimal [ (p,
+ s) ]
exact numeric of selectable precision
path
geometric path on a plane
pg_lsn
PostgreSQL Log Sequence Number
pg_snapshot
user-level transaction ID snapshot
point
geometric point on a plane
polygon
closed geometric path on a plane
real
float4
single precision floating-point number (4 bytes)
smallint
int2
signed two-byte integer
smallserial
serial2
autoincrementing two-byte integer
serial
serial4
autoincrementing four-byte integer
text
variable-length character string
time [ (p) ] [ without time zone ]
time of day (no time zone)
time [ (p) ] with time zone
timetz
time of day, including time zone
timestamp [ (p) ] [ without time zone ]
date and time (no time zone)
timestamp [ (p) ] with time zone
timestamptz
date and time, including time zone
tsquery
text search query
tsvector
text search document
txid_snapshot
user-level transaction ID snapshot (deprecated; see pg_snapshot)
uuid
universally unique identifier
xml
XML data
Compatibility
+ The following types (or spellings thereof) are specified by
+ SQL: bigint, bit, bit
+ varying, boolean, char,
+ character varying, character,
+ varchar, date, double
+ precision, integer, interval,
+ numeric, decimal, real,
+ smallint, time (with or without time zone),
+ timestamp (with or without time zone),
+ xml.
+
+ Each data type has an external representation determined by its input
+ and output functions. Many of the built-in types have
+ obvious external formats. However, several types are either unique
+ to PostgreSQL, such as geometric
+ paths, or have several possible formats, such as the date
+ and time types.
+ Some of the input and output functions are not invertible, i.e.,
+ the result of an output function might lose accuracy when compared to
+ the original input.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-appendix.html b/pgsql/doc/postgresql/html/datetime-appendix.html
new file mode 100644
index 0000000000000000000000000000000000000000..9e28b254312b5552e8f373cc1687a7c8640cc936
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-appendix.html
@@ -0,0 +1,15 @@
+
+Appendix B. Date/Time Support
+ PostgreSQL uses an internal heuristic
+ parser for all date/time input support. Dates and times are input as
+ strings, and are broken up into distinct fields with a preliminary
+ determination of what kind of information can be in the
+ field. Each field is interpreted and either assigned a numeric
+ value, ignored, or rejected.
+ The parser contains internal lookup tables for all textual fields,
+ including months, days of the week, and time zones.
+
+ This appendix includes information on the content of these
+ lookup tables and describes the steps used by the parser to decode
+ dates and times.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-config-files.html b/pgsql/doc/postgresql/html/datetime-config-files.html
new file mode 100644
index 0000000000000000000000000000000000000000..ad62fb70d02b229eccd09b2bcbd483ca6111c95e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-config-files.html
@@ -0,0 +1,98 @@
+
+B.4. Date/Time Configuration Files
+ Since timezone abbreviations are not well standardized,
+ PostgreSQL provides a means to customize
+ the set of abbreviations accepted by the server. The
+ timezone_abbreviations run-time parameter
+ determines the active set of abbreviations. While this parameter
+ can be altered by any database user, the possible values for it
+ are under the control of the database administrator — they
+ are in fact names of configuration files stored in
+ .../share/timezonesets/ of the installation directory.
+ By adding or altering files in that directory, the administrator
+ can set local policy for timezone abbreviations.
+
+ timezone_abbreviations can be set to any file name
+ found in .../share/timezonesets/, if the file's name
+ is entirely alphabetic. (The prohibition against non-alphabetic
+ characters in timezone_abbreviations prevents reading
+ files outside the intended directory, as well as reading editor
+ backup files and other extraneous files.)
+
+ A timezone abbreviation file can contain blank lines and comments
+ beginning with #. Non-comment lines must have one of
+ these formats:
+
+
+zone_abbreviationoffset
+zone_abbreviationoffset D
+zone_abbreviationtime_zone_name
+@INCLUDE file_name
+@OVERRIDE
+
+
+ A zone_abbreviation is just the abbreviation
+ being defined. An offset is an integer giving
+ the equivalent offset in seconds from UTC, positive being east from
+ Greenwich and negative being west. For example, -18000 would be five
+ hours west of Greenwich, or North American east coast standard time.
+ D indicates that the zone name represents local
+ daylight-savings time rather than standard time.
+
+ Alternatively, a time_zone_name can be given, referencing
+ a zone name defined in the IANA timezone database. The zone's definition
+ is consulted to see whether the abbreviation is or has been in use in
+ that zone, and if so, the appropriate meaning is used — that is,
+ the meaning that was currently in use at the timestamp whose value is
+ being determined, or the meaning in use immediately before that if it
+ wasn't current at that time, or the oldest meaning if it was used only
+ after that time. This behavior is essential for dealing with
+ abbreviations whose meaning has historically varied. It is also allowed
+ to define an abbreviation in terms of a zone name in which that
+ abbreviation does not appear; then using the abbreviation is just
+ equivalent to writing out the zone name.
+
Tip
+ Using a simple integer offset is preferred
+ when defining an abbreviation whose offset from UTC has never changed,
+ as such abbreviations are much cheaper to process than those that
+ require consulting a time zone definition.
+
+ The @INCLUDE syntax allows inclusion of another file in the
+ .../share/timezonesets/ directory. Inclusion can be nested,
+ to a limited depth.
+
+ The @OVERRIDE syntax indicates that subsequent entries in the
+ file can override previous entries (typically, entries obtained from
+ included files). Without this, conflicting definitions of the same
+ timezone abbreviation are considered an error.
+
+ In an unmodified installation, the file Default contains
+ all the non-conflicting time zone abbreviations for most of the world.
+ Additional files Australia and India are
+ provided for those regions: these files first include the
+ Default file and then add or modify abbreviations as needed.
+
+ For reference purposes, a standard installation also contains files
+ Africa.txt, America.txt, etc., containing
+ information about every time zone abbreviation known to be in use
+ according to the IANA timezone database. The zone name
+ definitions found in these files can be copied and pasted into a custom
+ configuration file as needed. Note that these files cannot be directly
+ referenced as timezone_abbreviations settings, because of
+ the dot embedded in their names.
+
Note
+ If an error occurs while reading the time zone abbreviation set, no new
+ value is applied and the old set is kept. If the error occurs while
+ starting the database, startup fails.
+
Caution
+ Time zone abbreviations defined in the configuration file override
+ non-timezone meanings built into PostgreSQL.
+ For example, the Australia configuration file defines
+ SAT (for South Australian Standard Time). When this
+ file is active, SAT will not be recognized as an abbreviation
+ for Saturday.
+
Caution
+ If you modify files in .../share/timezonesets/,
+ it is up to you to make backups — a normal database dump
+ will not include this directory.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-input-rules.html b/pgsql/doc/postgresql/html/datetime-input-rules.html
new file mode 100644
index 0000000000000000000000000000000000000000..0eeeaa568ecd6319ca01de7a3a74a59b52007ee9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-input-rules.html
@@ -0,0 +1,74 @@
+
+B.1. Date/Time Input Interpretation
+ Date/time input strings are decoded using the following procedure.
+
+ Break the input string into tokens and categorize each token as
+ a string, time, time zone, or number.
+
+ If the numeric token contains a colon (:), this is
+ a time string. Include all subsequent digits and colons.
+
+ If the numeric token contains a dash (-), slash
+ (/), or two or more dots (.), this is
+ a date string which might have a text month. If a date token has
+ already been seen, it is instead interpreted as a time zone
+ name (e.g., America/New_York).
+
+ If the token is numeric only, then it is either a single field
+ or an ISO 8601 concatenated date (e.g.,
+ 19990113 for January 13, 1999) or time
+ (e.g., 141516 for 14:15:16).
+
+ If the token starts with a plus (+) or minus
+ (-), then it is either a numeric time zone or a special
+ field.
+
+ If the token is an alphabetic string, match up with possible strings:
+
+ See if the token matches any known time zone abbreviation.
+ These abbreviations are supplied by the configuration file
+ described in Section B.4.
+
+ If not found, search an internal table to match
+ the token as either a special string (e.g., today),
+ day (e.g., Thursday),
+ month (e.g., January),
+ or noise word (e.g., at, on).
+
+ If still not found, throw an error.
+
+ When the token is a number or number field:
+
+ If there are eight or six digits,
+ and if no other date fields have been previously read, then interpret
+ as a “concatenated date” (e.g.,
+ 19990118 or 990118).
+ The interpretation is YYYYMMDD or YYMMDD.
+
+ If the token is three digits
+ and a year has already been read, then interpret as day of year.
+
+ If four or six digits and a year has already been read, then
+ interpret as a time (HHMM or HHMMSS).
+
+ If three or more digits and no date fields have yet been found,
+ interpret as a year (this forces yy-mm-dd ordering of the remaining
+ date fields).
+
+ Otherwise the date field ordering is assumed to follow the
+ DateStyle setting: mm-dd-yy, dd-mm-yy, or yy-mm-dd.
+ Throw an error if a month or day field is found to be out of range.
+
+ If BC has been specified, negate the year and add one for
+ internal storage. (There is no year zero in the Gregorian
+ calendar, so numerically 1 BC becomes year zero.)
+
+ If BC was not specified, and if the year field was two digits in length,
+ then adjust the year to four digits. If the field is less than 70, then
+ add 2000, otherwise add 1900.
+
+
Tip
+ Gregorian years AD 1–99 can be entered by using 4 digits with leading
+ zeros (e.g., 0099 is AD 99).
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-invalid-input.html b/pgsql/doc/postgresql/html/datetime-invalid-input.html
new file mode 100644
index 0000000000000000000000000000000000000000..65c9b888ca6b85efdf9e1eda4227ba9484a909d1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-invalid-input.html
@@ -0,0 +1,62 @@
+
+B.2. Handling of Invalid or Ambiguous Timestamps
B.2. Handling of Invalid or Ambiguous Timestamps #
+ Ordinarily, if a date/time string is syntactically valid but contains
+ out-of-range field values, an error will be thrown. For example, input
+ specifying the 31st of February will be rejected.
+
+ During a daylight-savings-time transition, it is possible for a
+ seemingly valid timestamp string to represent a nonexistent or ambiguous
+ timestamp. Such cases are not rejected; the ambiguity is resolved by
+ determining which UTC offset to apply. For example, supposing that the
+ TimeZone parameter is set
+ to America/New_York, consider
+
+ Because that day was a spring-forward transition date in that time zone,
+ there was no civil time instant 2:30AM; clocks jumped forward from 2AM
+ EST to 3AM EDT. PostgreSQL interprets the
+ given time as if it were standard time (UTC-5), which then renders as
+ 3:30AM EDT (UTC-4).
+
+ Conversely, consider the behavior during a fall-back transition:
+
+ On that date, there were two possible interpretations of 1:30AM; there
+ was 1:30AM EDT, and then an hour later after clocks jumped back from
+ 2AM EDT to 1AM EST, there was 1:30AM EST.
+ Again, PostgreSQL interprets the given time
+ as if it were standard time (UTC-5). We can force the other
+ interpretation by specifying daylight-savings time:
+
+ The precise rule that is applied in such cases is that an invalid
+ timestamp that appears to fall within a jump-forward daylight savings
+ transition is assigned the UTC offset that prevailed in the time zone
+ just before the transition, while an ambiguous timestamp that could fall
+ on either side of a jump-back transition is assigned the UTC offset that
+ prevailed just after the transition. In most time zones this is
+ equivalent to saying that “the standard-time interpretation is
+ preferred when in doubt”.
+
+ In all cases, the UTC offset associated with a timestamp can be
+ specified explicitly, using either a numeric UTC offset or a time zone
+ abbreviation that corresponds to a fixed UTC offset. The rule just
+ given applies only when it is necessary to infer a UTC offset for a time
+ zone in which the offset varies.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-julian-dates.html b/pgsql/doc/postgresql/html/datetime-julian-dates.html
new file mode 100644
index 0000000000000000000000000000000000000000..c6d43245f4a4cffc720ce42148338efeb1fa2c52
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-julian-dates.html
@@ -0,0 +1,48 @@
+
+B.7. Julian Dates
+ The Julian Date system is a method for
+ numbering days. It is
+ unrelated to the Julian calendar, though it is confusingly
+ named similarly to that calendar.
+ The Julian Date system was invented by the French scholar
+ Joseph Justus Scaliger (1540–1609)
+ and probably takes its name from Scaliger's father,
+ the Italian scholar Julius Caesar Scaliger (1484–1558).
+
+ In the Julian Date system, each day has a sequential number, starting
+ from JD 0 (which is sometimes called the Julian Date).
+ JD 0 corresponds to 1 January 4713 BC in the Julian calendar, or
+ 24 November 4714 BC in the Gregorian calendar. Julian Date counting
+ is most often used by astronomers for labeling their nightly observations,
+ and therefore a date runs from noon UTC to the next noon UTC, rather than
+ from midnight to midnight: JD 0 designates the 24 hours from noon UTC on
+ 24 November 4714 BC to noon UTC on 25 November 4714 BC.
+
+ Although PostgreSQL supports Julian Date notation for
+ input and output of dates (and also uses Julian dates for some internal
+ datetime calculations), it does not observe the nicety of having dates
+ run from noon to noon. PostgreSQL treats a Julian Date
+ as running from local midnight to local midnight, the same as a normal
+ date.
+
+ This definition does, however, provide a way to obtain the astronomical
+ definition when you need it: do the arithmetic in time
+ zone UTC+12. For example,
+
+=> SELECT extract(julian from '2021-06-23 7:00:00-04'::timestamptz at time zone 'UTC+12');
+ extract
+------------------------------
+ 2459388.95833333333333333333
+(1 row)
+=> SELECT extract(julian from '2021-06-23 8:00:00-04'::timestamptz at time zone 'UTC+12');
+ extract
+--------------------------------------
+ 2459389.0000000000000000000000000000
+(1 row)
+=> SELECT extract(julian from date '2021-06-23');
+ extract
+---------
+ 2459389
+(1 row)
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-keywords.html b/pgsql/doc/postgresql/html/datetime-keywords.html
new file mode 100644
index 0000000000000000000000000000000000000000..6d4bac40444de51cca7b1e85f973fcef43dcacfc
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-keywords.html
@@ -0,0 +1,11 @@
+
+B.3. Date/Time Key Words
+ Table B.1 shows the tokens that are
+ recognized as names of months.
+
Table B.1. Month Names
Month
Abbreviations
January
Jan
February
Feb
March
Mar
April
Apr
May
June
Jun
July
Jul
August
Aug
September
Sep, Sept
October
Oct
November
Nov
December
Dec
+ Table B.2 shows the tokens that are
+ recognized as names of days of the week.
+
Table B.2. Day of the Week Names
Day
Abbreviations
Sunday
Sun
Monday
Mon
Tuesday
Tue, Tues
Wednesday
Wed, Weds
Thursday
Thu, Thur, Thurs
Friday
Fri
Saturday
Sat
+ Table B.3 shows the tokens that serve
+ various modifier purposes.
+
Table B.3. Date/Time Field Modifiers
Identifier
Description
AM
Time is before 12:00
AT
Ignored
JULIAN, JD, J
Next field is Julian Date
ON
Ignored
PM
Time is on or after 12:00
T
Next field is time
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-posix-timezone-specs.html b/pgsql/doc/postgresql/html/datetime-posix-timezone-specs.html
new file mode 100644
index 0000000000000000000000000000000000000000..e79ad27179ac7f5aa2ed696fb2c7859c8bfd8bae
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-posix-timezone-specs.html
@@ -0,0 +1,135 @@
+
+B.5. POSIX Time Zone Specifications
+ PostgreSQL can accept time zone specifications
+ that are written according to the POSIX standard's rules
+ for the TZ environment
+ variable. POSIX time zone specifications are
+ inadequate to deal with the complexity of real-world time zone history,
+ but there are sometimes reasons to use them.
+
+ A POSIX time zone specification has the form
+
+STDoffset [DST [dstoffset] [ , rule] ]
+
+ (For readability, we show spaces between the fields, but spaces should
+ not be used in practice.) The fields are:
+
+ STD is the zone abbreviation to be used
+ for standard time.
+
+ offset is the zone's standard-time offset
+ from UTC.
+
+ DST is the zone abbreviation to be used
+ for daylight-savings time. If this field and the following ones are
+ omitted, the zone uses a fixed UTC offset with no daylight-savings
+ rule.
+
+ dstoffset is the daylight-savings offset
+ from UTC. This field is typically omitted, since it defaults to one
+ hour less than the standard-time offset,
+ which is usually the right thing.
+
+ rule defines the rule for when daylight
+ savings is in effect, as described below.
+
+
+ In this syntax, a zone abbreviation can be a string of letters, such
+ as EST, or an arbitrary string surrounded by angle
+ brackets, such as <UTC-05>.
+ Note that the zone abbreviations given here are only used for output,
+ and even then only in some timestamp output formats. The zone
+ abbreviations recognized in timestamp input are determined as explained
+ in Section B.4.
+
+ The offset fields specify the hours, and optionally minutes and seconds,
+ difference from UTC. They have the format
+ hh[:mm[:ss]]
+ optionally with a leading sign (+
+ or -). The positive sign is used for
+ zones west of Greenwich. (Note that this is the
+ opposite of the ISO-8601 sign convention used elsewhere in
+ PostgreSQL.) hh
+ can have one or two digits; mm
+ and ss (if used) must have two.
+
+ The daylight-savings transition rule has the
+ format
+
+dstdate [/dsttime] ,stddate [/stdtime]
+
+ (As before, spaces should not be included in practice.)
+ The dstdate
+ and dsttime fields define when daylight-savings
+ time starts, while stddate
+ and stdtime define when standard time
+ starts. (In some cases, notably in zones south of the equator, the
+ former might be later in the year than the latter.) The date fields
+ have one of these formats:
+
n
+ A plain integer denotes a day of the year, counting from zero to
+ 364, or to 365 in leap years.
+
Jn
+ In this form, n counts from 1 to 365,
+ and February 29 is not counted even if it is present. (Thus, a
+ transition occurring on February 29 could not be specified this
+ way. However, days after February have the same numbers whether
+ it's a leap year or not, so that this form is usually more useful
+ than the plain-integer form for transitions on fixed dates.)
+
Mm.n.d
+ This form specifies a transition that always happens during the same
+ month and on the same day of the week. m
+ identifies the month, from 1 to 12. n
+ specifies the n'th occurrence of the
+ weekday identified by d.
+ n is a number between 1 and 4, or 5
+ meaning the last occurrence of that weekday in the month (which
+ could be the fourth or the fifth). d is
+ a number between 0 and 6, with 0 indicating Sunday.
+ For example, M3.2.0 means “the second
+ Sunday in March”.
+
+
Note
+ The M format is sufficient to describe many common
+ daylight-savings transition laws. But note that none of these variants
+ can deal with daylight-savings law changes, so in practice the
+ historical data stored for named time zones (in the IANA time zone
+ database) is necessary to interpret past time stamps correctly.
+
+ The time fields in a transition rule have the same format as the offset
+ fields described previously, except that they cannot contain signs.
+ They define the current local time at which the change to the other
+ time occurs. If omitted, they default to 02:00:00.
+
+ If a daylight-savings abbreviation is given but the
+ transition rule field is omitted,
+ the fallback behavior is to use the
+ rule M3.2.0,M11.1.0, which corresponds to USA
+ practice as of 2020 (that is, spring forward on the second Sunday of
+ March, fall back on the first Sunday of November, both transitions
+ occurring at 2AM prevailing time). Note that this rule does not
+ give correct USA transition dates for years before 2007.
+
+ As an example, CET-1CEST,M3.5.0,M10.5.0/3 describes
+ current (as of 2020) timekeeping practice in Paris. This specification
+ says that standard time has the abbreviation CET and
+ is one hour ahead (east) of UTC; daylight savings time has the
+ abbreviation CEST and is implicitly two hours ahead
+ of UTC; daylight savings time begins on the last Sunday in March at 2AM
+ CET and ends on the last Sunday in October at 3AM CEST.
+
+ The four timezone names EST5EDT,
+ CST6CDT, MST7MDT,
+ and PST8PDT look like they are POSIX zone
+ specifications. However, they actually are treated as named time zones
+ because (for historical reasons) there are files by those names in the
+ IANA time zone database. The practical implication of this is that
+ these zone names will produce valid historical USA daylight-savings
+ transitions, even when a plain POSIX specification would not.
+
+ One should be wary that it is easy to misspell a POSIX-style time zone
+ specification, since there is no check on the reasonableness of the
+ zone abbreviation(s). For example, SET TIMEZONE TO
+ FOOBAR0 will work, leaving the system effectively using a
+ rather peculiar abbreviation for UTC.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/datetime-units-history.html b/pgsql/doc/postgresql/html/datetime-units-history.html
new file mode 100644
index 0000000000000000000000000000000000000000..3908d53d77481d0877c99340ea8154dbf6c2ec67
--- /dev/null
+++ b/pgsql/doc/postgresql/html/datetime-units-history.html
@@ -0,0 +1,87 @@
+
+B.6. History of Units
+ The SQL standard states that “Within the definition of a
+ ‘datetime literal’, the ‘datetime
+ values’ are constrained by the natural rules for dates and
+ times according to the Gregorian calendar”.
+ PostgreSQL follows the SQL
+ standard's lead by counting dates exclusively in the Gregorian
+ calendar, even for years before that calendar was in use.
+ This rule is known as the proleptic Gregorian calendar.
+
+ The Julian calendar was introduced by Julius Caesar in 45 BC.
+ It was in common use in the Western world
+ until the year 1582, when countries started changing to the Gregorian
+ calendar. In the Julian calendar, the tropical year is
+ approximated as 365 1/4 days = 365.25 days. This gives an error of
+ about 1 day in 128 years.
+
+ The accumulating calendar error prompted
+ Pope Gregory XIII to reform the calendar in accordance with
+ instructions from the Council of Trent.
+ In the Gregorian calendar, the tropical year is approximated as
+ 365 + 97 / 400 days = 365.2425 days. Thus it takes approximately 3300
+ years for the tropical year to shift one day with respect to the
+ Gregorian calendar.
+
+ The approximation 365+97/400 is achieved by having 97 leap years
+ every 400 years, using the following rules:
+
+
+ Every year divisible by 4 is a leap year.
+
+ However, every year divisible by 100 is not a leap year.
+
+ However, every year divisible by 400 is a leap year after all.
+
+
+ So, 1700, 1800, 1900, 2100, and 2200 are not leap years. But 1600,
+ 2000, and 2400 are leap years.
+
+ By contrast, in the older Julian calendar all years divisible by 4 are leap
+ years.
+
+ The papal bull of February 1582 decreed that 10 days should be dropped
+ from October 1582 so that 15 October should follow immediately after
+ 4 October.
+ This was observed in Italy, Poland, Portugal, and Spain. Other Catholic
+ countries followed shortly after, but Protestant countries were
+ reluctant to change, and the Greek Orthodox countries didn't change
+ until the start of the 20th century.
+
+ The reform was observed by Great Britain and its dominions (including what
+ is now the USA) in 1752.
+ Thus 2 September 1752 was followed by 14 September 1752.
+
+ This is why Unix systems that have the cal program
+ produce the following:
+
+
+$ cal 9 1752
+ September 1752
+ S M Tu W Th F S
+ 1 2 14 15 16
+17 18 19 20 21 22 23
+24 25 26 27 28 29 30
+
+
+ But, of course, this calendar is only valid for Great Britain and
+ dominions, not other places.
+ Since it would be difficult and confusing to try to track the actual
+ calendars that were in use in various places at various times,
+ PostgreSQL does not try, but rather follows the Gregorian
+ calendar rules for all dates, even though this method is not historically
+ accurate.
+
+ Different calendars have been developed in various parts of the
+ world, many predating the Gregorian system.
+
+ For example,
+ the beginnings of the Chinese calendar can be traced back to the 14th
+ century BC. Legend has it that the Emperor Huangdi invented that
+ calendar in 2637 BC.
+
+ The People's Republic of China uses the Gregorian calendar
+ for civil purposes. The Chinese calendar is used for determining
+ festivals.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dblink.html b/pgsql/doc/postgresql/html/dblink.html
new file mode 100644
index 0000000000000000000000000000000000000000..7b75933d24400f6e0e2141e93563c82e62b9838f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dblink.html
@@ -0,0 +1,18 @@
+
+F.12. dblink — connect to other PostgreSQL databases
F.12. dblink — connect to other PostgreSQL databases
dblink_get_pkey — returns the positions and field names of a relation's
+ primary key fields
+
dblink_build_sql_insert —
+ builds an INSERT statement using a local tuple, replacing the
+ primary key field values with alternative supplied values
+
dblink_build_sql_delete — builds a DELETE statement using supplied values for primary
+ key field values
+
dblink_build_sql_update — builds an UPDATE statement using a local tuple, replacing
+ the primary key field values with alternative supplied values
+
+ dblink is a module that supports connections to
+ other PostgreSQL databases from within a database
+ session.
+
+ See also postgres_fdw, which provides roughly the same
+ functionality using a more modern and standards-compliant infrastructure.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-alter.html b/pgsql/doc/postgresql/html/ddl-alter.html
new file mode 100644
index 0000000000000000000000000000000000000000..c11c98821897346f458591cdeaafcd5c6854b8ed
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-alter.html
@@ -0,0 +1,156 @@
+
+5.6. Modifying Tables
+ When you create a table and you realize that you made a mistake, or
+ the requirements of the application change, you can drop the
+ table and create it again. But this is not a convenient option if
+ the table is already filled with data, or if the table is
+ referenced by other database objects (for instance a foreign key
+ constraint). Therefore PostgreSQL
+ provides a family of commands to make modifications to existing
+ tables. Note that this is conceptually distinct from altering
+ the data contained in the table: here we are interested in altering
+ the definition, or structure, of the table.
+
+ You can:
+
Add columns
Remove columns
Add constraints
Remove constraints
Change default values
Change column data types
Rename columns
Rename tables
+
+ All these actions are performed using the
+ ALTER TABLE
+ command, whose reference page contains details beyond those given
+ here.
+
+ The new column is initially filled with whatever default
+ value is given (null if you don't specify a DEFAULT clause).
+
Tip
+ From PostgreSQL 11, adding a column with
+ a constant default value no longer means that each row of the table
+ needs to be updated when the ALTER TABLE statement
+ is executed. Instead, the default value will be returned the next time
+ the row is accessed, and applied when the table is rewritten, making
+ the ALTER TABLE very fast even on large tables.
+
+ However, if the default value is volatile (e.g.,
+ clock_timestamp())
+ each row will need to be updated with the value calculated at the time
+ ALTER TABLE is executed. To avoid a potentially
+ lengthy update operation, particularly if you intend to fill the column
+ with mostly nondefault values anyway, it may be preferable to add the
+ column with no default, insert the correct values using
+ UPDATE, and then add any desired default as described
+ below.
+
+ You can also define constraints on the column at the same time,
+ using the usual syntax:
+
+ In fact all the options that can be applied to a column description
+ in CREATE TABLE can be used here. Keep in mind however
+ that the default value must satisfy the given constraints, or the
+ ADD will fail. Alternatively, you can add
+ constraints later (see below) after you've filled in the new column
+ correctly.
+
+ Whatever data was in the column disappears. Table constraints involving
+ the column are dropped, too. However, if the column is referenced by a
+ foreign key constraint of another table,
+ PostgreSQL will not silently drop that
+ constraint. You can authorize dropping everything that depends on
+ the column by adding CASCADE:
+
+ALTER TABLE products DROP COLUMN description CASCADE;
+
+ See Section 5.14 for a description of the general
+ mechanism behind this.
+
+ To remove a constraint you need to know its name. If you gave it
+ a name then that's easy. Otherwise the system assigned a
+ generated name, which you need to find out. The
+ psql command \d
+ tablename can be helpful
+ here; other interfaces might also provide a way to inspect table
+ details. Then the command is:
+
+ALTER TABLE products DROP CONSTRAINT some_name;
+
+ (If you are dealing with a generated constraint name like $2,
+ don't forget that you'll need to double-quote it to make it a valid
+ identifier.)
+
+ As with dropping a column, you need to add CASCADE if you
+ want to drop a constraint that something else depends on. An example
+ is that a foreign key constraint depends on a unique or primary key
+ constraint on the referenced column(s).
+
+ This works the same for all constraint types except not-null
+ constraints. To drop a not null constraint use:
+
+ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;
+
+ (Recall that not-null constraints do not have names.)
+
+ To set a new default for a column, use a command like:
+
+ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
+
+ Note that this doesn't affect any existing rows in the table, it
+ just changes the default for future INSERT commands.
+
+ To remove any default value, use:
+
+ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
+
+ This is effectively the same as setting the default to null.
+ As a consequence, it is not an error
+ to drop a default where one hadn't been defined, because the
+ default is implicitly the null value.
+
+ To convert a column to a different data type, use a command like:
+
+ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
+
+ This will succeed only if each existing entry in the column can be
+ converted to the new type by an implicit cast. If a more complex
+ conversion is needed, you can add a USING clause that
+ specifies how to compute the new values from the old.
+
+ PostgreSQL will attempt to convert the column's
+ default value (if any) to the new type, as well as any constraints
+ that involve the column. But these conversions might fail, or might
+ produce surprising results. It's often best to drop any constraints
+ on the column before altering its type, and then add back suitably
+ modified constraints afterwards.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-basics.html b/pgsql/doc/postgresql/html/ddl-basics.html
new file mode 100644
index 0000000000000000000000000000000000000000..0cad8f508b2483779e2495b0fc960bfd1e2243bd
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-basics.html
@@ -0,0 +1,101 @@
+
+5.1. Table Basics
+ A table in a relational database is much like a table on paper: It
+ consists of rows and columns. The number and order of the columns
+ is fixed, and each column has a name. The number of rows is
+ variable — it reflects how much data is stored at a given moment.
+ SQL does not make any guarantees about the order of the rows in a
+ table. When a table is read, the rows will appear in an unspecified order,
+ unless sorting is explicitly requested. This is covered in Chapter 7. Furthermore, SQL does not assign unique
+ identifiers to rows, so it is possible to have several completely
+ identical rows in a table. This is a consequence of the
+ mathematical model that underlies SQL but is usually not desirable.
+ Later in this chapter we will see how to deal with this issue.
+
+ Each column has a data type. The data type constrains the set of
+ possible values that can be assigned to a column and assigns
+ semantics to the data stored in the column so that it can be used
+ for computations. For instance, a column declared to be of a
+ numerical type will not accept arbitrary text strings, and the data
+ stored in such a column can be used for mathematical computations.
+ By contrast, a column declared to be of a character string type
+ will accept almost any kind of data but it does not lend itself to
+ mathematical calculations, although other operations such as string
+ concatenation are available.
+
+ PostgreSQL includes a sizable set of
+ built-in data types that fit many applications. Users can also
+ define their own data types. Most built-in data types have obvious
+ names and semantics, so we defer a detailed explanation to Chapter 8. Some of the frequently used data types are
+ integer for whole numbers, numeric for
+ possibly fractional numbers, text for character
+ strings, date for dates, time for
+ time-of-day values, and timestamp for values
+ containing both date and time.
+
+ To create a table, you use the aptly named CREATE TABLE command.
+ In this command you specify at least a name for the new table, the
+ names of the columns and the data type of each column. For
+ example:
+
+ This creates a table named my_first_table with
+ two columns. The first column is named
+ first_column and has a data type of
+ text; the second column has the name
+ second_column and the type integer.
+ The table and column names follow the identifier syntax explained
+ in Section 4.1.1. The type names are
+ usually also identifiers, but there are some exceptions. Note that the
+ column list is comma-separated and surrounded by parentheses.
+
+ Of course, the previous example was heavily contrived. Normally,
+ you would give names to your tables and columns that convey what
+ kind of data they store. So let's look at a more realistic
+ example:
+
+ (The numeric type can store fractional components, as
+ would be typical of monetary amounts.)
+
Tip
+ When you create many interrelated tables it is wise to choose a
+ consistent naming pattern for the tables and columns. For
+ instance, there is a choice of using singular or plural nouns for
+ table names, both of which are favored by some theorist or other.
+
+ There is a limit on how many columns a table can contain.
+ Depending on the column types, it is between 250 and 1600.
+ However, defining a table with anywhere near this many columns is
+ highly unusual and often a questionable design.
+
+ If you no longer need a table, you can remove it using the DROP TABLE command.
+ For example:
+
+ Attempting to drop a table that does not exist is an error.
+ Nevertheless, it is common in SQL script files to unconditionally
+ try to drop each table before creating it, ignoring any error
+ messages, so that the script works whether or not the table exists.
+ (If you like, you can use the DROP TABLE IF EXISTS variant
+ to avoid the error messages, but this is not standard SQL.)
+
+ If you need to modify a table that already exists, see Section 5.6 later in this chapter.
+
+ With the tools discussed so far you can create fully functional
+ tables. The remainder of this chapter is concerned with adding
+ features to the table definition to ensure data integrity,
+ security, or convenience. If you are eager to fill your tables with
+ data now you can skip ahead to Chapter 6 and read the
+ rest of this chapter later.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-constraints.html b/pgsql/doc/postgresql/html/ddl-constraints.html
new file mode 100644
index 0000000000000000000000000000000000000000..7071e49354faad889477317d5c4757af0b56c991
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-constraints.html
@@ -0,0 +1,607 @@
+
+5.4. Constraints
+ Data types are a way to limit the kind of data that can be stored
+ in a table. For many applications, however, the constraint they
+ provide is too coarse. For example, a column containing a product
+ price should probably only accept positive values. But there is no
+ standard data type that accepts only positive numbers. Another issue is
+ that you might want to constrain column data with respect to other
+ columns or rows. For example, in a table containing product
+ information, there should be only one row for each product number.
+
+ To that end, SQL allows you to define constraints on columns and
+ tables. Constraints give you as much control over the data in your
+ tables as you wish. If a user attempts to store data in a column
+ that would violate a constraint, an error is raised. This applies
+ even if the value came from the default value definition.
+
+ A check constraint is the most generic constraint type. It allows
+ you to specify that the value in a certain column must satisfy a
+ Boolean (truth-value) expression. For instance, to require positive
+ product prices, you could use:
+
+ As you see, the constraint definition comes after the data type,
+ just like default value definitions. Default values and
+ constraints can be listed in any order. A check constraint
+ consists of the key word CHECK followed by an
+ expression in parentheses. The check constraint expression should
+ involve the column thus constrained, otherwise the constraint
+ would not make too much sense.
+
+ You can also give the constraint a separate name. This clarifies
+ error messages and allows you to refer to the constraint when you
+ need to change it. The syntax is:
+
+ So, to specify a named constraint, use the key word
+ CONSTRAINT followed by an identifier followed
+ by the constraint definition. (If you don't specify a constraint
+ name in this way, the system chooses a name for you.)
+
+ A check constraint can also refer to several columns. Say you
+ store a regular price and a discounted price, and you want to
+ ensure that the discounted price is lower than the regular price:
+
+ The first two constraints should look familiar. The third one
+ uses a new syntax. It is not attached to a particular column,
+ instead it appears as a separate item in the comma-separated
+ column list. Column definitions and these constraint
+ definitions can be listed in mixed order.
+
+ We say that the first two constraints are column constraints, whereas the
+ third one is a table constraint because it is written separately
+ from any one column definition. Column constraints can also be
+ written as table constraints, while the reverse is not necessarily
+ possible, since a column constraint is supposed to refer to only the
+ column it is attached to. (PostgreSQL doesn't
+ enforce that rule, but you should follow it if you want your table
+ definitions to work with other database systems.) The above example could
+ also be written as:
+
+ It should be noted that a check constraint is satisfied if the
+ check expression evaluates to true or the null value. Since most
+ expressions will evaluate to the null value if any operand is null,
+ they will not prevent null values in the constrained columns. To
+ ensure that a column does not contain null values, the not-null
+ constraint described in the next section can be used.
+
Note
+ PostgreSQL does not support
+ CHECK constraints that reference table data other than
+ the new or updated row being checked. While a CHECK
+ constraint that violates this rule may appear to work in simple
+ tests, it cannot guarantee that the database will not reach a state
+ in which the constraint condition is false (due to subsequent changes
+ of the other row(s) involved). This would cause a database dump and
+ restore to fail. The restore could fail even when the complete
+ database state is consistent with the constraint, due to rows not
+ being loaded in an order that will satisfy the constraint. If
+ possible, use UNIQUE, EXCLUDE,
+ or FOREIGN KEY constraints to express
+ cross-row and cross-table restrictions.
+
+ If what you desire is a one-time check against other rows at row
+ insertion, rather than a continuously-maintained consistency
+ guarantee, a custom trigger can be used
+ to implement that. (This approach avoids the dump/restore problem because
+ pg_dump does not reinstall triggers until after
+ restoring data, so that the check will not be enforced during a
+ dump/restore.)
+
Note
+ PostgreSQL assumes that
+ CHECK constraints' conditions are immutable, that
+ is, they will always give the same result for the same input row.
+ This assumption is what justifies examining CHECK
+ constraints only when rows are inserted or updated, and not at other
+ times. (The warning above about not referencing other table data is
+ really a special case of this restriction.)
+
+ An example of a common way to break this assumption is to reference a
+ user-defined function in a CHECK expression, and
+ then change the behavior of that
+ function. PostgreSQL does not disallow
+ that, but it will not notice if there are rows in the table that now
+ violate the CHECK constraint. That would cause a
+ subsequent database dump and restore to fail.
+ The recommended way to handle such a change is to drop the constraint
+ (using ALTER TABLE), adjust the function definition,
+ and re-add the constraint, thereby rechecking it against all table rows.
+
+ A not-null constraint simply specifies that a column must not
+ assume the null value. A syntax example:
+
+CREATE TABLE products (
+ product_no integer NOT NULL,
+ name text NOT NULL,
+ price numeric
+);
+
+
+ A not-null constraint is always written as a column constraint. A
+ not-null constraint is functionally equivalent to creating a check
+ constraint CHECK (column_name
+ IS NOT NULL), but in
+ PostgreSQL creating an explicit
+ not-null constraint is more efficient. The drawback is that you
+ cannot give explicit names to not-null constraints created this
+ way.
+
+ Of course, a column can have more than one constraint. Just write
+ the constraints one after another:
+
+CREATE TABLE products (
+ product_no integer NOT NULL,
+ name text NOT NULL,
+ price numeric NOT NULL CHECK (price > 0)
+);
+
+ The order doesn't matter. It does not necessarily determine in which
+ order the constraints are checked.
+
+ The NOT NULL constraint has an inverse: the
+ NULL constraint. This does not mean that the
+ column must be null, which would surely be useless. Instead, this
+ simply selects the default behavior that the column might be null.
+ The NULL constraint is not present in the SQL
+ standard and should not be used in portable applications. (It was
+ only added to PostgreSQL to be
+ compatible with some other database systems.) Some users, however,
+ like it because it makes it easy to toggle the constraint in a
+ script file. For example, you could start with:
+
+CREATE TABLE products (
+ product_no integer NULL,
+ name text NULL,
+ price numeric NULL
+);
+
+ and then insert the NOT key word where desired.
+
Tip
+ In most database designs the majority of columns should be marked
+ not null.
+
+ Unique constraints ensure that the data contained in a column, or a
+ group of columns, is unique among all the rows in the
+ table. The syntax is:
+
+ To define a unique constraint for a group of columns, write it as a
+ table constraint with the column names separated by commas:
+
+CREATE TABLE example (
+ a integer,
+ b integer,
+ c integer,
+ UNIQUE (a, c)
+);
+
+ This specifies that the combination of values in the indicated columns
+ is unique across the whole table, though any one of the columns
+ need not be (and ordinarily isn't) unique.
+
+ You can assign your own name for a unique constraint, in the usual way:
+
+ Adding a unique constraint will automatically create a unique B-tree
+ index on the column or group of columns listed in the constraint.
+ A uniqueness restriction covering only some rows cannot be written as
+ a unique constraint, but it is possible to enforce such a restriction by
+ creating a unique partial index.
+
+ In general, a unique constraint is violated if there is more than
+ one row in the table where the values of all of the
+ columns included in the constraint are equal.
+ By default, two null values are not considered equal in this
+ comparison. That means even in the presence of a
+ unique constraint it is possible to store duplicate
+ rows that contain a null value in at least one of the constrained
+ columns. This behavior can be changed by adding the clause NULLS
+ NOT DISTINCT, like
+
+CREATE TABLE products (
+ product_no integer UNIQUE NULLS NOT DISTINCT,
+ name text,
+ price numeric
+);
+
+ The default behavior can be specified explicitly using NULLS
+ DISTINCT. The default null treatment in unique constraints is
+ implementation-defined according to the SQL standard, and other
+ implementations have a different behavior. So be careful when developing
+ applications that are intended to be portable.
+
+ A primary key constraint indicates that a column, or group of columns,
+ can be used as a unique identifier for rows in the table. This
+ requires that the values be both unique and not null. So, the following
+ two table definitions accept the same data:
+
+CREATE TABLE products (
+ product_no integer UNIQUE NOT NULL,
+ name text,
+ price numeric
+);
+
+ Primary keys can span more than one column; the syntax
+ is similar to unique constraints:
+
+CREATE TABLE example (
+ a integer,
+ b integer,
+ c integer,
+ PRIMARY KEY (a, c)
+);
+
+
+ Adding a primary key will automatically create a unique B-tree index
+ on the column or group of columns listed in the primary key, and will
+ force the column(s) to be marked NOT NULL.
+
+ A table can have at most one primary key. (There can be any number
+ of unique and not-null constraints, which are functionally almost the
+ same thing, but only one can be identified as the primary key.)
+ Relational database theory
+ dictates that every table must have a primary key. This rule is
+ not enforced by PostgreSQL, but it is
+ usually best to follow it.
+
+ Primary keys are useful both for
+ documentation purposes and for client applications. For example,
+ a GUI application that allows modifying row values probably needs
+ to know the primary key of a table to be able to identify rows
+ uniquely. There are also various ways in which the database system
+ makes use of a primary key if one has been declared; for example,
+ the primary key defines the default target column(s) for foreign keys
+ referencing its table.
+
+ A foreign key constraint specifies that the values in a column (or
+ a group of columns) must match the values appearing in some row
+ of another table.
+ We say this maintains the referential
+ integrity between two related tables.
+
+ Say you have the product table that we have used several times already:
+
+ Let's also assume you have a table storing orders of those
+ products. We want to ensure that the orders table only contains
+ orders of products that actually exist. So we define a foreign
+ key constraint in the orders table that references the products
+ table:
+
+ Now it is impossible to create orders with non-NULL
+ product_no entries that do not appear in the
+ products table.
+
+ We say that in this situation the orders table is the
+ referencing table and the products table is
+ the referenced table. Similarly, there are
+ referencing and referenced columns.
+
+ because in absence of a column list the primary key of the
+ referenced table is used as the referenced column(s).
+
+ You can assign your own name for a foreign key constraint,
+ in the usual way.
+
+ A foreign key can also constrain and reference a group of columns.
+ As usual, it then needs to be written in table constraint form.
+ Here is a contrived syntax example:
+
+CREATE TABLE t1 (
+ a integer PRIMARY KEY,
+ b integer,
+ c integer,
+ FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)
+);
+
+ Of course, the number and type of the constrained columns need to
+ match the number and type of the referenced columns.
+
+ Sometimes it is useful for the “other table” of a
+ foreign key constraint to be the same table; this is called
+ a self-referential foreign key. For
+ example, if you want rows of a table to represent nodes of a tree
+ structure, you could write
+
+ A top-level node would have NULL parent_id,
+ while non-NULL parent_id entries would be
+ constrained to reference valid rows of the table.
+
+ A table can have more than one foreign key constraint. This is
+ used to implement many-to-many relationships between tables. Say
+ you have tables about products and orders, but now you want to
+ allow one order to contain possibly many products (which the
+ structure above did not allow). You could use this table structure:
+
+ Notice that the primary key overlaps with the foreign keys in
+ the last table.
+
+ We know that the foreign keys disallow creation of orders that
+ do not relate to any products. But what if a product is removed
+ after an order is created that references it? SQL allows you to
+ handle that as well. Intuitively, we have a few options:
+
Disallow deleting a referenced product
Delete the orders as well
Something else?
+
+ To illustrate this, let's implement the following policy on the
+ many-to-many relationship example above: when someone wants to
+ remove a product that is still referenced by an order (via
+ order_items), we disallow it. If someone
+ removes an order, the order items are removed as well:
+
+ Restricting and cascading deletes are the two most common options.
+ RESTRICT prevents deletion of a
+ referenced row. NO ACTION means that if any
+ referencing rows still exist when the constraint is checked, an error
+ is raised; this is the default behavior if you do not specify anything.
+ (The essential difference between these two choices is that
+ NO ACTION allows the check to be deferred until
+ later in the transaction, whereas RESTRICT does not.)
+ CASCADE specifies that when a referenced row is deleted,
+ row(s) referencing it should be automatically deleted as well.
+ There are two other options:
+ SET NULL and SET DEFAULT.
+ These cause the referencing column(s) in the referencing row(s)
+ to be set to nulls or their default
+ values, respectively, when the referenced row is deleted.
+ Note that these do not excuse you from observing any constraints.
+ For example, if an action specifies SET DEFAULT
+ but the default value would not satisfy the foreign key constraint, the
+ operation will fail.
+
+ The appropriate choice of ON DELETE action depends on
+ what kinds of objects the related tables represent. When the referencing
+ table represents something that is a component of what is represented by
+ the referenced table and cannot exist independently, then
+ CASCADE could be appropriate. If the two tables
+ represent independent objects, then RESTRICT or
+ NO ACTION is more appropriate; an application that
+ actually wants to delete both objects would then have to be explicit about
+ this and run two delete commands. In the above example, order items are
+ part of an order, and it is convenient if they are deleted automatically
+ if an order is deleted. But products and orders are different things, and
+ so making a deletion of a product automatically cause the deletion of some
+ order items could be considered problematic. The actions SET
+ NULL or SET DEFAULT can be appropriate if a
+ foreign-key relationship represents optional information. For example, if
+ the products table contained a reference to a product manager, and the
+ product manager entry gets deleted, then setting the product's product
+ manager to null or a default might be useful.
+
+ The actions SET NULL and SET DEFAULT
+ can take a column list to specify which columns to set. Normally, all
+ columns of the foreign-key constraint are set; setting only a subset is
+ useful in some special cases. Consider the following example:
+
+ Without the specification of the column, the foreign key would also set
+ the column tenant_id to null, but that column is still
+ required as part of the primary key.
+
+ Analogous to ON DELETE there is also
+ ON UPDATE which is invoked when a referenced
+ column is changed (updated). The possible actions are the same,
+ except that column lists cannot be specified for SET
+ NULL and SET DEFAULT.
+ In this case, CASCADE means that the updated values of the
+ referenced column(s) should be copied into the referencing row(s).
+
+ Normally, a referencing row need not satisfy the foreign key constraint
+ if any of its referencing columns are null. If MATCH FULL
+ is added to the foreign key declaration, a referencing row escapes
+ satisfying the constraint only if all its referencing columns are null
+ (so a mix of null and non-null values is guaranteed to fail a
+ MATCH FULL constraint). If you don't want referencing rows
+ to be able to avoid satisfying the foreign key constraint, declare the
+ referencing column(s) as NOT NULL.
+
+ A foreign key must reference columns that either are a primary key or
+ form a unique constraint, or are columns from a non-partial unique index.
+ This means that the referenced columns always have an index to allow
+ efficient lookups on whether a referencing row has a match. Since a
+ DELETE of a row from the referenced table or an
+ UPDATE of a referenced column will require a scan of
+ the referencing table for rows matching the old value, it is often a good
+ idea to index the referencing columns too. Because this is not always
+ needed, and there are many choices available on how to index, the
+ declaration of a foreign key constraint does not automatically create an
+ index on the referencing columns.
+
+ More information about updating and deleting data is in Chapter 6. Also see the description of foreign key constraint
+ syntax in the reference documentation for
+ CREATE TABLE.
+
+ Exclusion constraints ensure that if any two rows are compared on
+ the specified columns or expressions using the specified operators,
+ at least one of these operator comparisons will return false or null.
+ The syntax is:
+
+CREATE TABLE circles (
+ c circle,
+ EXCLUDE USING gist (c WITH &&)
+);
+
+ Adding an exclusion constraint will automatically create an index
+ of the type specified in the constraint declaration.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-default.html b/pgsql/doc/postgresql/html/ddl-default.html
new file mode 100644
index 0000000000000000000000000000000000000000..3206fc8befa286b4d8c60f804994c1e48b9c93f8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-default.html
@@ -0,0 +1,49 @@
+
+5.2. Default Values
+ A column can be assigned a default value. When a new row is
+ created and no values are specified for some of the columns, those
+ columns will be filled with their respective default values. A
+ data manipulation command can also request explicitly that a column
+ be set to its default value, without having to know what that value is.
+ (Details about data manipulation commands are in Chapter 6.)
+
+
+ If no default value is declared explicitly, the default value is the
+ null value. This usually makes sense because a null value can
+ be considered to represent unknown data.
+
+ In a table definition, default values are listed after the column
+ data type. For example:
+
+ The default value can be an expression, which will be
+ evaluated whenever the default value is inserted
+ (not when the table is created). A common example
+ is for a timestamp column to have a default of CURRENT_TIMESTAMP,
+ so that it gets set to the time of row insertion. Another common
+ example is generating a “serial number” for each row.
+ In PostgreSQL this is typically done by
+ something like:
+
+ where the nextval() function supplies successive values
+ from a sequence object (see Section 9.17). This arrangement is sufficiently common
+ that there's a special shorthand for it:
+
+ The SERIAL shorthand is discussed further in Section 8.1.4.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-depend.html b/pgsql/doc/postgresql/html/ddl-depend.html
new file mode 100644
index 0000000000000000000000000000000000000000..b1c9e0f06d2629252b5e7946e95a7cf10e0afee6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-depend.html
@@ -0,0 +1,99 @@
+
+5.14. Dependency Tracking
+ When you create complex database structures involving many tables
+ with foreign key constraints, views, triggers, functions, etc. you
+ implicitly create a net of dependencies between the objects.
+ For instance, a table with a foreign key constraint depends on the
+ table it references.
+
+ To ensure the integrity of the entire database structure,
+ PostgreSQL makes sure that you cannot
+ drop objects that other objects still depend on. For example,
+ attempting to drop the products table we considered in Section 5.4.5, with the orders table depending on
+ it, would result in an error message like this:
+
+DROP TABLE products;
+
+ERROR: cannot drop table products because other objects depend on it
+DETAIL: constraint orders_product_no_fkey on table orders depends on table products
+HINT: Use DROP ... CASCADE to drop the dependent objects too.
+
+ The error message contains a useful hint: if you do not want to
+ bother deleting all the dependent objects individually, you can run:
+
+DROP TABLE products CASCADE;
+
+ and all the dependent objects will be removed, as will any objects
+ that depend on them, recursively. In this case, it doesn't remove
+ the orders table, it only removes the foreign key constraint.
+ It stops there because nothing depends on the foreign key constraint.
+ (If you want to check what DROP ... CASCADE will do,
+ run DROP without CASCADE and read the
+ DETAIL output.)
+
+ Almost all DROP commands in PostgreSQL support
+ specifying CASCADE. Of course, the nature of
+ the possible dependencies varies with the type of the object. You
+ can also write RESTRICT instead of
+ CASCADE to get the default behavior, which is to
+ prevent dropping objects that any other objects depend on.
+
Note
+ According to the SQL standard, specifying either
+ RESTRICT or CASCADE is
+ required in a DROP command. No database system actually
+ enforces that rule, but whether the default behavior
+ is RESTRICT or CASCADE varies
+ across systems.
+
+ If a DROP command lists multiple
+ objects, CASCADE is only required when there are
+ dependencies outside the specified group. For example, when saying
+ DROP TABLE tab1, tab2 the existence of a foreign
+ key referencing tab1 from tab2 would not mean
+ that CASCADE is needed to succeed.
+
+ For a user-defined function or procedure whose body is defined as a string
+ literal, PostgreSQL tracks
+ dependencies associated with the function's externally-visible properties,
+ such as its argument and result types, but not dependencies
+ that could only be known by examining the function body. As an example,
+ consider this situation:
+
+
+CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow',
+ 'green', 'blue', 'purple');
+
+CREATE TABLE my_colors (color rainbow, note text);
+
+CREATE FUNCTION get_color_note (rainbow) RETURNS text AS
+ 'SELECT note FROM my_colors WHERE color = $1'
+ LANGUAGE SQL;
+
+
+ (See Section 38.5 for an explanation of SQL-language
+ functions.) PostgreSQL will be aware that
+ the get_color_note function depends on the rainbow
+ type: dropping the type would force dropping the function, because its
+ argument type would no longer be defined. But PostgreSQL
+ will not consider get_color_note to depend on
+ the my_colors table, and so will not drop the function if
+ the table is dropped. While there are disadvantages to this approach,
+ there are also benefits. The function is still valid in some sense if the
+ table is missing, though executing it would cause an error; creating a new
+ table of the same name would allow the function to work again.
+
+ On the other hand, for a SQL-language function or procedure whose body
+ is written in SQL-standard style, the body is parsed at function
+ definition time and all dependencies recognized by the parser are
+ stored. Thus, if we write the function above as
+
+
+CREATE FUNCTION get_color_note (rainbow) RETURNS text
+BEGIN ATOMIC
+ SELECT note FROM my_colors WHERE color = $1;
+END;
+
+
+ then the function's dependency on the my_colors
+ table will be known and enforced by DROP.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-foreign-data.html b/pgsql/doc/postgresql/html/ddl-foreign-data.html
new file mode 100644
index 0000000000000000000000000000000000000000..1f4c07603c11ca1fdc0e0b98e09f63b37e6da67d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-foreign-data.html
@@ -0,0 +1,41 @@
+
+5.12. Foreign Data
+ PostgreSQL implements portions of the SQL/MED
+ specification, allowing you to access data that resides outside
+ PostgreSQL using regular SQL queries. Such data is referred to as
+ foreign data. (Note that this usage is not to be confused
+ with foreign keys, which are a type of constraint within the database.)
+
+ Foreign data is accessed with help from a
+ foreign data wrapper. A foreign data wrapper is a
+ library that can communicate with an external data source, hiding the
+ details of connecting to the data source and obtaining data from it.
+ There are some foreign data wrappers available as contrib
+ modules; see Appendix F. Other kinds of foreign data
+ wrappers might be found as third party products. If none of the existing
+ foreign data wrappers suit your needs, you can write your own; see Chapter 59.
+
+ To access foreign data, you need to create a foreign server
+ object, which defines how to connect to a particular external data source
+ according to the set of options used by its supporting foreign data
+ wrapper. Then you need to create one or more foreign
+ tables, which define the structure of the remote data. A
+ foreign table can be used in queries just like a normal table, but a
+ foreign table has no storage in the PostgreSQL server. Whenever it is
+ used, PostgreSQL asks the foreign data wrapper
+ to fetch data from the external source, or transmit data to the external
+ source in the case of update commands.
+
+ Accessing remote data may require authenticating to the external
+ data source. This information can be provided by a
+ user mapping, which can provide additional data
+ such as user names and passwords based
+ on the current PostgreSQL role.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-generated-columns.html b/pgsql/doc/postgresql/html/ddl-generated-columns.html
new file mode 100644
index 0000000000000000000000000000000000000000..e010198b79891dc94676e9fd50dd422dc7de400a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-generated-columns.html
@@ -0,0 +1,106 @@
+
+5.3. Generated Columns
+ A generated column is a special column that is always computed from other
+ columns. Thus, it is for columns what a view is for tables. There are two
+ kinds of generated columns: stored and virtual. A stored generated column
+ is computed when it is written (inserted or updated) and occupies storage
+ as if it were a normal column. A virtual generated column occupies no
+ storage and is computed when it is read. Thus, a virtual generated column
+ is similar to a view and a stored generated column is similar to a
+ materialized view (except that it is always updated automatically).
+ PostgreSQL currently implements only stored generated columns.
+
+ To create a generated column, use the GENERATED ALWAYS
+ AS clause in CREATE TABLE, for example:
+
+ The keyword STORED must be specified to choose the
+ stored kind of generated column. See CREATE TABLE for
+ more details.
+
+ A generated column cannot be written to directly. In
+ INSERT or UPDATE commands, a value
+ cannot be specified for a generated column, but the keyword
+ DEFAULT may be specified.
+
+ Consider the differences between a column with a default and a generated
+ column. The column default is evaluated once when the row is first
+ inserted if no other value was provided; a generated column is updated
+ whenever the row changes and cannot be overridden. A column default may
+ not refer to other columns of the table; a generation expression would
+ normally do so. A column default can use volatile functions, for example
+ random() or functions referring to the current time;
+ this is not allowed for generated columns.
+
+ Several restrictions apply to the definition of generated columns and
+ tables involving generated columns:
+
+
+ The generation expression can only use immutable functions and cannot
+ use subqueries or reference anything other than the current row in any
+ way.
+
+ A generation expression cannot reference another generated column.
+
+ A generation expression cannot reference a system column, except
+ tableoid.
+
+ A generated column cannot have a column default or an identity definition.
+
+ A generated column cannot be part of a partition key.
+
+ Foreign tables can have generated columns. See CREATE FOREIGN TABLE for details.
+
For inheritance and partitioning:
+ If a parent column is a generated column, its child column must also
+ be a generated column; however, the child column can have a
+ different generation expression. The generation expression that is
+ actually applied during insert or update of a row is the one
+ associated with the table that the row is physically in.
+ (This is unlike the behavior for column defaults: for those, the
+ default value associated with the table named in the query applies.)
+
+ If a parent column is not a generated column, its child column must
+ not be generated either.
+
+ For inherited tables, if you write a child column definition without
+ any GENERATED clause in CREATE TABLE
+ ... INHERITS, then its GENERATED clause
+ will automatically be copied from the parent. ALTER TABLE
+ ... INHERIT will insist that parent and child columns
+ already match as to generation status, but it will not require their
+ generation expressions to match.
+
+ Similarly for partitioned tables, if you write a child column
+ definition without any GENERATED clause
+ in CREATE TABLE ... PARTITION OF, then
+ its GENERATED clause will automatically be copied
+ from the parent. ALTER TABLE ... ATTACH PARTITION
+ will insist that parent and child columns already match as to
+ generation status, but it will not require their generation
+ expressions to match.
+
+ In case of multiple inheritance, if one parent column is a generated
+ column, then all parent columns must be generated columns. If they
+ do not all have the same generation expression, then the desired
+ expression for the child must be specified explicitly.
+
+
+ Additional considerations apply to the use of generated columns.
+
+ Generated columns maintain access privileges separately from their
+ underlying base columns. So, it is possible to arrange it so that a
+ particular role can read from a generated column but not from the
+ underlying base columns.
+
+ Generated columns are, conceptually, updated after
+ BEFORE triggers have run. Therefore, changes made to
+ base columns in a BEFORE trigger will be reflected in
+ generated columns. But conversely, it is not allowed to access
+ generated columns in BEFORE triggers.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-inherit.html b/pgsql/doc/postgresql/html/ddl-inherit.html
new file mode 100644
index 0000000000000000000000000000000000000000..9581888010c9adeeff65d1681f541dfd821f82fc
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-inherit.html
@@ -0,0 +1,289 @@
+
+5.10. Inheritance
+ PostgreSQL implements table inheritance,
+ which can be a useful tool for database designers. (SQL:1999 and
+ later define a type inheritance feature, which differs in many
+ respects from the features described here.)
+
+ Let's start with an example: suppose we are trying to build a data
+ model for cities. Each state has many cities, but only one
+ capital. We want to be able to quickly retrieve the capital city
+ for any particular state. This can be done by creating two tables,
+ one for state capitals and one for cities that are not
+ capitals. However, what happens when we want to ask for data about
+ a city, regardless of whether it is a capital or not? The
+ inheritance feature can help to resolve this problem. We define the
+ capitals table so that it inherits from
+ cities:
+
+
+CREATE TABLE cities (
+ name text,
+ population float,
+ elevation int -- in feet
+);
+
+CREATE TABLE capitals (
+ state char(2)
+) INHERITS (cities);
+
+
+ In this case, the capitals table inherits
+ all the columns of its parent table, cities. State
+ capitals also have an extra column, state, that shows
+ their state.
+
+ In PostgreSQL, a table can inherit from
+ zero or more other tables, and a query can reference either all
+ rows of a table or all rows of a table plus all of its descendant tables.
+ The latter behavior is the default.
+ For example, the following query finds the names of all cities,
+ including state capitals, that are located at an elevation over
+ 500 feet:
+
+
+SELECT name, elevation
+ FROM cities
+ WHERE elevation > 500;
+
+
+ Given the sample data from the PostgreSQL
+ tutorial (see Section 2.1), this returns:
+
+
+ name | elevation
+-----------+-----------
+ Las Vegas | 2174
+ Mariposa | 1953
+ Madison | 845
+
+
+ On the other hand, the following query finds all the cities that
+ are not state capitals and are situated at an elevation over 500 feet:
+
+
+SELECT name, elevation
+ FROM ONLY cities
+ WHERE elevation > 500;
+
+ name | elevation
+-----------+-----------
+ Las Vegas | 2174
+ Mariposa | 1953
+
+
+ Here the ONLY keyword indicates that the query
+ should apply only to cities, and not any tables
+ below cities in the inheritance hierarchy. Many
+ of the commands that we have already discussed —
+ SELECT, UPDATE and
+ DELETE — support the
+ ONLY keyword.
+
+ You can also write the table name with a trailing *
+ to explicitly specify that descendant tables are included:
+
+
+SELECT name, elevation
+ FROM cities*
+ WHERE elevation > 500;
+
+
+ Writing * is not necessary, since this behavior is always
+ the default. However, this syntax is still supported for
+ compatibility with older releases where the default could be changed.
+
+ In some cases you might wish to know which table a particular row
+ originated from. There is a system column called
+ tableoid in each table which can tell you the
+ originating table:
+
+
+ tableoid | name | elevation
+----------+-----------+-----------
+ 139793 | Las Vegas | 2174
+ 139793 | Mariposa | 1953
+ 139798 | Madison | 845
+
+
+ (If you try to reproduce this example, you will probably get
+ different numeric OIDs.) By doing a join with
+ pg_class you can see the actual table names:
+
+
+SELECT p.relname, c.name, c.elevation
+FROM cities c, pg_class p
+WHERE c.elevation > 500 AND c.tableoid = p.oid;
+
+
+ which returns:
+
+
+ relname | name | elevation
+----------+-----------+-----------
+ cities | Las Vegas | 2174
+ cities | Mariposa | 1953
+ capitals | Madison | 845
+
+
+ Another way to get the same effect is to use the regclass
+ alias type, which will print the table OID symbolically:
+
+
+ Inheritance does not automatically propagate data from
+ INSERT or COPY commands to
+ other tables in the inheritance hierarchy. In our example, the
+ following INSERT statement will fail:
+
+ We might hope that the data would somehow be routed to the
+ capitals table, but this does not happen:
+ INSERT always inserts into exactly the table
+ specified. In some cases it is possible to redirect the insertion
+ using a rule (see Chapter 41). However that does not
+ help for the above case because the cities table
+ does not contain the column state, and so the
+ command will be rejected before the rule can be applied.
+
+ All check constraints and not-null constraints on a parent table are
+ automatically inherited by its children, unless explicitly specified
+ otherwise with NO INHERIT clauses. Other types of constraints
+ (unique, primary key, and foreign key constraints) are not inherited.
+
+ A table can inherit from more than one parent table, in which case it has
+ the union of the columns defined by the parent tables. Any columns
+ declared in the child table's definition are added to these. If the
+ same column name appears in multiple parent tables, or in both a parent
+ table and the child's definition, then these columns are “merged”
+ so that there is only one such column in the child table. To be merged,
+ columns must have the same data types, else an error is raised.
+ Inheritable check constraints and not-null constraints are merged in a
+ similar fashion. Thus, for example, a merged column will be marked
+ not-null if any one of the column definitions it came from is marked
+ not-null. Check constraints are merged if they have the same name,
+ and the merge will fail if their conditions are different.
+
+ Table inheritance is typically established when the child table is
+ created, using the INHERITS clause of the
+ CREATE TABLE
+ statement.
+ Alternatively, a table which is already defined in a compatible way can
+ have a new parent relationship added, using the INHERIT
+ variant of ALTER TABLE.
+ To do this the new child table must already include columns with
+ the same names and types as the columns of the parent. It must also include
+ check constraints with the same names and check expressions as those of the
+ parent. Similarly an inheritance link can be removed from a child using the
+ NO INHERIT variant of ALTER TABLE.
+ Dynamically adding and removing inheritance links like this can be useful
+ when the inheritance relationship is being used for table
+ partitioning (see Section 5.11).
+
+ One convenient way to create a compatible table that will later be made
+ a new child is to use the LIKE clause in CREATE
+ TABLE. This creates a new table with the same columns as
+ the source table. If there are any CHECK
+ constraints defined on the source table, the INCLUDING
+ CONSTRAINTS option to LIKE should be
+ specified, as the new child must have constraints matching the parent
+ to be considered compatible.
+
+ A parent table cannot be dropped while any of its children remain. Neither
+ can columns or check constraints of child tables be dropped or altered
+ if they are inherited
+ from any parent tables. If you wish to remove a table and all of its
+ descendants, one easy way is to drop the parent table with the
+ CASCADE option (see Section 5.14).
+
+ ALTER TABLE will
+ propagate any changes in column data definitions and check
+ constraints down the inheritance hierarchy. Again, dropping
+ columns that are depended on by other tables is only possible when using
+ the CASCADE option. ALTER
+ TABLE follows the same rules for duplicate column merging
+ and rejection that apply during CREATE TABLE.
+
+ Inherited queries perform access permission checks on the parent table
+ only. Thus, for example, granting UPDATE permission on
+ the cities table implies permission to update rows in
+ the capitals table as well, when they are
+ accessed through cities. This preserves the appearance
+ that the data is (also) in the parent table. But
+ the capitals table could not be updated directly
+ without an additional grant. In a similar way, the parent table's row
+ security policies (see Section 5.8) are applied to
+ rows coming from child tables during an inherited query. A child table's
+ policies, if any, are applied only when it is the table explicitly named
+ in the query; and in that case, any policies attached to its parent(s) are
+ ignored.
+
+ Foreign tables (see Section 5.12) can also
+ be part of inheritance hierarchies, either as parent or child
+ tables, just as regular tables can be. If a foreign table is part
+ of an inheritance hierarchy then any operations not supported by
+ the foreign table are not supported on the whole hierarchy either.
+
+ Note that not all SQL commands are able to work on
+ inheritance hierarchies. Commands that are used for data querying,
+ data modification, or schema modification
+ (e.g., SELECT, UPDATE, DELETE,
+ most variants of ALTER TABLE, but
+ not INSERT or ALTER TABLE ...
+ RENAME) typically default to including child tables and
+ support the ONLY notation to exclude them.
+ Commands that do database maintenance and tuning
+ (e.g., REINDEX, VACUUM)
+ typically only work on individual, physical tables and do not
+ support recursing over inheritance hierarchies. The respective
+ behavior of each individual command is documented in its reference
+ page (SQL Commands).
+
+ A serious limitation of the inheritance feature is that indexes (including
+ unique constraints) and foreign key constraints only apply to single
+ tables, not to their inheritance children. This is true on both the
+ referencing and referenced sides of a foreign key constraint. Thus,
+ in the terms of the above example:
+
+
+ If we declared cities.name to be
+ UNIQUE or a PRIMARY KEY, this would not stop the
+ capitals table from having rows with names duplicating
+ rows in cities. And those duplicate rows would by
+ default show up in queries from cities. In fact, by
+ default capitals would have no unique constraint at all,
+ and so could contain multiple rows with the same name.
+ You could add a unique constraint to capitals, but this
+ would not prevent duplication compared to cities.
+
+ Similarly, if we were to specify that
+ cities.nameREFERENCES some
+ other table, this constraint would not automatically propagate to
+ capitals. In this case you could work around it by
+ manually adding the same REFERENCES constraint to
+ capitals.
+
+ Specifying that another table's column REFERENCES
+ cities(name) would allow the other table to contain city names, but
+ not capital names. There is no good workaround for this case.
+
+
+ Some functionality not implemented for inheritance hierarchies is
+ implemented for declarative partitioning.
+ Considerable care is needed in deciding whether partitioning with legacy
+ inheritance is useful for your application.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-others.html b/pgsql/doc/postgresql/html/ddl-others.html
new file mode 100644
index 0000000000000000000000000000000000000000..fe6d88824f6f552d68626a35abc7af1b3e5bf6b1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-others.html
@@ -0,0 +1,20 @@
+
+5.13. Other Database Objects
+ Tables are the central objects in a relational database structure,
+ because they hold your data. But they are not the only objects
+ that exist in a database. Many other kinds of objects can be
+ created to make the use and management of the data more efficient
+ or convenient. They are not discussed in this chapter, but we give
+ you a list here so that you are aware of what is possible:
+
+ Views
+
+ Functions, procedures, and operators
+
+ Data types and domains
+
+ Triggers and rewrite rules
+
+ Detailed information on
+ these topics appears in Part V.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-partitioning.html b/pgsql/doc/postgresql/html/ddl-partitioning.html
new file mode 100644
index 0000000000000000000000000000000000000000..36d7a744dee6e78eb46bd1d96628da223a518495
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-partitioning.html
@@ -0,0 +1,994 @@
+
+5.11. Table Partitioning
+ Partitioning refers to splitting what is logically one large table into
+ smaller physical pieces. Partitioning can provide several benefits:
+
+ Query performance can be improved dramatically in certain situations,
+ particularly when most of the heavily accessed rows of the table are in a
+ single partition or a small number of partitions. Partitioning
+ effectively substitutes for the upper tree levels of indexes,
+ making it more likely that the heavily-used parts of the indexes
+ fit in memory.
+
+ When queries or updates access a large percentage of a single
+ partition, performance can be improved by using a
+ sequential scan of that partition instead of using an
+ index, which would require random-access reads scattered across the
+ whole table.
+
+ Bulk loads and deletes can be accomplished by adding or removing
+ partitions, if the usage pattern is accounted for in the
+ partitioning design. Dropping an individual partition
+ using DROP TABLE, or doing ALTER TABLE
+ DETACH PARTITION, is far faster than a bulk
+ operation. These commands also entirely avoid the
+ VACUUM overhead caused by a bulk DELETE.
+
+ Seldom-used data can be migrated to cheaper and slower storage media.
+
+
+ These benefits will normally be worthwhile only when a table would
+ otherwise be very large. The exact point at which a table will
+ benefit from partitioning depends on the application, although a
+ rule of thumb is that the size of the table should exceed the physical
+ memory of the database server.
+
+ PostgreSQL offers built-in support for the
+ following forms of partitioning:
+
+
+ The table is partitioned into “ranges” defined
+ by a key column or set of columns, with no overlap between
+ the ranges of values assigned to different partitions. For
+ example, one might partition by date ranges, or by ranges of
+ identifiers for particular business objects.
+ Each range's bounds are understood as being inclusive at the
+ lower end and exclusive at the upper end. For example, if one
+ partition's range is from 1
+ to 10, and the next one's range is
+ from 10 to 20, then
+ value 10 belongs to the second partition not
+ the first.
+
+ The table is partitioned by specifying a modulus and a remainder for
+ each partition. Each partition will hold the rows for which the hash
+ value of the partition key divided by the specified modulus will
+ produce the specified remainder.
+
+
+ If your application needs to use other forms of partitioning not listed
+ above, alternative methods such as inheritance and
+ UNION ALL views can be used instead. Such methods
+ offer flexibility but do not have some of the performance benefits
+ of built-in declarative partitioning.
+
+ PostgreSQL allows you to declare
+ that a table is divided into partitions. The table that is divided
+ is referred to as a partitioned table. The
+ declaration includes the partitioning method
+ as described above, plus a list of columns or expressions to be used
+ as the partition key.
+
+ The partitioned table itself is a “virtual” table having
+ no storage of its own. Instead, the storage belongs
+ to partitions, which are otherwise-ordinary
+ tables associated with the partitioned table.
+ Each partition stores a subset of the data as defined by its
+ partition bounds.
+ All rows inserted into a partitioned table will be routed to the
+ appropriate one of the partitions based on the values of the partition
+ key column(s).
+ Updating the partition key of a row will cause it to be moved into a
+ different partition if it no longer satisfies the partition bounds
+ of its original partition.
+
+ Partitions may themselves be defined as partitioned tables, resulting
+ in sub-partitioning. Although all partitions
+ must have the same columns as their partitioned parent, partitions may
+ have their
+ own indexes, constraints and default values, distinct from those of other
+ partitions. See CREATE TABLE for more details on
+ creating partitioned tables and partitions.
+
+ It is not possible to turn a regular table into a partitioned table or
+ vice versa. However, it is possible to add an existing regular or
+ partitioned table as a partition of a partitioned table, or remove a
+ partition from a partitioned table turning it into a standalone table;
+ this can simplify and speed up many maintenance processes.
+ See ALTER TABLE to learn more about the
+ ATTACH PARTITION and DETACH PARTITION
+ sub-commands.
+
+ Partitions can also be foreign
+ tables, although considerable care is needed because it is then
+ the user's responsibility that the contents of the foreign table
+ satisfy the partitioning rule. There are some other restrictions as
+ well. See CREATE FOREIGN TABLE for more
+ information.
+
+ Suppose we are constructing a database for a large ice cream company.
+ The company measures peak temperatures every day as well as ice cream
+ sales in each region. Conceptually, we want a table like:
+
+
+CREATE TABLE measurement (
+ city_id int not null,
+ logdate date not null,
+ peaktemp int,
+ unitsales int
+);
+
+
+ We know that most queries will access just the last week's, month's or
+ quarter's data, since the main use of this table will be to prepare
+ online reports for management. To reduce the amount of old data that
+ needs to be stored, we decide to keep only the most recent 3 years
+ worth of data. At the beginning of each month we will remove the oldest
+ month's data. In this situation we can use partitioning to help us meet
+ all of our different requirements for the measurements table.
+
+ To use declarative partitioning in this case, use the following steps:
+
+
+ Create the measurement table as a partitioned
+ table by specifying the PARTITION BY clause, which
+ includes the partitioning method (RANGE in this
+ case) and the list of column(s) to use as the partition key.
+
+
+CREATE TABLE measurement (
+ city_id int not null,
+ logdate date not null,
+ peaktemp int,
+ unitsales int
+) PARTITION BY RANGE (logdate);
+
+
+ Create partitions. Each partition's definition must specify bounds
+ that correspond to the partitioning method and partition key of the
+ parent. Note that specifying bounds such that the new partition's
+ values would overlap with those in one or more existing partitions will
+ cause an error.
+
+ Partitions thus created are in every way normal
+ PostgreSQL
+ tables (or, possibly, foreign tables). It is possible to specify a
+ tablespace and storage parameters for each partition separately.
+
+ For our example, each partition should hold one month's worth of
+ data, to match the requirement of deleting one month's data at a
+ time. So the commands might look like:
+
+
+CREATE TABLE measurement_y2006m02 PARTITION OF measurement
+ FOR VALUES FROM ('2006-02-01') TO ('2006-03-01');
+
+CREATE TABLE measurement_y2006m03 PARTITION OF measurement
+ FOR VALUES FROM ('2006-03-01') TO ('2006-04-01');
+
+...
+CREATE TABLE measurement_y2007m11 PARTITION OF measurement
+ FOR VALUES FROM ('2007-11-01') TO ('2007-12-01');
+
+CREATE TABLE measurement_y2007m12 PARTITION OF measurement
+ FOR VALUES FROM ('2007-12-01') TO ('2008-01-01')
+ TABLESPACE fasttablespace;
+
+CREATE TABLE measurement_y2008m01 PARTITION OF measurement
+ FOR VALUES FROM ('2008-01-01') TO ('2008-02-01')
+ WITH (parallel_workers = 4)
+ TABLESPACE fasttablespace;
+
+
+ (Recall that adjacent partitions can share a bound value, since
+ range upper bounds are treated as exclusive bounds.)
+
+ If you wish to implement sub-partitioning, again specify the
+ PARTITION BY clause in the commands used to create
+ individual partitions, for example:
+
+
+CREATE TABLE measurement_y2006m02 PARTITION OF measurement
+ FOR VALUES FROM ('2006-02-01') TO ('2006-03-01')
+ PARTITION BY RANGE (peaktemp);
+
+
+ After creating partitions of measurement_y2006m02,
+ any data inserted into measurement that is mapped to
+ measurement_y2006m02 (or data that is
+ directly inserted into measurement_y2006m02,
+ which is allowed provided its partition constraint is satisfied)
+ will be further redirected to one of its
+ partitions based on the peaktemp column. The partition
+ key specified may overlap with the parent's partition key, although
+ care should be taken when specifying the bounds of a sub-partition
+ such that the set of data it accepts constitutes a subset of what
+ the partition's own bounds allow; the system does not try to check
+ whether that's really the case.
+
+ Inserting data into the parent table that does not map
+ to one of the existing partitions will cause an error; an appropriate
+ partition must be added manually.
+
+ It is not necessary to manually create table constraints describing
+ the partition boundary conditions for partitions. Such constraints
+ will be created automatically.
+
+ Create an index on the key column(s), as well as any other indexes you
+ might want, on the partitioned table. (The key index is not strictly
+ necessary, but in most scenarios it is helpful.)
+ This automatically creates a matching index on each partition, and
+ any partitions you create or attach later will also have such an
+ index.
+ An index or unique constraint declared on a partitioned table
+ is “virtual” in the same way that the partitioned table
+ is: the actual data is in child indexes on the individual partition
+ tables.
+
+
+CREATE INDEX ON measurement (logdate);
+
+
+ Ensure that the enable_partition_pruning
+ configuration parameter is not disabled in postgresql.conf.
+ If it is, queries will not be optimized as desired.
+
+
+ In the above example we would be creating a new partition each month, so
+ it might be wise to write a script that generates the required DDL
+ automatically.
+
+ Normally the set of partitions established when initially defining the
+ table is not intended to remain static. It is common to want to
+ remove partitions holding old data and periodically add new partitions for
+ new data. One of the most important advantages of partitioning is
+ precisely that it allows this otherwise painful task to be executed
+ nearly instantaneously by manipulating the partition structure, rather
+ than physically moving large amounts of data around.
+
+ The simplest option for removing old data is to drop the partition that
+ is no longer necessary:
+
+DROP TABLE measurement_y2006m02;
+
+ This can very quickly delete millions of records because it doesn't have
+ to individually delete every record. Note however that the above command
+ requires taking an ACCESS EXCLUSIVE lock on the parent
+ table.
+
+ Another option that is often preferable is to remove the partition from
+ the partitioned table but retain access to it as a table in its own
+ right. This has two forms:
+
+
+
+ These allow further operations to be performed on the data before
+ it is dropped. For example, this is often a useful time to back up
+ the data using COPY, pg_dump, or
+ similar tools. It might also be a useful time to aggregate data
+ into smaller formats, perform other data manipulations, or run
+ reports. The first form of the command requires an
+ ACCESS EXCLUSIVE lock on the parent table.
+ Adding the CONCURRENTLY qualifier as in the second
+ form allows the detach operation to require only
+ SHARE UPDATE EXCLUSIVE lock on the parent table, but see
+ ALTER TABLE ... DETACH PARTITION
+ for details on the restrictions.
+
+ Similarly we can add a new partition to handle new data. We can create an
+ empty partition in the partitioned table just as the original partitions
+ were created above:
+
+
+CREATE TABLE measurement_y2008m02 PARTITION OF measurement
+ FOR VALUES FROM ('2008-02-01') TO ('2008-03-01')
+ TABLESPACE fasttablespace;
+
+
+ As an alternative, it is sometimes more convenient to create the
+ new table outside the partition structure, and attach it as a
+ partition later. This allows new data to be loaded, checked, and
+ transformed prior to it appearing in the partitioned table.
+ Moreover, the ATTACH PARTITION operation requires
+ only SHARE UPDATE EXCLUSIVE lock on the
+ partitioned table, as opposed to the ACCESS
+ EXCLUSIVE lock that is required by CREATE TABLE
+ ... PARTITION OF, so it is more friendly to concurrent
+ operations on the partitioned table.
+ The CREATE TABLE ... LIKE option is helpful
+ to avoid tediously repeating the parent table's definition:
+
+
+CREATE TABLE measurement_y2008m02
+ (LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS)
+ TABLESPACE fasttablespace;
+
+ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
+ CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' );
+
+\copy measurement_y2008m02 from 'measurement_y2008m02'
+-- possibly some other data preparation work
+
+ALTER TABLE measurement ATTACH PARTITION measurement_y2008m02
+ FOR VALUES FROM ('2008-02-01') TO ('2008-03-01' );
+
+
+ Before running the ATTACH PARTITION command, it is
+ recommended to create a CHECK constraint on the table to
+ be attached that matches the expected partition constraint, as
+ illustrated above. That way, the system will be able to skip the scan
+ which is otherwise needed to validate the implicit
+ partition constraint. Without the CHECK constraint,
+ the table will be scanned to validate the partition constraint while
+ holding an ACCESS EXCLUSIVE lock on that partition.
+ It is recommended to drop the now-redundant CHECK
+ constraint after the ATTACH PARTITION is complete. If
+ the table being attached is itself a partitioned table, then each of its
+ sub-partitions will be recursively locked and scanned until either a
+ suitable CHECK constraint is encountered or the leaf
+ partitions are reached.
+
+ Similarly, if the partitioned table has a DEFAULT
+ partition, it is recommended to create a CHECK
+ constraint which excludes the to-be-attached partition's constraint. If
+ this is not done then the DEFAULT partition will be
+ scanned to verify that it contains no records which should be located in
+ the partition being attached. This operation will be performed whilst
+ holding an ACCESS EXCLUSIVE lock on the
+ DEFAULT partition. If the DEFAULT partition
+ is itself a partitioned table, then each of its partitions will be
+ recursively checked in the same way as the table being attached, as
+ mentioned above.
+
+ As explained above, it is possible to create indexes on partitioned tables
+ so that they are applied automatically to the entire hierarchy.
+ This is very
+ convenient, as not only will the existing partitions become indexed, but
+ also any partitions that are created in the future will. One limitation is
+ that it's not possible to use the CONCURRENTLY
+ qualifier when creating such a partitioned index. To avoid long lock
+ times, it is possible to use CREATE INDEX ON ONLY
+ the partitioned table; such an index is marked invalid, and the partitions
+ do not get the index applied automatically. The indexes on partitions can
+ be created individually using CONCURRENTLY, and then
+ attached to the index on the parent using
+ ALTER INDEX .. ATTACH PARTITION. Once indexes for all
+ partitions are attached to the parent index, the parent index is marked
+ valid automatically. Example:
+
+CREATE INDEX measurement_usls_idx ON ONLY measurement (unitsales);
+
+CREATE INDEX CONCURRENTLY measurement_usls_200602_idx
+ ON measurement_y2006m02 (unitsales);
+ALTER INDEX measurement_usls_idx
+ ATTACH PARTITION measurement_usls_200602_idx;
+...
+
+
+ This technique can be used with UNIQUE and
+ PRIMARY KEY constraints too; the indexes are created
+ implicitly when the constraint is created. Example:
+
+ The following limitations apply to partitioned tables:
+
+ To create a unique or primary key constraint on a partitioned table,
+ the partition keys must not include any expressions or function calls
+ and the constraint's columns must include all of the partition key
+ columns. This limitation exists because the individual indexes making
+ up the constraint can only directly enforce uniqueness within their own
+ partitions; therefore, the partition structure itself must guarantee
+ that there are not duplicates in different partitions.
+
+ There is no way to create an exclusion constraint spanning the
+ whole partitioned table. It is only possible to put such a
+ constraint on each leaf partition individually. Again, this
+ limitation stems from not being able to enforce cross-partition
+ restrictions.
+
+ BEFORE ROW triggers on INSERT
+ cannot change which partition is the final destination for a new row.
+
+ Mixing temporary and permanent relations in the same partition tree is
+ not allowed. Hence, if the partitioned table is permanent, so must be
+ its partitions and likewise if the partitioned table is temporary. When
+ using temporary relations, all members of the partition tree have to be
+ from the same session.
+
+
+ Individual partitions are linked to their partitioned table using
+ inheritance behind-the-scenes. However, it is not possible to use
+ all of the generic features of inheritance with declaratively
+ partitioned tables or their partitions, as discussed below. Notably,
+ a partition cannot have any parents other than the partitioned table
+ it is a partition of, nor can a table inherit from both a partitioned
+ table and a regular table. That means partitioned tables and their
+ partitions never share an inheritance hierarchy with regular tables.
+
+ Since a partition hierarchy consisting of the partitioned table and its
+ partitions is still an inheritance hierarchy,
+ tableoid and all the normal rules of
+ inheritance apply as described in Section 5.10, with
+ a few exceptions:
+
+
+ Partitions cannot have columns that are not present in the parent. It
+ is not possible to specify columns when creating partitions with
+ CREATE TABLE, nor is it possible to add columns to
+ partitions after-the-fact using ALTER TABLE.
+ Tables may be added as a partition with ALTER TABLE
+ ... ATTACH PARTITION only if their columns exactly match
+ the parent.
+
+ Both CHECK and NOT NULL
+ constraints of a partitioned table are always inherited by all its
+ partitions. CHECK constraints that are marked
+ NO INHERIT are not allowed to be created on
+ partitioned tables.
+ You cannot drop a NOT NULL constraint on a
+ partition's column if the same constraint is present in the parent
+ table.
+
+ Using ONLY to add or drop a constraint on only
+ the partitioned table is supported as long as there are no
+ partitions. Once partitions exist, using ONLY
+ will result in an error for any constraints other than
+ UNIQUE and PRIMARY KEY.
+ Instead, constraints on the partitions
+ themselves can be added and (if they are not present in the parent
+ table) dropped.
+
+ As a partitioned table does not have any data itself, attempts to use
+ TRUNCATEONLY on a partitioned
+ table will always return an error.
+
+ While the built-in declarative partitioning is suitable for most
+ common use cases, there are some circumstances where a more flexible
+ approach may be useful. Partitioning can be implemented using table
+ inheritance, which allows for several features not supported
+ by declarative partitioning, such as:
+
+
+ For declarative partitioning, partitions must have exactly the same set
+ of columns as the partitioned table, whereas with table inheritance,
+ child tables may have extra columns not present in the parent.
+
+ Table inheritance allows for multiple inheritance.
+
+ Declarative partitioning only supports range, list and hash
+ partitioning, whereas table inheritance allows data to be divided in a
+ manner of the user's choosing. (Note, however, that if constraint
+ exclusion is unable to prune child tables effectively, query performance
+ might be poor.)
+
+ This example builds a partitioning structure equivalent to the
+ declarative partitioning example above. Use
+ the following steps:
+
+
+ Create the “root” table, from which all of the
+ “child” tables will inherit. This table will contain no data. Do not
+ define any check constraints on this table, unless you intend them
+ to be applied equally to all child tables. There is no point in
+ defining any indexes or unique constraints on it, either. For our
+ example, the root table is the measurement
+ table as originally defined:
+
+
+CREATE TABLE measurement (
+ city_id int not null,
+ logdate date not null,
+ peaktemp int,
+ unitsales int
+);
+
+
+ Create several “child” tables that each inherit from
+ the root table. Normally, these tables will not add any columns
+ to the set inherited from the root. Just as with declarative
+ partitioning, these tables are in every way normal
+ PostgreSQL tables (or foreign tables).
+
+ Add non-overlapping table constraints to the child tables to
+ define the allowed key values in each.
+
+ Typical examples would be:
+
+CHECK ( x = 1 )
+CHECK ( county IN ( 'Oxfordshire', 'Buckinghamshire', 'Warwickshire' ))
+CHECK ( outletID >= 100 AND outletID < 200 )
+
+ Ensure that the constraints guarantee that there is no overlap
+ between the key values permitted in different child tables. A common
+ mistake is to set up range constraints like:
+
+CHECK ( outletID BETWEEN 100 AND 200 )
+CHECK ( outletID BETWEEN 200 AND 300 )
+
+ This is wrong since it is not clear which child table the key
+ value 200 belongs in.
+ Instead, ranges should be defined in this style:
+
+
+CREATE TABLE measurement_y2006m02 (
+ CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
+) INHERITS (measurement);
+
+CREATE TABLE measurement_y2006m03 (
+ CHECK ( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' )
+) INHERITS (measurement);
+
+...
+CREATE TABLE measurement_y2007m11 (
+ CHECK ( logdate >= DATE '2007-11-01' AND logdate < DATE '2007-12-01' )
+) INHERITS (measurement);
+
+CREATE TABLE measurement_y2007m12 (
+ CHECK ( logdate >= DATE '2007-12-01' AND logdate < DATE '2008-01-01' )
+) INHERITS (measurement);
+
+CREATE TABLE measurement_y2008m01 (
+ CHECK ( logdate >= DATE '2008-01-01' AND logdate < DATE '2008-02-01' )
+) INHERITS (measurement);
+
+
+ For each child table, create an index on the key column(s),
+ as well as any other indexes you might want.
+
+CREATE INDEX measurement_y2006m02_logdate ON measurement_y2006m02 (logdate);
+CREATE INDEX measurement_y2006m03_logdate ON measurement_y2006m03 (logdate);
+CREATE INDEX measurement_y2007m11_logdate ON measurement_y2007m11 (logdate);
+CREATE INDEX measurement_y2007m12_logdate ON measurement_y2007m12 (logdate);
+CREATE INDEX measurement_y2008m01_logdate ON measurement_y2008m01 (logdate);
+
+
+ We want our application to be able to say INSERT INTO
+ measurement ... and have the data be redirected into the
+ appropriate child table. We can arrange that by attaching
+ a suitable trigger function to the root table.
+ If data will be added only to the latest child, we can
+ use a very simple trigger function:
+
+
+CREATE OR REPLACE FUNCTION measurement_insert_trigger()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO measurement_y2008m01 VALUES (NEW.*);
+ RETURN NULL;
+END;
+$$
+LANGUAGE plpgsql;
+
+
+ After creating the function, we create a trigger which
+ calls the trigger function:
+
+
+CREATE TRIGGER insert_measurement_trigger
+ BEFORE INSERT ON measurement
+ FOR EACH ROW EXECUTE FUNCTION measurement_insert_trigger();
+
+
+ We must redefine the trigger function each month so that it always
+ inserts into the current child table. The trigger definition does
+ not need to be updated, however.
+
+ We might want to insert data and have the server automatically
+ locate the child table into which the row should be added. We
+ could do this with a more complex trigger function, for example:
+
+
+CREATE OR REPLACE FUNCTION measurement_insert_trigger()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF ( NEW.logdate >= DATE '2006-02-01' AND
+ NEW.logdate < DATE '2006-03-01' ) THEN
+ INSERT INTO measurement_y2006m02 VALUES (NEW.*);
+ ELSIF ( NEW.logdate >= DATE '2006-03-01' AND
+ NEW.logdate < DATE '2006-04-01' ) THEN
+ INSERT INTO measurement_y2006m03 VALUES (NEW.*);
+ ...
+ ELSIF ( NEW.logdate >= DATE '2008-01-01' AND
+ NEW.logdate < DATE '2008-02-01' ) THEN
+ INSERT INTO measurement_y2008m01 VALUES (NEW.*);
+ ELSE
+ RAISE EXCEPTION 'Date out of range. Fix the measurement_insert_trigger() function!';
+ END IF;
+ RETURN NULL;
+END;
+$$
+LANGUAGE plpgsql;
+
+
+ The trigger definition is the same as before.
+ Note that each IF test must exactly match the
+ CHECK constraint for its child table.
+
+ While this function is more complex than the single-month case,
+ it doesn't need to be updated as often, since branches can be
+ added in advance of being needed.
+
Note
+ In practice, it might be best to check the newest child first,
+ if most inserts go into that child. For simplicity, we have
+ shown the trigger's tests in the same order as in other parts
+ of this example.
+
+ A different approach to redirecting inserts into the appropriate
+ child table is to set up rules, instead of a trigger, on the
+ root table. For example:
+
+
+CREATE RULE measurement_insert_y2006m02 AS
+ON INSERT TO measurement WHERE
+ ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
+DO INSTEAD
+ INSERT INTO measurement_y2006m02 VALUES (NEW.*);
+...
+CREATE RULE measurement_insert_y2008m01 AS
+ON INSERT TO measurement WHERE
+ ( logdate >= DATE '2008-01-01' AND logdate < DATE '2008-02-01' )
+DO INSTEAD
+ INSERT INTO measurement_y2008m01 VALUES (NEW.*);
+
+
+ A rule has significantly more overhead than a trigger, but the
+ overhead is paid once per query rather than once per row, so this
+ method might be advantageous for bulk-insert situations. In most
+ cases, however, the trigger method will offer better performance.
+
+ Be aware that COPY ignores rules. If you want to
+ use COPY to insert data, you'll need to copy into the
+ correct child table rather than directly into the root. COPY
+ does fire triggers, so you can use it normally if you use the trigger
+ approach.
+
+ Another disadvantage of the rule approach is that there is no simple
+ way to force an error if the set of rules doesn't cover the insertion
+ date; the data will silently go into the root table instead.
+
+ Ensure that the constraint_exclusion
+ configuration parameter is not disabled in
+ postgresql.conf; otherwise
+ child tables may be accessed unnecessarily.
+
+
+ As we can see, a complex table hierarchy could require a
+ substantial amount of DDL. In the above example we would be creating
+ a new child table each month, so it might be wise to write a script that
+ generates the required DDL automatically.
+
5.11.3.2. Maintenance for Inheritance Partitioning #
+ To remove old data quickly, simply drop the child table that is no longer
+ necessary:
+
+DROP TABLE measurement_y2006m02;
+
+
+ To remove the child table from the inheritance hierarchy table but retain access to
+ it as a table in its own right:
+
+
+ALTER TABLE measurement_y2006m02 NO INHERIT measurement;
+
+
+ To add a new child table to handle new data, create an empty child table
+ just as the original children were created above:
+
+
+CREATE TABLE measurement_y2008m02 (
+ CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' )
+) INHERITS (measurement);
+
+
+ Alternatively, one may want to create and populate the new child table
+ before adding it to the table hierarchy. This could allow data to be
+ loaded, checked, and transformed before being made visible to queries on
+ the parent table.
+
+
+CREATE TABLE measurement_y2008m02
+ (LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
+ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
+ CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE '2008-03-01' );
+\copy measurement_y2008m02 from 'measurement_y2008m02'
+-- possibly some other data preparation work
+ALTER TABLE measurement_y2008m02 INHERIT measurement;
+
+ The following caveats apply to partitioning implemented using
+ inheritance:
+
+ There is no automatic way to verify that all of the
+ CHECK constraints are mutually
+ exclusive. It is safer to create code that generates
+ child tables and creates and/or modifies associated objects than
+ to write each by hand.
+
+ Indexes and foreign key constraints apply to single tables and not
+ to their inheritance children, hence they have some
+ caveats to be aware of.
+
+ The schemes shown here assume that the values of a row's key column(s)
+ never change, or at least do not change enough to require it to move to another partition.
+ An UPDATE that attempts
+ to do that will fail because of the CHECK constraints.
+ If you need to handle such cases, you can put suitable update triggers
+ on the child tables, but it makes management of the structure
+ much more complicated.
+
+ If you are using manual VACUUM or
+ ANALYZE commands, don't forget that
+ you need to run them on each child table individually. A command like:
+
+ANALYZE measurement;
+
+ will only process the root table.
+
+ INSERT statements with ON CONFLICT
+ clauses are unlikely to work as expected, as the ON CONFLICT
+ action is only taken in case of unique violations on the specified
+ target relation, not its child relations.
+
+ Triggers or rules will be needed to route rows to the desired
+ child table, unless the application is explicitly aware of the
+ partitioning scheme. Triggers may be complicated to write, and will
+ be much slower than the tuple routing performed internally by
+ declarative partitioning.
+
+ Partition pruning is a query optimization technique
+ that improves performance for declaratively partitioned tables.
+ As an example:
+
+
+SET enable_partition_pruning = on; -- the default
+SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
+
+
+ Without partition pruning, the above query would scan each of the
+ partitions of the measurement table. With
+ partition pruning enabled, the planner will examine the definition
+ of each partition and prove that the partition need not
+ be scanned because it could not contain any rows meeting the query's
+ WHERE clause. When the planner can prove this, it
+ excludes (prunes) the partition from the query
+ plan.
+
+ By using the EXPLAIN command and the enable_partition_pruning configuration parameter, it's
+ possible to show the difference between a plan for which partitions have
+ been pruned and one for which they have not. A typical unoptimized
+ plan for this type of table setup is:
+
+
+ Some or all of the partitions might use index scans instead of
+ full-table sequential scans, but the point here is that there
+ is no need to scan the older partitions at all to answer this query.
+ When we enable partition pruning, we get a significantly
+ cheaper plan that will deliver the same answer:
+
+SET enable_partition_pruning = on;
+EXPLAIN SELECT count(*) FROM measurement WHERE logdate >= DATE '2008-01-01';
+ QUERY PLAN
+-----------------------------------------------------------------------------------
+ Aggregate (cost=37.75..37.76 rows=1 width=8)
+ -> Seq Scan on measurement_y2008m01 (cost=0.00..33.12 rows=617 width=0)
+ Filter: (logdate >= '2008-01-01'::date)
+
+
+ Note that partition pruning is driven only by the constraints defined
+ implicitly by the partition keys, not by the presence of indexes.
+ Therefore it isn't necessary to define indexes on the key columns.
+ Whether an index needs to be created for a given partition depends on
+ whether you expect that queries that scan the partition will
+ generally scan a large part of the partition or just a small part.
+ An index will be helpful in the latter case but not the former.
+
+ Partition pruning can be performed not only during the planning of a
+ given query, but also during its execution. This is useful as it can
+ allow more partitions to be pruned when clauses contain expressions
+ whose values are not known at query planning time, for example,
+ parameters defined in a PREPARE statement, using a
+ value obtained from a subquery, or using a parameterized value on the
+ inner side of a nested loop join. Partition pruning during execution
+ can be performed at any of the following times:
+
+
+ During initialization of the query plan. Partition pruning can be
+ performed here for parameter values which are known during the
+ initialization phase of execution. Partitions which are pruned
+ during this stage will not show up in the query's
+ EXPLAIN or EXPLAIN ANALYZE.
+ It is possible to determine the number of partitions which were
+ removed during this phase by observing the
+ “Subplans Removed” property in the
+ EXPLAIN output.
+
+ During actual execution of the query plan. Partition pruning may
+ also be performed here to remove partitions using values which are
+ only known during actual query execution. This includes values
+ from subqueries and values from execution-time parameters such as
+ those from parameterized nested loop joins. Since the value of
+ these parameters may change many times during the execution of the
+ query, partition pruning is performed whenever one of the
+ execution parameters being used by partition pruning changes.
+ Determining if partitions were pruned during this phase requires
+ careful inspection of the loops property in
+ the EXPLAIN ANALYZE output. Subplans
+ corresponding to different partitions may have different values
+ for it depending on how many times each of them was pruned during
+ execution. Some may be shown as (never executed)
+ if they were pruned every time.
+
+ Constraint exclusion is a query optimization
+ technique similar to partition pruning. While it is primarily used
+ for partitioning implemented using the legacy inheritance method, it can be
+ used for other purposes, including with declarative partitioning.
+
+ Constraint exclusion works in a very similar way to partition
+ pruning, except that it uses each table's CHECK
+ constraints — which gives it its name — whereas partition
+ pruning uses the table's partition bounds, which exist only in the
+ case of declarative partitioning. Another difference is that
+ constraint exclusion is only applied at plan time; there is no attempt
+ to remove partitions at execution time.
+
+ The fact that constraint exclusion uses CHECK
+ constraints, which makes it slow compared to partition pruning, can
+ sometimes be used as an advantage: because constraints can be defined
+ even on declaratively-partitioned tables, in addition to their internal
+ partition bounds, constraint exclusion may be able
+ to elide additional partitions from the query plan.
+
+ The default (and recommended) setting of
+ constraint_exclusion is neither
+ on nor off, but an intermediate setting
+ called partition, which causes the technique to be
+ applied only to queries that are likely to be working on inheritance partitioned
+ tables. The on setting causes the planner to examine
+ CHECK constraints in all queries, even simple ones that
+ are unlikely to benefit.
+
+ The following caveats apply to constraint exclusion:
+
+
+ Constraint exclusion is only applied during query planning, unlike
+ partition pruning, which can also be applied during query execution.
+
+ Constraint exclusion only works when the query's WHERE
+ clause contains constants (or externally supplied parameters).
+ For example, a comparison against a non-immutable function such as
+ CURRENT_TIMESTAMP cannot be optimized, since the
+ planner cannot know which child table the function's value might fall
+ into at run time.
+
+ Keep the partitioning constraints simple, else the planner may not be
+ able to prove that child tables might not need to be visited. Use simple
+ equality conditions for list partitioning, or simple
+ range tests for range partitioning, as illustrated in the preceding
+ examples. A good rule of thumb is that partitioning constraints should
+ contain only comparisons of the partitioning column(s) to constants
+ using B-tree-indexable operators, because only B-tree-indexable
+ column(s) are allowed in the partition key.
+
+ All constraints on all children of the parent table are examined
+ during constraint exclusion, so large numbers of children are likely
+ to increase query planning time considerably. So the legacy
+ inheritance based partitioning will work well with up to perhaps a
+ hundred child tables; don't try to use many thousands of children.
+
+
5.11.6. Best Practices for Declarative Partitioning #
+ The choice of how to partition a table should be made carefully, as the
+ performance of query planning and execution can be negatively affected by
+ poor design.
+
+ One of the most critical design decisions will be the column or columns
+ by which you partition your data. Often the best choice will be to
+ partition by the column or set of columns which most commonly appear in
+ WHERE clauses of queries being executed on the
+ partitioned table. WHERE clauses that are compatible
+ with the partition bound constraints can be used to prune unneeded
+ partitions. However, you may be forced into making other decisions by
+ requirements for the PRIMARY KEY or a
+ UNIQUE constraint. Removal of unwanted data is also a
+ factor to consider when planning your partitioning strategy. An entire
+ partition can be detached fairly quickly, so it may be beneficial to
+ design the partition strategy in such a way that all data to be removed
+ at once is located in a single partition.
+
+ Choosing the target number of partitions that the table should be divided
+ into is also a critical decision to make. Not having enough partitions
+ may mean that indexes remain too large and that data locality remains poor
+ which could result in low cache hit ratios. However, dividing the table
+ into too many partitions can also cause issues. Too many partitions can
+ mean longer query planning times and higher memory consumption during both
+ query planning and execution, as further described below.
+ When choosing how to partition your table,
+ it's also important to consider what changes may occur in the future. For
+ example, if you choose to have one partition per customer and you
+ currently have a small number of large customers, consider the
+ implications if in several years you instead find yourself with a large
+ number of small customers. In this case, it may be better to choose to
+ partition by HASH and choose a reasonable number of
+ partitions rather than trying to partition by LIST and
+ hoping that the number of customers does not increase beyond what it is
+ practical to partition the data by.
+
+ Sub-partitioning can be useful to further divide partitions that are
+ expected to become larger than other partitions.
+ Another option is to use range partitioning with multiple columns in
+ the partition key.
+ Either of these can easily lead to excessive numbers of partitions,
+ so restraint is advisable.
+
+ It is important to consider the overhead of partitioning during
+ query planning and execution. The query planner is generally able to
+ handle partition hierarchies with up to a few thousand partitions fairly
+ well, provided that typical queries allow the query planner to prune all
+ but a small number of partitions. Planning times become longer and memory
+ consumption becomes higher when more partitions remain after the planner
+ performs partition pruning. Another
+ reason to be concerned about having a large number of partitions is that
+ the server's memory consumption may grow significantly over
+ time, especially if many sessions touch large numbers of partitions.
+ That's because each partition requires its metadata to be loaded into the
+ local memory of each session that touches it.
+
+ With data warehouse type workloads, it can make sense to use a larger
+ number of partitions than with an OLTP type workload.
+ Generally, in data warehouses, query planning time is less of a concern as
+ the majority of processing time is spent during query execution. With
+ either of these two types of workload, it is important to make the right
+ decisions early, as re-partitioning large quantities of data can be
+ painfully slow. Simulations of the intended workload are often beneficial
+ for optimizing the partitioning strategy. Never just assume that more
+ partitions are better than fewer partitions, nor vice-versa.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-priv.html b/pgsql/doc/postgresql/html/ddl-priv.html
new file mode 100644
index 0000000000000000000000000000000000000000..13f846eddfe09060bca0c2ad2b76ca21329e2073
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-priv.html
@@ -0,0 +1,314 @@
+
+5.7. Privileges
+ When an object is created, it is assigned an owner. The
+ owner is normally the role that executed the creation statement.
+ For most kinds of objects, the initial state is that only the owner
+ (or a superuser) can do anything with the object. To allow
+ other roles to use it, privileges must be
+ granted.
+
+ There are different kinds of privileges: SELECT,
+ INSERT, UPDATE, DELETE,
+ TRUNCATE, REFERENCES, TRIGGER,
+ CREATE, CONNECT, TEMPORARY,
+ EXECUTE, USAGE, SET
+ and ALTER SYSTEM.
+ The privileges applicable to a particular
+ object vary depending on the object's type (table, function, etc.).
+ More detail about the meanings of these privileges appears below.
+ The following sections and chapters will also show you how
+ these privileges are used.
+
+ The right to modify or destroy an object is inherent in being the
+ object's owner, and cannot be granted or revoked in itself.
+ (However, like all privileges, that right can be inherited by
+ members of the owning role; see Section 22.3.)
+
+ An object can be assigned to a new owner with an ALTER
+ command of the appropriate kind for the object, for example
+
+ALTER TABLE table_name OWNER TO new_owner;
+
+ Superusers can always do this; ordinary roles can only do it if they are
+ both the current owner of the object (or inherit the privileges of the
+ owning role) and able to SET ROLE to the new owning role.
+
+ To assign privileges, the GRANT command is
+ used. For example, if joe is an existing role, and
+ accounts is an existing table, the privilege to
+ update the table can be granted with:
+
+GRANT UPDATE ON accounts TO joe;
+
+ Writing ALL in place of a specific privilege grants all
+ privileges that are relevant for the object type.
+
+ The special “role” name PUBLIC can
+ be used to grant a privilege to every role on the system. Also,
+ “group” roles can be set up to help manage privileges when
+ there are many users of a database — for details see
+ Chapter 22.
+
+ To revoke a previously-granted privilege, use the fittingly named
+ REVOKE command:
+
+REVOKE ALL ON accounts FROM PUBLIC;
+
+
+ Ordinarily, only the object's owner (or a superuser) can grant or
+ revoke privileges on an object. However, it is possible to grant a
+ privilege “with grant option”, which gives the recipient
+ the right to grant it in turn to others. If the grant option is
+ subsequently revoked then all who received the privilege from that
+ recipient (directly or through a chain of grants) will lose the
+ privilege. For details see the GRANT and
+ REVOKE reference pages.
+
+ An object's owner can choose to revoke their own ordinary privileges,
+ for example to make a table read-only for themselves as well as others.
+ But owners are always treated as holding all grant options, so they
+ can always re-grant their own privileges.
+
+ Allows SELECT from
+ any column, or specific column(s), of a table, view, materialized
+ view, or other table-like object.
+ Also allows use of COPY TO.
+ This privilege is also needed to reference existing column values in
+ UPDATE, DELETE,
+ or MERGE.
+ For sequences, this privilege also allows use of the
+ currval function.
+ For large objects, this privilege allows the object to be read.
+
+ Allows INSERT of a new row into a table, view,
+ etc. Can be granted on specific column(s), in which case
+ only those columns may be assigned to in the INSERT
+ command (other columns will therefore receive default values).
+ Also allows use of COPY FROM.
+
+ Allows UPDATE of any
+ column, or specific column(s), of a table, view, etc.
+ (In practice, any nontrivial UPDATE command will
+ require SELECT privilege as well, since it must
+ reference table columns to determine which rows to update, and/or to
+ compute new values for columns.)
+ SELECT ... FOR UPDATE
+ and SELECT ... FOR SHARE
+ also require this privilege on at least one column, in addition to the
+ SELECT privilege. For sequences, this
+ privilege allows use of the nextval and
+ setval functions.
+ For large objects, this privilege allows writing or truncating the
+ object.
+
+ Allows DELETE of a row from a table, view, etc.
+ (In practice, any nontrivial DELETE command will
+ require SELECT privilege as well, since it must
+ reference table columns to determine which rows to delete.)
+
+ For databases, allows new schemas and publications to be created within
+ the database, and allows trusted extensions to be installed within
+ the database.
+
+ For schemas, allows new objects to be created within the schema.
+ To rename an existing object, you must own the
+ object and have this privilege for the containing
+ schema.
+
+ For tablespaces, allows tables, indexes, and temporary files to be
+ created within the tablespace, and allows databases to be created that
+ have the tablespace as their default tablespace.
+
+ Note that revoking this privilege will not alter the existence or
+ location of existing objects.
+
+ Allows the grantee to connect to the database. This
+ privilege is checked at connection startup (in addition to checking
+ any restrictions imposed by pg_hba.conf).
+
+ Allows calling a function or procedure, including use of
+ any operators that are implemented on top of the function. This is the
+ only type of privilege that is applicable to functions and procedures.
+
+ For procedural languages, allows use of the language for
+ the creation of functions in that language. This is the only type
+ of privilege that is applicable to procedural languages.
+
+ For schemas, allows access to objects contained in the
+ schema (assuming that the objects' own privilege requirements are
+ also met). Essentially this allows the grantee to “look up”
+ objects within the schema. Without this permission, it is still
+ possible to see the object names, e.g., by querying system catalogs.
+ Also, after revoking this permission, existing sessions might have
+ statements that have previously performed this lookup, so this is not
+ a completely secure way to prevent object access.
+
+ For sequences, allows use of the
+ currval and nextval functions.
+
+ For types and domains, allows use of the type or domain in the
+ creation of tables, functions, and other schema objects. (Note that
+ this privilege does not control all “usage” of the
+ type, such as values of the type appearing in queries. It only
+ prevents objects from being created that depend on the type. The
+ main purpose of this privilege is controlling which users can create
+ dependencies on a type, which could prevent the owner from changing
+ the type later.)
+
+ For foreign-data wrappers, allows creation of new servers using the
+ foreign-data wrapper.
+
+ For foreign servers, allows creation of foreign tables using the
+ server. Grantees may also create, alter, or drop their own user
+ mappings associated with that server.
+
+ Allows a server configuration parameter to be set to a new value
+ within the current session. (While this privilege can be granted
+ on any parameter, it is meaningless except for parameters that would
+ normally require superuser privilege to set.)
+
+ Allows a server configuration parameter to be configured to a new
+ value using the ALTER SYSTEM command.
+
+
+ The privileges required by other commands are listed on the
+ reference page of the respective command.
+
+ PostgreSQL grants privileges on some types of objects to
+ PUBLIC by default when the objects are created.
+ No privileges are granted to PUBLIC by default on
+ tables,
+ table columns,
+ sequences,
+ foreign data wrappers,
+ foreign servers,
+ large objects,
+ schemas,
+ tablespaces,
+ or configuration parameters.
+ For other types of objects, the default privileges
+ granted to PUBLIC are as follows:
+ CONNECT and TEMPORARY (create
+ temporary tables) privileges for databases;
+ EXECUTE privilege for functions and procedures; and
+ USAGE privilege for languages and data types
+ (including domains).
+ The object owner can, of course, REVOKE
+ both default and expressly granted privileges. (For maximum
+ security, issue the REVOKE in the same transaction that
+ creates the object; then there is no window in which another user
+ can use the object.)
+ Also, these default privilege settings can be overridden using the
+ ALTER DEFAULT PRIVILEGES command.
+
+ Table 5.1 shows the one-letter
+ abbreviations that are used for these privilege types in
+ ACL (Access Control List) values.
+ You will see these letters in the output of the psql
+ commands listed below, or when looking at ACL columns of system catalogs.
+
+ DOMAIN,
+ FOREIGN DATA WRAPPER,
+ FOREIGN SERVER,
+ LANGUAGE,
+ SCHEMA,
+ SEQUENCE,
+ TYPE
+
SET
s
PARAMETER
ALTER SYSTEM
A
PARAMETER
+ Table 5.2 summarizes the privileges
+ available for each type of SQL object, using the abbreviations shown
+ above.
+ It also shows the psql command
+ that can be used to examine privilege settings for each object type.
+
Table 5.2. Summary of Access Privileges
Object Type
All Privileges
Default PUBLIC Privileges
psql Command
DATABASE
CTc
Tc
\l
DOMAIN
U
U
\dD+
FUNCTION or PROCEDURE
X
X
\df+
FOREIGN DATA WRAPPER
U
none
\dew+
FOREIGN SERVER
U
none
\des+
LANGUAGE
U
U
\dL+
LARGE OBJECT
rw
none
\dl+
PARAMETER
sA
none
\dconfig+
SCHEMA
UC
none
\dn+
SEQUENCE
rwU
none
\dp
TABLE (and table-like objects)
arwdDxt
none
\dp
Table column
arwx
none
\dp
TABLESPACE
C
none
\db+
TYPE
U
U
\dT+
+
+ The privileges that have been granted for a particular object are
+ displayed as a list of aclitem entries, each having the
+ format:
+
+grantee=privilege-abbreviation[*].../grantor
+
+ Each aclitem lists all the permissions of one grantee that
+ have been granted by a particular grantor. Specific privileges are
+ represented by one-letter abbreviations from
+ Table 5.1, with *
+ appended if the privilege was granted with grant option. For example,
+ calvin=r*w/hobbes specifies that the role
+ calvin has the privilege
+ SELECT (r) with grant option
+ (*) as well as the non-grantable
+ privilege UPDATE (w), both granted
+ by the role hobbes. If calvin
+ also has some privileges on the same object granted by a different
+ grantor, those would appear as a separate aclitem entry.
+ An empty grantee field in an aclitem stands
+ for PUBLIC.
+
+ As an example, suppose that user miriam creates
+ table mytable and does:
+
+GRANT SELECT ON mytable TO PUBLIC;
+GRANT SELECT, UPDATE, INSERT ON mytable TO admin;
+GRANT SELECT (col1), UPDATE (col1) ON mytable TO miriam_rw;
+
+ If the “Access privileges” column is empty for a given
+ object, it means the object has default privileges (that is, its
+ privileges entry in the relevant system catalog is null). Default
+ privileges always include all privileges for the owner, and can include
+ some privileges for PUBLIC depending on the object
+ type, as explained above. The first GRANT
+ or REVOKE on an object will instantiate the default
+ privileges (producing, for
+ example, miriam=arwdDxt/miriam) and then modify them
+ per the specified request. Similarly, entries are shown in “Column
+ privileges” only for columns with nondefault privileges.
+ (Note: for this purpose, “default privileges” always means
+ the built-in default privileges for the object's type. An object whose
+ privileges have been affected by an ALTER DEFAULT
+ PRIVILEGES command will always be shown with an explicit
+ privilege entry that includes the effects of
+ the ALTER.)
+
+ Notice that the owner's implicit grant options are not marked in the
+ access privileges display. A * will appear only when
+ grant options have been explicitly granted to someone.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-rowsecurity.html b/pgsql/doc/postgresql/html/ddl-rowsecurity.html
new file mode 100644
index 0000000000000000000000000000000000000000..4e2021cd15419a79003670f3771c42f2f9e8be00
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-rowsecurity.html
@@ -0,0 +1,382 @@
+
+5.8. Row Security Policies
+ In addition to the SQL-standard privilege
+ system available through GRANT,
+ tables can have row security policies that restrict,
+ on a per-user basis, which rows can be returned by normal queries
+ or inserted, updated, or deleted by data modification commands.
+ This feature is also known as Row-Level Security.
+ By default, tables do not have any policies, so that if a user has
+ access privileges to a table according to the SQL privilege system,
+ all rows within it are equally available for querying or updating.
+
+ When row security is enabled on a table (with
+ ALTER TABLE ... ENABLE ROW LEVEL
+ SECURITY), all normal access to the table for selecting rows or
+ modifying rows must be allowed by a row security policy. (However, the
+ table's owner is typically not subject to row security policies.) If no
+ policy exists for the table, a default-deny policy is used, meaning that
+ no rows are visible or can be modified. Operations that apply to the
+ whole table, such as TRUNCATE and REFERENCES,
+ are not subject to row security.
+
+ Row security policies can be specific to commands, or to roles, or to
+ both. A policy can be specified to apply to ALL
+ commands, or to SELECT, INSERT, UPDATE,
+ or DELETE. Multiple roles can be assigned to a given
+ policy, and normal role membership and inheritance rules apply.
+
+ To specify which rows are visible or modifiable according to a policy,
+ an expression is required that returns a Boolean result. This
+ expression will be evaluated for each row prior to any conditions or
+ functions coming from the user's query. (The only exceptions to this
+ rule are leakproof functions, which are guaranteed to
+ not leak information; the optimizer may choose to apply such functions
+ ahead of the row-security check.) Rows for which the expression does
+ not return true will not be processed. Separate expressions
+ may be specified to provide independent control over the rows which are
+ visible and the rows which are allowed to be modified. Policy
+ expressions are run as part of the query and with the privileges of the
+ user running the query, although security-definer functions can be used
+ to access data not available to the calling user.
+
+ Superusers and roles with the BYPASSRLS attribute always
+ bypass the row security system when accessing a table. Table owners
+ normally bypass row security as well, though a table owner can choose to
+ be subject to row security with ALTER
+ TABLE ... FORCE ROW LEVEL SECURITY.
+
+ Enabling and disabling row security, as well as adding policies to a
+ table, is always the privilege of the table owner only.
+
+ Policies are created using the CREATE POLICY
+ command, altered using the ALTER POLICY command,
+ and dropped using the DROP POLICY command. To
+ enable and disable row security for a given table, use the
+ ALTER TABLE command.
+
+ Each policy has a name and multiple policies can be defined for a
+ table. As policies are table-specific, each policy for a table must
+ have a unique name. Different tables may have policies with the
+ same name.
+
+ When multiple policies apply to a given query, they are combined using
+ either OR (for permissive policies, which are the
+ default) or using AND (for restrictive policies).
+ This is similar to the rule that a given role has the privileges
+ of all roles that they are a member of. Permissive vs. restrictive
+ policies are discussed further below.
+
+ As a simple example, here is how to create a policy on
+ the account relation to allow only members of
+ the managers role to access rows, and only rows of their
+ accounts:
+
+CREATE TABLE accounts (manager text, company text, contact_email text);
+
+ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY account_managers ON accounts TO managers
+ USING (manager = current_user);
+
+ The policy above implicitly provides a WITH CHECK
+ clause identical to its USING clause, so that the
+ constraint applies both to rows selected by a command (so a manager
+ cannot SELECT, UPDATE,
+ or DELETE existing rows belonging to a different
+ manager) and to rows modified by a command (so rows belonging to a
+ different manager cannot be created via INSERT
+ or UPDATE).
+
+ If no role is specified, or the special user name
+ PUBLIC is used, then the policy applies to all
+ users on the system. To allow all users to access only their own row in
+ a users table, a simple policy can be used:
+
+CREATE POLICY user_policy ON users
+ USING (user_name = current_user);
+
+ This works similarly to the previous example.
+
+ To use a different policy for rows that are being added to the table
+ compared to those rows that are visible, multiple policies can be
+ combined. This pair of policies would allow all users to view all rows
+ in the users table, but only modify their own:
+
+CREATE POLICY user_sel_policy ON users
+ FOR SELECT
+ USING (true);
+CREATE POLICY user_mod_policy ON users
+ USING (user_name = current_user);
+
+ In a SELECT command, these two policies are combined
+ using OR, with the net effect being that all rows
+ can be selected. In other command types, only the second policy applies,
+ so that the effects are the same as before.
+
+ Row security can also be disabled with the ALTER TABLE
+ command. Disabling row security does not remove any policies that are
+ defined on the table; they are simply ignored. Then all rows in the
+ table are visible and modifiable, subject to the standard SQL privileges
+ system.
+
+ Below is a larger example of how this feature can be used in production
+ environments. The table passwd emulates a Unix password
+ file:
+
+-- Simple passwd-file based example
+CREATE TABLE passwd (
+ user_name text UNIQUE NOT NULL,
+ pwhash text,
+ uid int PRIMARY KEY,
+ gid int NOT NULL,
+ real_name text NOT NULL,
+ home_phone text,
+ extra_info text,
+ home_dir text NOT NULL,
+ shell text NOT NULL
+);
+
+CREATE ROLE admin; -- Administrator
+CREATE ROLE bob; -- Normal user
+CREATE ROLE alice; -- Normal user
+
+-- Populate the table
+INSERT INTO passwd VALUES
+ ('admin','xxx',0,0,'Admin','111-222-3333',null,'/root','/bin/dash');
+INSERT INTO passwd VALUES
+ ('bob','xxx',1,1,'Bob','123-456-7890',null,'/home/bob','/bin/zsh');
+INSERT INTO passwd VALUES
+ ('alice','xxx',2,1,'Alice','098-765-4321',null,'/home/alice','/bin/zsh');
+
+-- Be sure to enable row-level security on the table
+ALTER TABLE passwd ENABLE ROW LEVEL SECURITY;
+
+-- Create policies
+-- Administrator can see all rows and add any rows
+CREATE POLICY admin_all ON passwd TO admin USING (true) WITH CHECK (true);
+-- Normal users can view all rows
+CREATE POLICY all_view ON passwd FOR SELECT USING (true);
+-- Normal users can update their own records, but
+-- limit which shells a normal user is allowed to set
+CREATE POLICY user_mod ON passwd FOR UPDATE
+ USING (current_user = user_name)
+ WITH CHECK (
+ current_user = user_name AND
+ shell IN ('/bin/bash','/bin/sh','/bin/dash','/bin/zsh','/bin/tcsh')
+ );
+
+-- Allow admin all normal rights
+GRANT SELECT, INSERT, UPDATE, DELETE ON passwd TO admin;
+-- Users only get select access on public columns
+GRANT SELECT
+ (user_name, uid, gid, real_name, home_phone, extra_info, home_dir, shell)
+ ON passwd TO public;
+-- Allow users to update certain columns
+GRANT UPDATE
+ (pwhash, real_name, home_phone, extra_info, shell)
+ ON passwd TO public;
+
+ As with any security settings, it's important to test and ensure that
+ the system is behaving as expected. Using the example above, this
+ demonstrates that the permission system is working properly.
+
+-- admin can view all rows and fields
+postgres=> set role admin;
+SET
+postgres=> table passwd;
+ user_name | pwhash | uid | gid | real_name | home_phone | extra_info | home_dir | shell
+-----------+--------+-----+-----+-----------+--------------+------------+-------------+-----------
+ admin | xxx | 0 | 0 | Admin | 111-222-3333 | | /root | /bin/dash
+ bob | xxx | 1 | 1 | Bob | 123-456-7890 | | /home/bob | /bin/zsh
+ alice | xxx | 2 | 1 | Alice | 098-765-4321 | | /home/alice | /bin/zsh
+(3 rows)
+
+-- Test what Alice is able to do
+postgres=> set role alice;
+SET
+postgres=> table passwd;
+ERROR: permission denied for table passwd
+postgres=> select user_name,real_name,home_phone,extra_info,home_dir,shell from passwd;
+ user_name | real_name | home_phone | extra_info | home_dir | shell
+-----------+-----------+--------------+------------+-------------+-----------
+ admin | Admin | 111-222-3333 | | /root | /bin/dash
+ bob | Bob | 123-456-7890 | | /home/bob | /bin/zsh
+ alice | Alice | 098-765-4321 | | /home/alice | /bin/zsh
+(3 rows)
+
+postgres=> update passwd set user_name = 'joe';
+ERROR: permission denied for table passwd
+-- Alice is allowed to change her own real_name, but no others
+postgres=> update passwd set real_name = 'Alice Doe';
+UPDATE 1
+postgres=> update passwd set real_name = 'John Doe' where user_name = 'admin';
+UPDATE 0
+postgres=> update passwd set shell = '/bin/xx';
+ERROR: new row violates WITH CHECK OPTION for "passwd"
+postgres=> delete from passwd;
+ERROR: permission denied for table passwd
+postgres=> insert into passwd (user_name) values ('xxx');
+ERROR: permission denied for table passwd
+-- Alice can change her own password; RLS silently prevents updating other rows
+postgres=> update passwd set pwhash = 'abc';
+UPDATE 1
+
+ All of the policies constructed thus far have been permissive policies,
+ meaning that when multiple policies are applied they are combined using
+ the “OR” Boolean operator. While permissive policies can be constructed
+ to only allow access to rows in the intended cases, it can be simpler to
+ combine permissive policies with restrictive policies (which the records
+ must pass and which are combined using the “AND” Boolean operator).
+ Building on the example above, we add a restrictive policy to require
+ the administrator to be connected over a local Unix socket to access the
+ records of the passwd table:
+
+CREATE POLICY admin_local_only ON passwd AS RESTRICTIVE TO admin
+ USING (pg_catalog.inet_client_addr() IS NULL);
+
+ We can then see that an administrator connecting over a network will not
+ see any records, due to the restrictive policy:
+
+ Referential integrity checks, such as unique or primary key constraints
+ and foreign key references, always bypass row security to ensure that
+ data integrity is maintained. Care must be taken when developing
+ schemas and row level policies to avoid “covert channel” leaks of
+ information through such referential integrity checks.
+
+ In some contexts it is important to be sure that row security is
+ not being applied. For example, when taking a backup, it could be
+ disastrous if row security silently caused some rows to be omitted
+ from the backup. In such a situation, you can set the
+ row_security configuration parameter
+ to off. This does not in itself bypass row security;
+ what it does is throw an error if any query's results would get filtered
+ by a policy. The reason for the error can then be investigated and
+ fixed.
+
+ In the examples above, the policy expressions consider only the current
+ values in the row to be accessed or updated. This is the simplest and
+ best-performing case; when possible, it's best to design row security
+ applications to work this way. If it is necessary to consult other rows
+ or other tables to make a policy decision, that can be accomplished using
+ sub-SELECTs, or functions that contain SELECTs,
+ in the policy expressions. Be aware however that such accesses can
+ create race conditions that could allow information leakage if care is
+ not taken. As an example, consider the following table design:
+
+-- definition of privilege groups
+CREATE TABLE groups (group_id int PRIMARY KEY,
+ group_name text NOT NULL);
+
+INSERT INTO groups VALUES
+ (1, 'low'),
+ (2, 'medium'),
+ (5, 'high');
+
+GRANT ALL ON groups TO alice; -- alice is the administrator
+GRANT SELECT ON groups TO public;
+
+-- definition of users' privilege levels
+CREATE TABLE users (user_name text PRIMARY KEY,
+ group_id int NOT NULL REFERENCES groups);
+
+INSERT INTO users VALUES
+ ('alice', 5),
+ ('bob', 2),
+ ('mallory', 2);
+
+GRANT ALL ON users TO alice;
+GRANT SELECT ON users TO public;
+
+-- table holding the information to be protected
+CREATE TABLE information (info text,
+ group_id int NOT NULL REFERENCES groups);
+
+INSERT INTO information VALUES
+ ('barely secret', 1),
+ ('slightly secret', 2),
+ ('very secret', 5);
+
+ALTER TABLE information ENABLE ROW LEVEL SECURITY;
+
+-- a row should be visible to/updatable by users whose security group_id is
+-- greater than or equal to the row's group_id
+CREATE POLICY fp_s ON information FOR SELECT
+ USING (group_id <= (SELECT group_id FROM users WHERE user_name = current_user));
+CREATE POLICY fp_u ON information FOR UPDATE
+ USING (group_id <= (SELECT group_id FROM users WHERE user_name = current_user));
+
+-- we rely only on RLS to protect the information table
+GRANT ALL ON information TO public;
+
+ Now suppose that alice wishes to change the “slightly
+ secret” information, but decides that mallory should not
+ be trusted with the new content of that row, so she does:
+
+BEGIN;
+UPDATE users SET group_id = 1 WHERE user_name = 'mallory';
+UPDATE information SET info = 'secret from mallory' WHERE group_id = 2;
+COMMIT;
+
+ That looks safe; there is no window wherein mallory should be
+ able to see the “secret from mallory” string. However, there is
+ a race condition here. If mallory is concurrently doing,
+ say,
+
+SELECT * FROM information WHERE group_id = 2 FOR UPDATE;
+
+ and her transaction is in READ COMMITTED mode, it is possible
+ for her to see “secret from mallory”. That happens if her
+ transaction reaches the information row just
+ after alice's does. It blocks waiting
+ for alice's transaction to commit, then fetches the updated
+ row contents thanks to the FOR UPDATE clause. However, it
+ does not fetch an updated row for the
+ implicit SELECT from users, because that
+ sub-SELECT did not have FOR UPDATE; instead
+ the users row is read with the snapshot taken at the start
+ of the query. Therefore, the policy expression tests the old value
+ of mallory's privilege level and allows her to see the
+ updated row.
+
+ There are several ways around this problem. One simple answer is to use
+ SELECT ... FOR SHARE in sub-SELECTs in row
+ security policies. However, that requires granting UPDATE
+ privilege on the referenced table (here users) to the
+ affected users, which might be undesirable. (But another row security
+ policy could be applied to prevent them from actually exercising that
+ privilege; or the sub-SELECT could be embedded into a security
+ definer function.) Also, heavy concurrent use of row share locks on the
+ referenced table could pose a performance problem, especially if updates
+ of it are frequent. Another solution, practical if updates of the
+ referenced table are infrequent, is to take an
+ ACCESS EXCLUSIVE lock on the
+ referenced table when updating it, so that no concurrent transactions
+ could be examining old row values. Or one could just wait for all
+ concurrent transactions to end after committing an update of the
+ referenced table and before making changes that rely on the new security
+ situation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-schemas.html b/pgsql/doc/postgresql/html/ddl-schemas.html
new file mode 100644
index 0000000000000000000000000000000000000000..c647faa8a5ac71750be835f70f3654bc5906de33
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-schemas.html
@@ -0,0 +1,329 @@
+
+5.9. Schemas
+ A PostgreSQL database cluster contains
+ one or more named databases. Roles and a few other object types are
+ shared across the entire cluster. A client connection to the server
+ can only access data in a single database, the one specified in the
+ connection request.
+
Note
+ Users of a cluster do not necessarily have the privilege to access every
+ database in the cluster. Sharing of role names means that there
+ cannot be different roles named, say, joe in two databases
+ in the same cluster; but the system can be configured to allow
+ joe access to only some of the databases.
+
+ A database contains one or more named schemas, which
+ in turn contain tables. Schemas also contain other kinds of named
+ objects, including data types, functions, and operators. The same
+ object name can be used in different schemas without conflict; for
+ example, both schema1 and myschema can
+ contain tables named mytable. Unlike databases,
+ schemas are not rigidly separated: a user can access objects in any
+ of the schemas in the database they are connected to, if they have
+ privileges to do so.
+
+ There are several reasons why one might want to use schemas:
+
+
+ To allow many users to use one database without interfering with
+ each other.
+
+ To organize database objects into logical groups to make them
+ more manageable.
+
+ Third-party applications can be put into separate schemas so
+ they do not collide with the names of other objects.
+
+
+ Schemas are analogous to directories at the operating system level,
+ except that schemas cannot be nested.
+
+ To create a schema, use the CREATE SCHEMA
+ command. Give the schema a name
+ of your choice. For example:
+
+CREATE SCHEMA myschema;
+
+
+ To create or access objects in a schema, write a
+ qualified name consisting of the schema name and
+ table name separated by a dot:
+
+schema.table
+
+ This works anywhere a table name is expected, including the table
+ modification commands and the data access commands discussed in
+ the following chapters.
+ (For brevity we will speak of tables only, but the same ideas apply
+ to other kinds of named objects, such as types and functions.)
+
+ Actually, the even more general syntax
+
+database.schema.table
+
+ can be used too, but at present this is just for pro forma
+ compliance with the SQL standard. If you write a database name,
+ it must be the same as the database you are connected to.
+
+ So to create a table in the new schema, use:
+
+CREATE TABLE myschema.mytable (
+ ...
+);
+
+
+ To drop a schema if it's empty (all objects in it have been
+ dropped), use:
+
+DROP SCHEMA myschema;
+
+ To drop a schema including all contained objects, use:
+
+DROP SCHEMA myschema CASCADE;
+
+ See Section 5.14 for a description of the general
+ mechanism behind this.
+
+ Often you will want to create a schema owned by someone else
+ (since this is one of the ways to restrict the activities of your
+ users to well-defined namespaces). The syntax for that is:
+
+ You can even omit the schema name, in which case the schema name
+ will be the same as the user name. See Section 5.9.6 for how this can be useful.
+
+ Schema names beginning with pg_ are reserved for
+ system purposes and cannot be created by users.
+
+ In the previous sections we created tables without specifying any
+ schema names. By default such tables (and other objects) are
+ automatically put into a schema named “public”. Every new
+ database contains such a schema. Thus, the following are equivalent:
+
+ Qualified names are tedious to write, and it's often best not to
+ wire a particular schema name into applications anyway. Therefore
+ tables are often referred to by unqualified names,
+ which consist of just the table name. The system determines which table
+ is meant by following a search path, which is a list
+ of schemas to look in. The first matching table in the search path
+ is taken to be the one wanted. If there is no match in the search
+ path, an error is reported, even if matching table names exist
+ in other schemas in the database.
+
+ The ability to create like-named objects in different schemas complicates
+ writing a query that references precisely the same objects every time. It
+ also opens up the potential for users to change the behavior of other
+ users' queries, maliciously or accidentally. Due to the prevalence of
+ unqualified names in queries and their use
+ in PostgreSQL internals, adding a schema
+ to search_path effectively trusts all users having
+ CREATE privilege on that schema. When you run an
+ ordinary query, a malicious user able to create objects in a schema of
+ your search path can take control and execute arbitrary SQL functions as
+ though you executed them.
+
+ The first schema named in the search path is called the current schema.
+ Aside from being the first schema searched, it is also the schema in
+ which new tables will be created if the CREATE TABLE
+ command does not specify a schema name.
+
+ To show the current search path, use the following command:
+
+SHOW search_path;
+
+ In the default setup this returns:
+
+ search_path
+--------------
+ "$user", public
+
+ The first element specifies that a schema with the same name as
+ the current user is to be searched. If no such schema exists,
+ the entry is ignored. The second element refers to the
+ public schema that we have seen already.
+
+ The first schema in the search path that exists is the default
+ location for creating new objects. That is the reason that by
+ default objects are created in the public schema. When objects
+ are referenced in any other context without schema qualification
+ (table modification, data modification, or query commands) the
+ search path is traversed until a matching object is found.
+ Therefore, in the default configuration, any unqualified access
+ again can only refer to the public schema.
+
+ To put our new schema in the path, we use:
+
+SET search_path TO myschema,public;
+
+ (We omit the $user here because we have no
+ immediate need for it.) And then we can access the table without
+ schema qualification:
+
+DROP TABLE mytable;
+
+ Also, since myschema is the first element in
+ the path, new objects would by default be created in it.
+
+ We could also have written:
+
+SET search_path TO myschema;
+
+ Then we no longer have access to the public schema without
+ explicit qualification. There is nothing special about the public
+ schema except that it exists by default. It can be dropped, too.
+
+ See also Section 9.26 for other ways to manipulate
+ the schema search path.
+
+ The search path works in the same way for data type names, function names,
+ and operator names as it does for table names. Data type and function
+ names can be qualified in exactly the same way as table names. If you
+ need to write a qualified operator name in an expression, there is a
+ special provision: you must write
+
+OPERATOR(schema.operator)
+
+ This is needed to avoid syntactic ambiguity. An example is:
+
+SELECT 3 OPERATOR(pg_catalog.+) 4;
+
+ In practice one usually relies on the search path for operators,
+ so as not to have to write anything so ugly as that.
+
+ By default, users cannot access any objects in schemas they do not
+ own. To allow that, the owner of the schema must grant the
+ USAGE privilege on the schema. By default, everyone
+ has that privilege on the schema public. To allow
+ users to make use of the objects in a schema, additional privileges might
+ need to be granted, as appropriate for the object.
+
+ A user can also be allowed to create objects in someone else's schema. To
+ allow that, the CREATE privilege on the schema needs to
+ be granted. In databases upgraded from
+ PostgreSQL 14 or earlier, everyone has that
+ privilege on the schema public.
+ Some usage patterns call for
+ revoking that privilege:
+
+REVOKE CREATE ON SCHEMA public FROM PUBLIC;
+
+ (The first “public” is the schema, the second
+ “public” means “every user”. In the
+ first sense it is an identifier, in the second sense it is a
+ key word, hence the different capitalization; recall the
+ guidelines from Section 4.1.1.)
+
+ In addition to public and user-created schemas, each
+ database contains a pg_catalog schema, which contains
+ the system tables and all the built-in data types, functions, and
+ operators. pg_catalog is always effectively part of
+ the search path. If it is not named explicitly in the path then
+ it is implicitly searched before searching the path's
+ schemas. This ensures that built-in names will always be
+ findable. However, you can explicitly place
+ pg_catalog at the end of your search path if you
+ prefer to have user-defined names override built-in names.
+
+ Since system table names begin with pg_, it is best to
+ avoid such names to ensure that you won't suffer a conflict if some
+ future version defines a system table named the same as your
+ table. (With the default search path, an unqualified reference to
+ your table name would then be resolved as the system table instead.)
+ System tables will continue to follow the convention of having
+ names beginning with pg_, so that they will not
+ conflict with unqualified user-table names so long as users avoid
+ the pg_ prefix.
+
+ Schemas can be used to organize your data in many ways.
+ A secure schema usage pattern prevents untrusted
+ users from changing the behavior of other users' queries. When a database
+ does not use a secure schema usage pattern, users wishing to securely
+ query that database would take protective action at the beginning of each
+ session. Specifically, they would begin each session by
+ setting search_path to the empty string or otherwise
+ removing schemas that are writable by non-superusers
+ from search_path. There are a few usage patterns
+ easily supported by the default configuration:
+
+ Constrain ordinary users to user-private schemas.
+ To implement this pattern, first ensure that no schemas have
+ public CREATE privileges. Then, for every user
+ needing to create non-temporary objects, create a schema with the
+ same name as that user, for example
+ CREATE SCHEMA alice AUTHORIZATION alice.
+ (Recall that the default search path starts
+ with $user, which resolves to the user
+ name. Therefore, if each user has a separate schema, they access
+ their own schemas by default.) This pattern is a secure schema
+ usage pattern unless an untrusted user is the database owner or
+ has been granted ADMIN OPTION on a relevant role,
+ in which case no secure schema usage pattern exists.
+
+ In PostgreSQL 15 and later, the default
+ configuration supports this usage pattern. In prior versions, or
+ when using a database that has been upgraded from a prior version,
+ you will need to remove the public CREATE
+ privilege from the public schema (issue
+ REVOKE CREATE ON SCHEMA public FROM PUBLIC).
+ Then consider auditing the public schema for
+ objects named like objects in schema pg_catalog.
+
+ Remove the public schema from the default search path, by modifying
+ postgresql.conf
+ or by issuing ALTER ROLE ALL SET search_path =
+ "$user". Then, grant privileges to create in the public
+ schema. Only qualified names will choose public schema objects. While
+ qualified table references are fine, calls to functions in the public
+ schema will be unsafe or
+ unreliable. If you create functions or extensions in the public
+ schema, use the first pattern instead. Otherwise, like the first
+ pattern, this is secure unless an untrusted user is the database owner
+ or has been granted ADMIN OPTION on a relevant role.
+
+ Keep the default search path, and grant privileges to create in the
+ public schema. All users access the public schema implicitly. This
+ simulates the situation where schemas are not available at all, giving
+ a smooth transition from the non-schema-aware world. However, this is
+ never a secure pattern. It is acceptable only when the database has a
+ single user or a few mutually-trusting users. In databases upgraded
+ from PostgreSQL 14 or earlier, this is the
+ default.
+
+
+ For any pattern, to install shared applications (tables to be used by
+ everyone, additional functions provided by third parties, etc.), put them
+ into separate schemas. Remember to grant appropriate privileges to allow
+ the other users to access them. Users can then refer to these additional
+ objects by qualifying the names with a schema name, or they can put the
+ additional schemas into their search path, as they choose.
+
+ In the SQL standard, the notion of objects in the same schema
+ being owned by different users does not exist. Moreover, some
+ implementations do not allow you to create schemas that have a
+ different name than their owner. In fact, the concepts of schema
+ and user are nearly equivalent in a database system that
+ implements only the basic schema support specified in the
+ standard. Therefore, many users consider qualified names to
+ really consist of
+ user_name.table_name.
+ This is how PostgreSQL will effectively
+ behave if you create a per-user schema for every user.
+
+ Also, there is no concept of a public schema in the
+ SQL standard. For maximum conformance to the standard, you should
+ not use the public schema.
+
+ Of course, some SQL database systems might not implement schemas
+ at all, or provide namespace support by allowing (possibly
+ limited) cross-database access. If you need to work with those
+ systems, then maximum portability would be achieved by not using
+ schemas at all.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl-system-columns.html b/pgsql/doc/postgresql/html/ddl-system-columns.html
new file mode 100644
index 0000000000000000000000000000000000000000..53dc8b63ec134239dc8b2f739a596bb07442d705
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl-system-columns.html
@@ -0,0 +1,58 @@
+
+5.5. System Columns
+ Every table has several system columns that are
+ implicitly defined by the system. Therefore, these names cannot be
+ used as names of user-defined columns. (Note that these
+ restrictions are separate from whether the name is a key word or
+ not; quoting a name will not allow you to escape these
+ restrictions.) You do not really need to be concerned about these
+ columns; just know they exist.
+
+ The OID of the table containing this row. This column is
+ particularly handy for queries that select from partitioned
+ tables (see Section 5.11) or inheritance
+ hierarchies (see Section 5.10), since without it,
+ it's difficult to tell which individual table a row came from. The
+ tableoid can be joined against the
+ oid column of
+ pg_class to obtain the table name.
+
+ The identity (transaction ID) of the inserting transaction for
+ this row version. (A row version is an individual state of a
+ row; each update of a row creates a new row version for the same
+ logical row.)
+
+ The identity (transaction ID) of the deleting transaction, or
+ zero for an undeleted row version. It is possible for this column to
+ be nonzero in a visible row version. That usually indicates that the
+ deleting transaction hasn't committed yet, or that an attempted
+ deletion was rolled back.
+
+ The physical location of the row version within its table. Note that
+ although the ctid can be used to
+ locate the row version very quickly, a row's
+ ctid will change if it is
+ updated or moved by VACUUM FULL. Therefore
+ ctid is useless as a long-term row
+ identifier. A primary key should be used to identify logical rows.
+
+ Transaction identifiers are also 32-bit quantities. In a
+ long-lived database it is possible for transaction IDs to wrap
+ around. This is not a fatal problem given appropriate maintenance
+ procedures; see Chapter 25 for details. It is
+ unwise, however, to depend on the uniqueness of transaction IDs
+ over the long term (more than one billion transactions).
+
+ Command identifiers are also 32-bit quantities. This creates a hard limit
+ of 232 (4 billion) SQL commands
+ within a single transaction. In practice this limit is not a
+ problem — note that the limit is on the number of
+ SQL commands, not the number of rows processed.
+ Also, only commands that actually modify the database contents will
+ consume a command identifier.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ddl.html b/pgsql/doc/postgresql/html/ddl.html
new file mode 100644
index 0000000000000000000000000000000000000000..99df749ebdcba73be1aa9da4bc55dee6132ce164
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ddl.html
@@ -0,0 +1,13 @@
+
+Chapter 5. Data Definition
+ This chapter covers how one creates the database structures that
+ will hold one's data. In a relational database, the raw data is
+ stored in tables, so the majority of this chapter is devoted to
+ explaining how tables are created and modified and what features are
+ available to control what data is stored in the tables.
+ Subsequently, we discuss how tables can be organized into
+ schemas, and how privileges can be assigned to tables. Finally,
+ we will briefly look at other features that affect the data storage,
+ such as inheritance, table partitioning, views, functions, and
+ triggers.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/default-roles.html b/pgsql/doc/postgresql/html/default-roles.html
new file mode 100644
index 0000000000000000000000000000000000000000..d23a5fc269959a78db9f5b067fde357915140b44
--- /dev/null
+++ b/pgsql/doc/postgresql/html/default-roles.html
@@ -0,0 +1,9 @@
+
+O.2. Default Roles Renamed to Predefined Roles
+ PostgreSQL 13 and below used the term “Default Roles”. However, as these
+ roles are not able to actually be changed and are installed as part of the
+ system at initialization time, the more appropriate term to use is “Predefined Roles”.
+ See Section 22.5 for current documentation regarding
+ Predefined Roles, and the release notes for
+ PostgreSQL 14 for details on this change.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dict-int.html b/pgsql/doc/postgresql/html/dict-int.html
new file mode 100644
index 0000000000000000000000000000000000000000..5e86f2ecbf862c266ff61fb04c4a0381610cefa1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dict-int.html
@@ -0,0 +1,64 @@
+
+F.13. dict_int — example full-text search dictionary for integers
F.13. dict_int —
+ example full-text search dictionary for integers
+ dict_int is an example of an add-on dictionary template
+ for full-text search. The motivation for this example dictionary is to
+ control the indexing of integers (signed and unsigned), allowing such
+ numbers to be indexed while preventing excessive growth in the number of
+ unique words, which greatly affects the performance of searching.
+
+ This module is considered “trusted”, that is, it can be
+ installed by non-superusers who have CREATE privilege
+ on the current database.
+
+ The maxlen parameter specifies the maximum number of
+ digits allowed in an integer word. The default value is 6.
+
+ The rejectlong parameter specifies whether an overlength
+ integer should be truncated or ignored. If rejectlong is
+ false (the default), the dictionary returns the first
+ maxlen digits of the integer. If rejectlong is
+ true, the dictionary treats an overlength integer as a stop
+ word, so that it will not be indexed. Note that this also means that
+ such an integer cannot be searched for.
+
+ The absval parameter specifies whether leading
+ “+” or “-”
+ signs should be removed from integer words. The default
+ is false. When true, the sign is
+ removed before maxlen is applied.
+
+ Installing the dict_int extension creates a text search
+ template intdict_template and a dictionary intdict
+ based on it, with the default parameters. You can alter the
+ parameters, for example
+
+
+mydb# ALTER TEXT SEARCH DICTIONARY intdict (MAXLEN = 4, REJECTLONG = true);
+ALTER TEXT SEARCH DICTIONARY
+
+
+ or create new dictionaries based on the template.
+
+
+ but real-world usage will involve including it in a text search
+ configuration as described in Chapter 12.
+ That might look like this:
+
+
+ALTER TEXT SEARCH CONFIGURATION english
+ ALTER MAPPING FOR int, uint WITH intdict;
+
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dict-xsyn.html b/pgsql/doc/postgresql/html/dict-xsyn.html
new file mode 100644
index 0000000000000000000000000000000000000000..de5177aff4015ccf5c1cc6d4bc521be296c6aec3
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dict-xsyn.html
@@ -0,0 +1,98 @@
+
+F.14. dict_xsyn — example synonym full-text search dictionary
F.14. dict_xsyn — example synonym full-text search dictionary
+ dict_xsyn (Extended Synonym Dictionary) is an example of an
+ add-on dictionary template for full-text search. This dictionary type
+ replaces words with groups of their synonyms, and so makes it possible to
+ search for a word using any of its synonyms.
+
+ A dict_xsyn dictionary accepts the following options:
+
+ matchorig controls whether the original word is accepted by
+ the dictionary. Default is true.
+
+ matchsynonyms controls whether the synonyms are
+ accepted by the dictionary. Default is false.
+
+ keeporig controls whether the original word is included in
+ the dictionary's output. Default is true.
+
+ keepsynonyms controls whether the synonyms are included in
+ the dictionary's output. Default is true.
+
+ rules is the base name of the file containing the list of
+ synonyms. This file must be stored in
+ $SHAREDIR/tsearch_data/ (where $SHAREDIR means
+ the PostgreSQL installation's shared-data directory).
+ Its name must end in .rules (which is not to be included in
+ the rules parameter).
+
+ The rules file has the following format:
+
+ Each line represents a group of synonyms for a single word, which is
+ given first on the line. Synonyms are separated by whitespace, thus:
+
+word syn1 syn2 syn3
+
+
+ The sharp (#) sign is a comment delimiter. It may appear at
+ any position in a line. The rest of the line will be skipped.
+
+ Look at xsyn_sample.rules, which is installed in
+ $SHAREDIR/tsearch_data/, for an example.
+
+ Installing the dict_xsyn extension creates a text search
+ template xsyn_template and a dictionary xsyn
+ based on it, with default parameters. You can alter the
+ parameters, for example
+
+
+mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false);
+ALTER TEXT SEARCH DICTIONARY
+
+
+ or create new dictionaries based on the template.
+
+ To test the dictionary, you can try
+
+
+mydb=# SELECT ts_lexize('xsyn', 'word');
+ ts_lexize
+-----------------------
+ {syn1,syn2,syn3}
+
+mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true);
+ALTER TEXT SEARCH DICTIONARY
+
+mydb=# SELECT ts_lexize('xsyn', 'word');
+ ts_lexize
+-----------------------
+ {word,syn1,syn2,syn3}
+
+mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=false, MATCHSYNONYMS=true);
+ALTER TEXT SEARCH DICTIONARY
+
+mydb=# SELECT ts_lexize('xsyn', 'syn1');
+ ts_lexize
+-----------------------
+ {syn1,syn2,syn3}
+
+mydb# ALTER TEXT SEARCH DICTIONARY xsyn (RULES='my_rules', KEEPORIG=true, MATCHORIG=false, KEEPSYNONYMS=false);
+ALTER TEXT SEARCH DICTIONARY
+
+mydb=# SELECT ts_lexize('xsyn', 'syn1');
+ ts_lexize
+-----------------------
+ {word}
+
+
+ Real-world usage will involve including it in a text search
+ configuration as described in Chapter 12.
+ That might look like this:
+
+
+ALTER TEXT SEARCH CONFIGURATION english
+ ALTER MAPPING FOR word, asciiword WITH xsyn, english_stem;
+
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/different-replication-solutions.html b/pgsql/doc/postgresql/html/different-replication-solutions.html
new file mode 100644
index 0000000000000000000000000000000000000000..2e59d08e6d15abb31dc220c54e49e9c415e0f50d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/different-replication-solutions.html
@@ -0,0 +1,137 @@
+
+27.1. Comparison of Different Solutions
+ Shared disk failover avoids synchronization overhead by having only one
+ copy of the database. It uses a single disk array that is shared by
+ multiple servers. If the main database server fails, the standby server
+ is able to mount and start the database as though it were recovering from
+ a database crash. This allows rapid failover with no data loss.
+
+ Shared hardware functionality is common in network storage devices.
+ Using a network file system is also possible, though care must be
+ taken that the file system has full POSIX behavior (see Section 19.2.2.1). One significant limitation of this
+ method is that if the shared disk array fails or becomes corrupt, the
+ primary and standby servers are both nonfunctional. Another issue is
+ that the standby server should never access the shared storage while
+ the primary server is running.
+
File System (Block Device) Replication
+ A modified version of shared hardware functionality is file system
+ replication, where all changes to a file system are mirrored to a file
+ system residing on another computer. The only restriction is that
+ the mirroring must be done in a way that ensures the standby server
+ has a consistent copy of the file system — specifically, writes
+ to the standby must be done in the same order as those on the primary.
+ DRBD is a popular file system replication solution
+ for Linux.
+
Write-Ahead Log Shipping
+ Warm and hot standby servers can be kept current by reading a
+ stream of write-ahead log (WAL)
+ records. If the main server fails, the standby contains
+ almost all of the data of the main server, and can be quickly
+ made the new primary database server. This can be synchronous or
+ asynchronous and can only be done for the entire database server.
+
+ A standby server can be implemented using file-based log shipping
+ (Section 27.2) or streaming replication (see
+ Section 27.2.5), or a combination of both. For
+ information on hot standby, see Section 27.4.
+
Logical Replication
+ Logical replication allows a database server to send a stream of data
+ modifications to another server. PostgreSQL
+ logical replication constructs a stream of logical data modifications
+ from the WAL. Logical replication allows replication of data changes on
+ a per-table basis. In addition, a server that is publishing its own
+ changes can also subscribe to changes from another server, allowing data
+ to flow in multiple directions. For more information on logical
+ replication, see Chapter 31. Through the
+ logical decoding interface (Chapter 49),
+ third-party extensions can also provide similar functionality.
+
Trigger-Based Primary-Standby Replication
+ A trigger-based replication setup typically funnels data modification
+ queries to a designated primary server. Operating on a per-table basis,
+ the primary server sends data changes (typically) asynchronously to the
+ standby servers. Standby servers can answer queries while the primary is
+ running, and may allow some local data changes or write activity. This
+ form of replication is often used for offloading large analytical or data
+ warehouse queries.
+
+ Slony-I is an example of this type of
+ replication, with per-table granularity, and support for multiple standby
+ servers. Because it updates the standby server asynchronously (in
+ batches), there is possible data loss during fail over.
+
SQL-Based Replication Middleware
+ With SQL-based replication middleware, a program intercepts
+ every SQL query and sends it to one or all servers. Each server
+ operates independently. Read-write queries must be sent to all servers,
+ so that every server receives any changes. But read-only queries can be
+ sent to just one server, allowing the read workload to be distributed
+ among them.
+
+ If queries are simply broadcast unmodified, functions like
+ random(), CURRENT_TIMESTAMP, and
+ sequences can have different values on different servers.
+ This is because each server operates independently, and because
+ SQL queries are broadcast rather than actual data changes. If
+ this is unacceptable, either the middleware or the application
+ must determine such values from a single source and then use those
+ values in write queries. Care must also be taken that all
+ transactions either commit or abort on all servers, perhaps
+ using two-phase commit (PREPARE TRANSACTION
+ and COMMIT PREPARED).
+ Pgpool-II and Continuent Tungsten
+ are examples of this type of replication.
+
Asynchronous Multimaster Replication
+ For servers that are not regularly connected or have slow
+ communication links, like laptops or
+ remote servers, keeping data consistent among servers is a
+ challenge. Using asynchronous multimaster replication, each
+ server works independently, and periodically communicates with
+ the other servers to identify conflicting transactions. The
+ conflicts can be resolved by users or conflict resolution rules.
+ Bucardo is an example of this type of replication.
+
Synchronous Multimaster Replication
+ In synchronous multimaster replication, each server can accept
+ write requests, and modified data is transmitted from the
+ original server to every other server before each transaction
+ commits. Heavy write activity can cause excessive locking and
+ commit delays, leading to poor performance. Read requests can
+ be sent to any server. Some implementations use shared disk
+ to reduce the communication overhead. Synchronous multimaster
+ replication is best for mostly read workloads, though its big
+ advantage is that any server can accept write requests —
+ there is no need to partition workloads between primary and
+ standby servers, and because the data changes are sent from one
+ server to another, there is no problem with non-deterministic
+ functions like random().
+
+ PostgreSQL does not offer this type of replication,
+ though PostgreSQL two-phase commit (PREPARE TRANSACTION and COMMIT PREPARED)
+ can be used to implement this in application code or middleware.
+
+ Table 27.1 summarizes
+ the capabilities of the various solutions listed above.
+
Table 27.1. High Availability, Load Balancing, and Replication Feature Matrix
Feature
Shared Disk
File System Repl.
Write-Ahead Log Shipping
Logical Repl.
Trigger-Based Repl.
SQL Repl. Middle-ware
Async. MM Repl.
Sync. MM Repl.
Popular examples
NAS
DRBD
built-in streaming repl.
built-in logical repl., pglogical
Londiste, Slony
pgpool-II
Bucardo
Comm. method
shared disk
disk blocks
WAL
logical decoding
table rows
SQL
table rows
table rows and row locks
No special hardware required
•
•
•
•
•
•
•
Allows multiple primary servers
•
•
•
•
No overhead on primary
•
•
•
•
No waiting for multiple servers
•
with sync off
with sync off
•
•
Primary failure will never lose data
•
•
with sync on
with sync on
•
•
Replicas accept read-only queries
with hot standby
•
•
•
•
•
Per-table granularity
•
•
•
•
No conflict resolution necessary
•
•
•
•
•
•
+ There are a few solutions that do not fit into the above categories:
+
Data Partitioning
+ Data partitioning splits tables into data sets. Each set can
+ be modified by only one server. For example, data can be
+ partitioned by offices, e.g., London and Paris, with a server
+ in each office. If queries combining London and Paris data
+ are necessary, an application can query both servers, or
+ primary/standby replication can be used to keep a read-only copy
+ of the other office's data on each server.
+
Multiple-Server Parallel Query Execution
+ Many of the above solutions allow multiple servers to handle multiple
+ queries, but none allow a single query to use multiple servers to
+ complete faster. This solution allows multiple servers to work
+ concurrently on a single query. It is usually accomplished by
+ splitting the data among servers and having each server execute its
+ part of the query and return results to a central server where they
+ are combined and returned to the user. This can be implemented using the
+ PL/Proxy tool set.
+
+ It should also be noted that because PostgreSQL
+ is open source and easily extended, a number of companies have
+ taken PostgreSQL and created commercial
+ closed-source solutions with unique failover, replication, and load
+ balancing capabilities. These are not discussed here.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/disk-full.html b/pgsql/doc/postgresql/html/disk-full.html
new file mode 100644
index 0000000000000000000000000000000000000000..d8d6418cddc21344586251ba6a64544af91d9abc
--- /dev/null
+++ b/pgsql/doc/postgresql/html/disk-full.html
@@ -0,0 +1,20 @@
+
+29.2. Disk Full Failure
+ The most important disk monitoring task of a database administrator
+ is to make sure the disk doesn't become full. A filled data disk will
+ not result in data corruption, but it might prevent useful activity
+ from occurring. If the disk holding the WAL files grows full, database
+ server panic and consequent shutdown might occur.
+
+ If you cannot free up additional space on the disk by deleting
+ other things, you can move some of the database files to other file
+ systems by making use of tablespaces. See Section 23.6 for more information about that.
+
Tip
+ Some file systems perform badly when they are almost full, so do
+ not wait until the disk is completely full to take action.
+
+ If your system supports per-user disk quotas, then the database
+ will naturally be subject to whatever quota is placed on the user
+ the server runs as. Exceeding the quota will have the same bad
+ effects as running out of disk space entirely.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/disk-usage.html b/pgsql/doc/postgresql/html/disk-usage.html
new file mode 100644
index 0000000000000000000000000000000000000000..f10783f3fd89e0ceb9136af2fa3898636ead3ad1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/disk-usage.html
@@ -0,0 +1,83 @@
+
+29.1. Determining Disk Usage
+ Each table has a primary heap disk file where most of the data is
+ stored. If the table has any columns with potentially-wide values,
+ there also might be a TOAST file associated with the table,
+ which is used to store values too wide to fit comfortably in the main
+ table (see Section 73.2). There will be one valid index
+ on the TOAST table, if present. There also might be indexes
+ associated with the base table. Each table and index is stored in a
+ separate disk file — possibly more than one file, if the file would
+ exceed one gigabyte. Naming conventions for these files are described
+ in Section 73.1.
+
+ You can monitor disk space in three ways:
+ using the SQL functions listed in Table 9.96,
+ using the oid2name module, or
+ using manual inspection of the system catalogs.
+ The SQL functions are the easiest to use and are generally recommended.
+ The remainder of this section shows how to do it by inspection of the
+ system catalogs.
+
+ Using psql on a recently vacuumed or analyzed database,
+ you can issue queries to see the disk usage of any table:
+
+ Each page is typically 8 kilobytes. (Remember, relpages
+ is only updated by VACUUM, ANALYZE, and
+ a few DDL commands such as CREATE INDEX.) The file path name
+ is of interest if you want to examine the table's disk file directly.
+
+ To show the space used by TOAST tables, use a query
+ like the following:
+
+SELECT relname, relpages
+FROM pg_class,
+ (SELECT reltoastrelid
+ FROM pg_class
+ WHERE relname = 'customer') AS ss
+WHERE oid = ss.reltoastrelid OR
+ oid = (SELECT indexrelid
+ FROM pg_index
+ WHERE indrelid = ss.reltoastrelid)
+ORDER BY relname;
+
+ relname | relpages
+----------------------+----------
+ pg_toast_16806 | 0
+ pg_toast_16806_index | 1
+
+
+ You can easily display index sizes, too:
+
+SELECT c2.relname, c2.relpages
+FROM pg_class c, pg_class c2, pg_index i
+WHERE c.relname = 'customer' AND
+ c.oid = i.indrelid AND
+ c2.oid = i.indexrelid
+ORDER BY c2.relname;
+
+ relname | relpages
+-------------------+----------
+ customer_id_index | 26
+
+
+ It is easy to find your largest tables and indexes using this
+ information:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/diskusage.html b/pgsql/doc/postgresql/html/diskusage.html
new file mode 100644
index 0000000000000000000000000000000000000000..c283813e33db770dcb2bb24e72907ebb2929b542
--- /dev/null
+++ b/pgsql/doc/postgresql/html/diskusage.html
@@ -0,0 +1,5 @@
+
+Chapter 29. Monitoring Disk Usage
+ This chapter discusses how to monitor the disk usage of a
+ PostgreSQL database system.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dml-delete.html b/pgsql/doc/postgresql/html/dml-delete.html
new file mode 100644
index 0000000000000000000000000000000000000000..386551e6c552b3796170431a1223cc787ffb1ad7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dml-delete.html
@@ -0,0 +1,28 @@
+
+6.3. Deleting Data
+ So far we have explained how to add data to tables and how to
+ change data. What remains is to discuss how to remove data that is
+ no longer needed. Just as adding data is only possible in whole
+ rows, you can only remove entire rows from a table. In the
+ previous section we explained that SQL does not provide a way to
+ directly address individual rows. Therefore, removing rows can
+ only be done by specifying conditions that the rows to be removed
+ have to match. If you have a primary key in the table then you can
+ specify the exact row. But you can also remove groups of rows
+ matching a condition, or you can remove all rows in the table at
+ once.
+
+ You use the DELETE
+ command to remove rows; the syntax is very similar to the
+ UPDATE command. For instance, to remove all
+ rows from the products table that have a price of 10, use:
+
+DELETE FROM products WHERE price = 10;
+
+
+ If you simply write:
+
+DELETE FROM products;
+
+ then all rows in the table will be deleted! Caveat programmer.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dml-insert.html b/pgsql/doc/postgresql/html/dml-insert.html
new file mode 100644
index 0000000000000000000000000000000000000000..cd3cb22c44b8344d25c4c439de179b501821a07e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dml-insert.html
@@ -0,0 +1,81 @@
+
+6.1. Inserting Data
+ When a table is created, it contains no data. The first thing to
+ do before a database can be of much use is to insert data. Data is
+ inserted one row at a time. You can also insert more than one row
+ in a single command, but it is not possible to insert something that
+ is not a complete row. Even if you know only some column values, a
+ complete row must be created.
+
+ To create a new row, use the INSERT
+ command. The command requires the
+ table name and column values. For
+ example, consider the products table from Chapter 5:
+
+INSERT INTO products VALUES (1, 'Cheese', 9.99);
+
+ The data values are listed in the order in which the columns appear
+ in the table, separated by commas. Usually, the data values will
+ be literals (constants), but scalar expressions are also allowed.
+
+ The above syntax has the drawback that you need to know the order
+ of the columns in the table. To avoid this you can also list the
+ columns explicitly. For example, both of the following commands
+ have the same effect as the one above:
+
+ Many users consider it good practice to always list the column
+ names.
+
+ If you don't have values for all the columns, you can omit some of
+ them. In that case, the columns will be filled with their default
+ values. For example:
+
+INSERT INTO products (product_no, name) VALUES (1, 'Cheese');
+INSERT INTO products VALUES (1, 'Cheese');
+
+ The second form is a PostgreSQL
+ extension. It fills the columns from the left with as many values
+ as are given, and the rest will be defaulted.
+
+ For clarity, you can also request default values explicitly, for
+ individual columns or for the entire row:
+
+INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', DEFAULT);
+INSERT INTO products DEFAULT VALUES;
+
+
+ You can insert multiple rows in a single command:
+
+ It is also possible to insert the result of a query (which might be no
+ rows, one row, or many rows):
+
+INSERT INTO products (product_no, name, price)
+ SELECT product_no, name, price FROM new_products
+ WHERE release_date = 'today';
+
+ This provides the full power of the SQL query mechanism (Chapter 7) for computing the rows to be inserted.
+
Tip
+ When inserting a lot of data at the same time, consider using
+ the COPY command.
+ It is not as flexible as the INSERT
+ command, but is more efficient. Refer
+ to Section 14.4 for more information on improving
+ bulk loading performance.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dml-returning.html b/pgsql/doc/postgresql/html/dml-returning.html
new file mode 100644
index 0000000000000000000000000000000000000000..59f626a450f326642dda348325508b2fc85a1069
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dml-returning.html
@@ -0,0 +1,53 @@
+
+6.4. Returning Data from Modified Rows
+ Sometimes it is useful to obtain data from modified rows while they are
+ being manipulated. The INSERT, UPDATE,
+ and DELETE commands all have an
+ optional RETURNING clause that supports this. Use
+ of RETURNING avoids performing an extra database query to
+ collect the data, and is especially valuable when it would otherwise be
+ difficult to identify the modified rows reliably.
+
+ The allowed contents of a RETURNING clause are the same as
+ a SELECT command's output list
+ (see Section 7.3). It can contain column
+ names of the command's target table, or value expressions using those
+ columns. A common shorthand is RETURNING *, which selects
+ all columns of the target table in order.
+
+ In an INSERT, the data available to RETURNING is
+ the row as it was inserted. This is not so useful in trivial inserts,
+ since it would just repeat the data provided by the client. But it can
+ be very handy when relying on computed default values. For example,
+ when using a serial
+ column to provide unique identifiers, RETURNING can return
+ the ID assigned to a new row:
+
+CREATE TABLE users (firstname text, lastname text, id serial primary key);
+
+INSERT INTO users (firstname, lastname) VALUES ('Joe', 'Cool') RETURNING id;
+
+ The RETURNING clause is also very useful
+ with INSERT ... SELECT.
+
+ In an UPDATE, the data available to RETURNING is
+ the new content of the modified row. For example:
+
+UPDATE products SET price = price * 1.10
+ WHERE price <= 99.99
+ RETURNING name, price AS new_price;
+
+
+ In a DELETE, the data available to RETURNING is
+ the content of the deleted row. For example:
+
+DELETE FROM products
+ WHERE obsoletion_date = 'today'
+ RETURNING *;
+
+
+ If there are triggers (Chapter 39) on the target table,
+ the data available to RETURNING is the row as modified by
+ the triggers. Thus, inspecting columns computed by triggers is another
+ common use-case for RETURNING.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dml-update.html b/pgsql/doc/postgresql/html/dml-update.html
new file mode 100644
index 0000000000000000000000000000000000000000..cad065f28d95fcbcdc45e0e0080af204f99e0be9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dml-update.html
@@ -0,0 +1,61 @@
+
+6.2. Updating Data
+ The modification of data that is already in the database is
+ referred to as updating. You can update individual rows, all the
+ rows in a table, or a subset of all rows. Each column can be
+ updated separately; the other columns are not affected.
+
+ To update existing rows, use the UPDATE
+ command. This requires
+ three pieces of information:
+
The name of the table and column to update
The new value of the column
Which row(s) to update
+
+ Recall from Chapter 5 that SQL does not, in general,
+ provide a unique identifier for rows. Therefore it is not
+ always possible to directly specify which row to update.
+ Instead, you specify which conditions a row must meet in order to
+ be updated. Only if you have a primary key in the table (independent of
+ whether you declared it or not) can you reliably address individual rows
+ by choosing a condition that matches the primary key.
+ Graphical database access tools rely on this fact to allow you to
+ update rows individually.
+
+ For example, this command updates all products that have a price of
+ 5 to have a price of 10:
+
+UPDATE products SET price = 10 WHERE price = 5;
+
+ This might cause zero, one, or many rows to be updated. It is not
+ an error to attempt an update that does not match any rows.
+
+ Let's look at that command in detail. First is the key word
+ UPDATE followed by the table name. As usual,
+ the table name can be schema-qualified, otherwise it is looked up
+ in the path. Next is the key word SET followed
+ by the column name, an equal sign, and the new column value. The
+ new column value can be any scalar expression, not just a constant.
+ For example, if you want to raise the price of all products by 10%
+ you could use:
+
+UPDATE products SET price = price * 1.10;
+
+ As you see, the expression for the new value can refer to the existing
+ value(s) in the row. We also left out the WHERE clause.
+ If it is omitted, it means that all rows in the table are updated.
+ If it is present, only those rows that match the
+ WHERE condition are updated. Note that the equals
+ sign in the SET clause is an assignment while
+ the one in the WHERE clause is a comparison, but
+ this does not create any ambiguity. Of course, the
+ WHERE condition does
+ not have to be an equality test. Many other operators are
+ available (see Chapter 9). But the expression
+ needs to evaluate to a Boolean result.
+
+ You can update more than one column in an
+ UPDATE command by listing more than one
+ assignment in the SET clause. For example:
+
+UPDATE mytable SET a = 5, b = 3, c = 1 WHERE a > 0;
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dml.html b/pgsql/doc/postgresql/html/dml.html
new file mode 100644
index 0000000000000000000000000000000000000000..4b2a2434605f9182735d8d986769c0691a71b599
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dml.html
@@ -0,0 +1,9 @@
+
+Chapter 6. Data Manipulation
+ The previous chapter discussed how to create tables and other
+ structures to hold your data. Now it is time to fill the tables
+ with data. This chapter covers how to insert, update, and delete
+ table data. The chapter
+ after this will finally explain how to extract your long-lost data
+ from the database.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide-authoring.html b/pgsql/doc/postgresql/html/docguide-authoring.html
new file mode 100644
index 0000000000000000000000000000000000000000..d6ac29e85af3cfb2296945ed003cf491a6220904
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide-authoring.html
@@ -0,0 +1,23 @@
+
+J.5. Documentation Authoring
+ The documentation sources are most conveniently modified with an editor
+ that has a mode for editing XML, and even more so if it has some awareness
+ of XML schema languages so that it can know about
+ DocBook syntax specifically.
+
+ Note that for historical reasons the documentation source files are named
+ with an extension .sgml even though they are now XML
+ files. So you might need to adjust your editor configuration to set the
+ correct mode.
+
+ nXML Mode, which ships with
+ Emacs, is the most common mode for editing
+ XML documents with Emacs.
+ It will allow you to use Emacs to insert tags
+ and check markup consistency, and it supports
+ DocBook out of the box. Check the
+ nXML manual for detailed documentation.
+
+ src/tools/editors/emacs.samples contains
+ recommended settings for this mode.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide-build-meson.html b/pgsql/doc/postgresql/html/docguide-build-meson.html
new file mode 100644
index 0000000000000000000000000000000000000000..851e31e707e537fa48e6b4cd358a4ca61292adf7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide-build-meson.html
@@ -0,0 +1,17 @@
+
+J.4. Building the Documentation with Meson
+ Two options are provided for building the documentation using Meson.
+ Change to the build directory before running
+ one of these commands, or add -C build to the command.
+
+ To build just the HTML version of the documentation:
+
+build$ ninja docs
+
+ To build all forms of the documentation:
+
+build$ ninja alldocs
+
+ The output appears in the
+ subdirectory build/doc/src/sgml.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide-build.html b/pgsql/doc/postgresql/html/docguide-build.html
new file mode 100644
index 0000000000000000000000000000000000000000..e48771889ae2133c1dd46809b292d93286030f01
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide-build.html
@@ -0,0 +1,99 @@
+
+J.3. Building the Documentation with Make
+ Once you have everything set up, change to the directory
+ doc/src/sgml and run one of the commands
+ described in the following subsections to build the
+ documentation. (Remember to use GNU make.)
+
+ To build the HTML version of the documentation:
+
+doc/src/sgml$ make html
+
+ This is also the default target. The output appears in the
+ subdirectory html.
+
+ To produce HTML documentation with the stylesheet used on postgresql.org instead of the
+ default simple style use:
+
+doc/src/sgml$ make STYLE=website html
+
+
+ If the STYLE=website option is used, the generated HTML
+ files include references to stylesheets hosted on postgresql.org and
+ require network access to view.
+
+ We use the DocBook XSL stylesheets to
+ convert DocBook
+ refentry pages to *roff output suitable for man
+ pages. To create the man pages, use the command:
+
+ To produce a PDF rendition of the documentation
+ using FOP, you can use one of the following
+ commands, depending on the preferred paper format:
+
+
+ For A4 format:
+
+doc/src/sgml$ make postgres-A4.pdf
+
+
+ For U.S. letter format:
+
+doc/src/sgml$ make postgres-US.pdf
+
+
+
+ Because the PostgreSQL documentation is fairly
+ big, FOP will require a significant amount of
+ memory. Because of that, on some systems, the build will fail with a
+ memory-related error message. This can usually be fixed by configuring
+ Java heap settings in the configuration
+ file ~/.foprc, for example:
+
+# FOP binary distribution
+FOP_OPTS='-Xmx1500m'
+# Debian
+JAVA_ARGS='-Xmx1500m'
+# Red Hat
+ADDITIONAL_FLAGS='-Xmx1500m'
+
+ There is a minimum amount of memory that is required, and to some extent
+ more memory appears to make things a bit faster. On systems with very
+ little memory (less than 1 GB), the build will either be very slow due to
+ swapping or will not work at all.
+
+ In its default configuration FOP will emit an
+ INFO message for each page. The log level can be
+ changed via ~/.foprc:
+
+ The installation instructions are also distributed as plain text,
+ in case they are needed in a situation where better reading tools
+ are not available. The INSTALL file
+ corresponds to Chapter 17, with some minor
+ changes to account for the different context. To recreate the
+ file, change to the directory doc/src/sgml
+ and enter make INSTALL. Building text output
+ requires Pandoc version 1.13 or newer as an
+ additional build tool.
+
+ In the past, the release notes and regression testing instructions
+ were also distributed as plain text, but this practice has been
+ discontinued.
+
+ Building the documentation can take very long. But there is a
+ method to just check the correct syntax of the documentation
+ files, which only takes a few seconds:
+
+doc/src/sgml$ make check
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide-docbook.html b/pgsql/doc/postgresql/html/docguide-docbook.html
new file mode 100644
index 0000000000000000000000000000000000000000..d39ab1621c678da74efc0873af8a04b3046df4a0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide-docbook.html
@@ -0,0 +1,23 @@
+
+J.1. DocBook
+ The documentation sources are written in
+ DocBook, which is a markup language
+ defined in XML. In what
+ follows, the terms DocBook and XML are both
+ used, but technically they are not interchangeable.
+
+ DocBook allows an author to specify the
+ structure and content of a technical document without worrying
+ about presentation details. A document style defines how that
+ content is rendered into one of several final forms. DocBook is
+ maintained by the
+ OASIS group. The
+ official DocBook site has good introductory and reference documentation and
+ a complete O'Reilly book for your online reading pleasure. The
+
+ NewbieDoc Docbook Guide is very helpful for beginners.
+ The
+ FreeBSD Documentation Project also uses DocBook and has some good
+ information, including a number of style guidelines that might be
+ worth considering.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide-style.html b/pgsql/doc/postgresql/html/docguide-style.html
new file mode 100644
index 0000000000000000000000000000000000000000..2cd773d1707a9feebb429918963c3ec3e88914f9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide-style.html
@@ -0,0 +1,89 @@
+
+J.6. Style Guide
+ Reference pages should follow a standard layout. This allows
+ users to find the desired information more quickly, and it also
+ encourages writers to document all relevant aspects of a command.
+ Consistency is not only desired among
+ PostgreSQL reference pages, but also
+ with reference pages provided by the operating system and other
+ packages. Hence the following guidelines have been developed.
+ They are for the most part consistent with similar guidelines
+ established by various operating systems.
+
+ Reference pages that describe executable commands should contain
+ the following sections, in this order. Sections that do not apply
+ can be omitted. Additional top-level sections should only be used
+ in special circumstances; often that information belongs in the
+ “Usage” section.
+
+
+ This section contains the syntax diagram of the command. The
+ synopsis should normally not list each command-line option;
+ that is done below. Instead, list the major components of the
+ command line, such as where input and output files go.
+
+ If the program uses 0 for success and non-zero for failure,
+ then you do not need to document it. If there is a meaning
+ behind the different non-zero exit codes, list them here.
+
+ Describe any sublanguage or run-time interface of the program.
+ If the program is not interactive, this section can usually be
+ omitted. Otherwise, this section is a catch-all for
+ describing run-time features. Use subsections if appropriate.
+
+ List all environment variables that the program might use.
+ Try to be complete; even seemingly trivial variables like
+ SHELL might be of interest to the user.
+
+ List any files that the program might access implicitly. That
+ is, do not list input and output files that were specified on
+ the command line, but list configuration files, etc.
+
+ Explain any unusual output that the program might create.
+ Refrain from listing every possible error message. This is a
+ lot of work and has little use in practice. But if, say, the
+ error messages have a standard format that the user can parse,
+ this would be the place to explain it.
+
+ Cross-references, listed in the following order: other
+ PostgreSQL command reference pages,
+ PostgreSQL SQL command reference
+ pages, citation of PostgreSQL
+ manuals, other reference pages (e.g., operating system, other
+ packages), other documentation. Items in the same group are
+ listed alphabetically.
+
+
+ Reference pages describing SQL commands should contain the
+ following sections: Name, Synopsis, Description, Parameters,
+ Outputs, Notes, Examples, Compatibility, History, See
+ Also. The Parameters section is like the Options section, but
+ there is more freedom about which clauses of the command can be
+ listed. The Outputs section is only needed if the command returns
+ something other than a default command-completion tag. The Compatibility
+ section should explain to what extent
+ this command conforms to the SQL standard(s), or to which other
+ database system it is compatible. The See Also section of SQL
+ commands should list SQL commands before cross-references to
+ programs.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide-toolsets.html b/pgsql/doc/postgresql/html/docguide-toolsets.html
new file mode 100644
index 0000000000000000000000000000000000000000..da5bc188306e5da9369cb98bfaa1dacca4d865ae
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide-toolsets.html
@@ -0,0 +1,120 @@
+
+J.2. Tool Sets
+ This is the definition of DocBook itself. We currently use version
+ 4.5; you cannot use later or earlier versions. You need
+ the XML variant of the DocBook DTD, not
+ the SGML variant.
+
+ This library and the xmllint tool it contains are
+ used for processing XML. Many developers will already
+ have Libxml2 installed, because it is also
+ used when building the PostgreSQL code. Note, however,
+ that xmllint might need to be installed from a
+ separate subpackage.
+
+ This is a program for converting, among other things, XML to PDF.
+ It is needed only if you want to build the documentation in PDF format.
+
+
+ We have documented experience with several installation methods for
+ the various tools that are needed to process the documentation.
+ These will be described below. There might be some other packaged
+ distributions for these tools. Please report package status to the
+ documentation mailing list, and we will include that information
+ here.
+
J.2.1. Installation on Fedora, RHEL, and Derivatives #
+ When building the documentation from the doc
+ directory you'll need to use gmake, because the
+ makefile provided is not suitable for FreeBSD's make.
+
+ Without it, xsltproc will throw errors like this:
+
+I/O error : Attempt to load network entity http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd
+postgres.sgml:21: warning: failed to load external entity "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"
+...
+
+
+ While it is possible to use the Apple-provided versions
+ of xmllint and xsltproc
+ instead of those from MacPorts or Homebrew, you'll still need
+ to install the DocBook DTD and stylesheets, and set up a catalog
+ file that points to them.
+
+ Before you can build the documentation you need to run the
+ configure script, as you would when building
+ the PostgreSQL programs themselves.
+ Check the output near the end of the run; it should look something
+ like this:
+
+checking for xmllint... xmllint
+checking for xsltproc... xsltproc
+checking for fop... fop
+checking for dbtoepub... dbtoepub
+
+ If xmllint or xsltproc is not
+ found, you will not be able to build any of the documentation.
+ fop is only needed to build the documentation in
+ PDF format.
+ dbtoepub is only needed to build the documentation
+ in EPUB format.
+
+ If necessary, you can tell configure where to find
+ these programs, for example
+
+ If you prefer to build PostgreSQL using
+ Meson, instead run meson setup as described in
+ Section 17.4, and then see
+ Section J.4.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/docguide.html b/pgsql/doc/postgresql/html/docguide.html
new file mode 100644
index 0000000000000000000000000000000000000000..bccaa013ad76ff19a0e69a73a29d47d942a00b31
--- /dev/null
+++ b/pgsql/doc/postgresql/html/docguide.html
@@ -0,0 +1,24 @@
+
+Appendix J. Documentation
+ PostgreSQL has four primary documentation
+ formats:
+
+
+ Plain text, for pre-installation information
+
+ HTML, for on-line browsing and reference
+
+ PDF, for printing
+
+ man pages, for quick reference.
+
+
+ Additionally, a number of plain-text README files can
+ be found throughout the PostgreSQL source tree,
+ documenting various implementation issues.
+
+ HTML documentation and man pages are part of a
+ standard distribution and are installed by default. PDF
+ format documentation is available separately for
+ download.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/domains.html b/pgsql/doc/postgresql/html/domains.html
new file mode 100644
index 0000000000000000000000000000000000000000..ca925c9d3bb5ecc281203390dc40fae6ed584626
--- /dev/null
+++ b/pgsql/doc/postgresql/html/domains.html
@@ -0,0 +1,34 @@
+
+8.18. Domain Types
+ A domain is a user-defined data type that is
+ based on another underlying type. Optionally,
+ it can have constraints that restrict its valid values to a subset of
+ what the underlying type would allow. Otherwise it behaves like the
+ underlying type — for example, any operator or function that
+ can be applied to the underlying type will work on the domain type.
+ The underlying type can be any built-in or user-defined base type,
+ enum type, array type, composite type, range type, or another domain.
+
+ For example, we could create a domain over integers that accepts only
+ positive integers:
+
+CREATE DOMAIN posint AS integer CHECK (VALUE > 0);
+CREATE TABLE mytable (id posint);
+INSERT INTO mytable VALUES(1); -- works
+INSERT INTO mytable VALUES(-1); -- fails
+
+
+ When an operator or function of the underlying type is applied to a
+ domain value, the domain is automatically down-cast to the underlying
+ type. Thus, for example, the result of mytable.id - 1
+ is considered to be of type integer not posint.
+ We could write (mytable.id - 1)::posint to cast the
+ result back to posint, causing the domain's constraints
+ to be rechecked. In this case, that would result in an error if the
+ expression had been applied to an id value of
+ 1. Assigning a value of the underlying type to a field or variable of
+ the domain type is allowed without writing an explicit cast, but the
+ domain's constraints will be checked.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/dynamic-trace.html b/pgsql/doc/postgresql/html/dynamic-trace.html
new file mode 100644
index 0000000000000000000000000000000000000000..eca471df7f93a8842030e0d3f7ef8e97f28683b8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/dynamic-trace.html
@@ -0,0 +1,303 @@
+
+28.5. Dynamic Tracing
+ PostgreSQL provides facilities to support
+ dynamic tracing of the database server. This allows an external
+ utility to be called at specific points in the code and thereby trace
+ execution.
+
+ A number of probes or trace points are already inserted into the source
+ code. These probes are intended to be used by database developers and
+ administrators. By default the probes are not compiled into
+ PostgreSQL; the user needs to explicitly tell
+ the configure script to make the probes available.
+
+ Currently, the
+ DTrace
+ utility is supported, which, at the time of this writing, is available
+ on Solaris, macOS, FreeBSD, NetBSD, and Oracle Linux. The
+ SystemTap project
+ for Linux provides a DTrace equivalent and can also be used. Supporting other dynamic
+ tracing utilities is theoretically possible by changing the definitions for
+ the macros in src/include/utils/probes.h.
+
+ By default, probes are not available, so you will need to
+ explicitly tell the configure script to make the probes available
+ in PostgreSQL. To include DTrace support
+ specify --enable-dtrace to configure. See Section 17.3.3.6 for further information.
+
+ A number of standard probes are provided in the source code,
+ as shown in Table 28.48;
+ Table 28.49
+ shows the types used in the probes. More probes can certainly be
+ added to enhance PostgreSQL's observability.
+
Table 28.48. Built-in DTrace Probes
Name
Parameters
Description
transaction-start
(LocalTransactionId)
Probe that fires at the start of a new transaction.
+ arg0 is the transaction ID.
transaction-commit
(LocalTransactionId)
Probe that fires when a transaction completes successfully.
+ arg0 is the transaction ID.
transaction-abort
(LocalTransactionId)
Probe that fires when a transaction completes unsuccessfully.
+ arg0 is the transaction ID.
query-start
(const char *)
Probe that fires when the processing of a query is started.
+ arg0 is the query string.
query-done
(const char *)
Probe that fires when the processing of a query is complete.
+ arg0 is the query string.
query-parse-start
(const char *)
Probe that fires when the parsing of a query is started.
+ arg0 is the query string.
query-parse-done
(const char *)
Probe that fires when the parsing of a query is complete.
+ arg0 is the query string.
query-rewrite-start
(const char *)
Probe that fires when the rewriting of a query is started.
+ arg0 is the query string.
query-rewrite-done
(const char *)
Probe that fires when the rewriting of a query is complete.
+ arg0 is the query string.
query-plan-start
()
Probe that fires when the planning of a query is started.
query-plan-done
()
Probe that fires when the planning of a query is complete.
query-execute-start
()
Probe that fires when the execution of a query is started.
query-execute-done
()
Probe that fires when the execution of a query is complete.
statement-status
(const char *)
Probe that fires anytime the server process updates its
+ pg_stat_activity.status.
+ arg0 is the new status string.
checkpoint-start
(int)
Probe that fires when a checkpoint is started.
+ arg0 holds the bitwise flags used to distinguish different checkpoint
+ types, such as shutdown, immediate or force.
checkpoint-done
(int, int, int, int, int)
Probe that fires when a checkpoint is complete.
+ (The probes listed next fire in sequence during checkpoint processing.)
+ arg0 is the number of buffers written. arg1 is the total number of
+ buffers. arg2, arg3 and arg4 contain the number of WAL files added,
+ removed and recycled respectively.
clog-checkpoint-start
(bool)
Probe that fires when the CLOG portion of a checkpoint is started.
+ arg0 is true for normal checkpoint, false for shutdown
+ checkpoint.
clog-checkpoint-done
(bool)
Probe that fires when the CLOG portion of a checkpoint is
+ complete. arg0 has the same meaning as for clog-checkpoint-start.
subtrans-checkpoint-start
(bool)
Probe that fires when the SUBTRANS portion of a checkpoint is
+ started.
+ arg0 is true for normal checkpoint, false for shutdown
+ checkpoint.
subtrans-checkpoint-done
(bool)
Probe that fires when the SUBTRANS portion of a checkpoint is
+ complete. arg0 has the same meaning as for
+ subtrans-checkpoint-start.
multixact-checkpoint-start
(bool)
Probe that fires when the MultiXact portion of a checkpoint is
+ started.
+ arg0 is true for normal checkpoint, false for shutdown
+ checkpoint.
multixact-checkpoint-done
(bool)
Probe that fires when the MultiXact portion of a checkpoint is
+ complete. arg0 has the same meaning as for
+ multixact-checkpoint-start.
buffer-checkpoint-start
(int)
Probe that fires when the buffer-writing portion of a checkpoint
+ is started.
+ arg0 holds the bitwise flags used to distinguish different checkpoint
+ types, such as shutdown, immediate or force.
buffer-sync-start
(int, int)
Probe that fires when we begin to write dirty buffers during
+ checkpoint (after identifying which buffers must be written).
+ arg0 is the total number of buffers.
+ arg1 is the number that are currently dirty and need to be written.
buffer-sync-written
(int)
Probe that fires after each buffer is written during checkpoint.
+ arg0 is the ID number of the buffer.
buffer-sync-done
(int, int, int)
Probe that fires when all dirty buffers have been written.
+ arg0 is the total number of buffers.
+ arg1 is the number of buffers actually written by the checkpoint process.
+ arg2 is the number that were expected to be written (arg1 of
+ buffer-sync-start); any difference reflects other processes flushing
+ buffers during the checkpoint.
buffer-checkpoint-sync-start
()
Probe that fires after dirty buffers have been written to the
+ kernel, and before starting to issue fsync requests.
buffer-checkpoint-done
()
Probe that fires when syncing of buffers to disk is
+ complete.
twophase-checkpoint-start
()
Probe that fires when the two-phase portion of a checkpoint is
+ started.
twophase-checkpoint-done
()
Probe that fires when the two-phase portion of a checkpoint is
+ complete.
Probe that fires when a relation extension starts.
+ arg0 contains the fork to be extended. arg1, arg2, and arg3 contain the
+ tablespace, database, and relation OIDs identifying the relation. arg4
+ is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared
+ buffer. arg5 is the number of blocks the caller would like to extend
+ by.
Probe that fires when a relation extension is complete.
+ arg0 contains the fork to be extended. arg1, arg2, and arg3 contain the
+ tablespace, database, and relation OIDs identifying the relation. arg4
+ is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared
+ buffer. arg5 is the number of blocks the relation was extended by, this
+ can be less than the number in the
+ buffer-extend-start due to resource
+ constraints. arg6 contains the BlockNumber of the first new
+ block.
buffer-read-start
(ForkNumber, BlockNumber, Oid, Oid, Oid, int)
Probe that fires when a buffer read is started.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
+ arg5 is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared buffer.
+
Probe that fires when a buffer read is complete.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
+ arg5 is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared buffer.
+ arg6 is true if the buffer was found in the pool, false if not.
buffer-flush-start
(ForkNumber, BlockNumber, Oid, Oid, Oid)
Probe that fires before issuing any write request for a shared
+ buffer.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
buffer-flush-done
(ForkNumber, BlockNumber, Oid, Oid, Oid)
Probe that fires when a write request is complete. (Note
+ that this just reflects the time to pass the data to the kernel;
+ it's typically not actually been written to disk yet.)
+ The arguments are the same as for buffer-flush-start.
wal-buffer-write-dirty-start
()
Probe that fires when a server process begins to write a
+ dirty WAL buffer because no more WAL buffer space is available.
+ (If this happens often, it implies that
+ wal_buffers is too small.)
wal-buffer-write-dirty-done
()
Probe that fires when a dirty WAL buffer write is complete.
wal-insert
(unsigned char, unsigned char)
Probe that fires when a WAL record is inserted.
+ arg0 is the resource manager (rmid) for the record.
+ arg1 contains the info flags.
wal-switch
()
Probe that fires when a WAL segment switch is requested.
smgr-md-read-start
(ForkNumber, BlockNumber, Oid, Oid, Oid, int)
Probe that fires when beginning to read a block from a relation.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
+ arg5 is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared buffer.
Probe that fires when a block read is complete.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
+ arg5 is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared buffer.
+ arg6 is the number of bytes actually read, while arg7 is the number
+ requested (if these are different it indicates trouble).
smgr-md-write-start
(ForkNumber, BlockNumber, Oid, Oid, Oid, int)
Probe that fires when beginning to write a block to a relation.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
+ arg5 is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared buffer.
Probe that fires when a block write is complete.
+ arg0 and arg1 contain the fork and block numbers of the page.
+ arg2, arg3, and arg4 contain the tablespace, database, and relation OIDs
+ identifying the relation.
+ arg5 is the ID of the backend which created the temporary relation for a
+ local buffer, or InvalidBackendId (-1) for a shared buffer.
+ arg6 is the number of bytes actually written, while arg7 is the number
+ requested (if these are different it indicates trouble).
sort-start
(int, bool, int, int, bool, int)
Probe that fires when a sort operation is started.
+ arg0 indicates heap, index or datum sort.
+ arg1 is true for unique-value enforcement.
+ arg2 is the number of key columns.
+ arg3 is the number of kilobytes of work memory allowed.
+ arg4 is true if random access to the sort result is required.
+ arg5 indicates serial when 0, parallel worker when
+ 1, or parallel leader when 2.
sort-done
(bool, long)
Probe that fires when a sort is complete.
+ arg0 is true for external sort, false for internal sort.
+ arg1 is the number of disk blocks used for an external sort,
+ or kilobytes of memory used for an internal sort.
lwlock-acquire
(char *, LWLockMode)
Probe that fires when an LWLock has been acquired.
+ arg0 is the LWLock's tranche.
+ arg1 is the requested lock mode, either exclusive or shared.
lwlock-release
(char *)
Probe that fires when an LWLock has been released (but note
+ that any released waiters have not yet been awakened).
+ arg0 is the LWLock's tranche.
lwlock-wait-start
(char *, LWLockMode)
Probe that fires when an LWLock was not immediately available and
+ a server process has begun to wait for the lock to become available.
+ arg0 is the LWLock's tranche.
+ arg1 is the requested lock mode, either exclusive or shared.
lwlock-wait-done
(char *, LWLockMode)
Probe that fires when a server process has been released from its
+ wait for an LWLock (it does not actually have the lock yet).
+ arg0 is the LWLock's tranche.
+ arg1 is the requested lock mode, either exclusive or shared.
lwlock-condacquire
(char *, LWLockMode)
Probe that fires when an LWLock was successfully acquired when the
+ caller specified no waiting.
+ arg0 is the LWLock's tranche.
+ arg1 is the requested lock mode, either exclusive or shared.
lwlock-condacquire-fail
(char *, LWLockMode)
Probe that fires when an LWLock was not successfully acquired when
+ the caller specified no waiting.
+ arg0 is the LWLock's tranche.
+ arg1 is the requested lock mode, either exclusive or shared.
Probe that fires when a request for a heavyweight lock (lmgr lock)
+ has begun to wait because the lock is not available.
+ arg0 through arg3 are the tag fields identifying the object being
+ locked. arg4 indicates the type of object being locked.
+ arg5 indicates the lock type being requested.
Probe that fires when a request for a heavyweight lock (lmgr lock)
+ has finished waiting (i.e., has acquired the lock).
+ The arguments are the same as for lock-wait-start.
deadlock-found
()
Probe that fires when a deadlock is found by the deadlock
+ detector.
Table 28.49. Defined Types Used in Probe Parameters
+ The example below shows a DTrace script for analyzing transaction
+ counts in the system, as an alternative to snapshotting
+ pg_stat_database before and after a performance test:
+
+ When executed, the example D script gives output such as:
+
+# ./txn_count.d `pgrep -n postgres` or ./txn_count.d <PID>
+^C
+
+Start 71
+Commit 70
+Total time (ns) 2312105013
+
+
Note
+ SystemTap uses a different notation for trace scripts than DTrace does,
+ even though the underlying trace points are compatible. One point worth
+ noting is that at this writing, SystemTap scripts must reference probe
+ names using double underscores in place of hyphens. This is expected to
+ be fixed in future SystemTap releases.
+
+ You should remember that DTrace scripts need to be carefully written and
+ debugged, otherwise the trace information collected might
+ be meaningless. In most cases where problems are found it is the
+ instrumentation that is at fault, not the underlying system. When
+ discussing information found using dynamic tracing, be sure to enclose
+ the script used to allow that too to be checked and discussed.
+
+ New probes can be defined within the code wherever the developer
+ desires, though this will require a recompilation. Below are the steps
+ for inserting new probes:
+
+ Decide on probe names and data to be made available through the probes
+
+ Add the probe definitions to src/backend/utils/probes.d
+
+ Include pg_trace.h if it is not already present in the
+ module(s) containing the probe points, and insert
+ TRACE_POSTGRESQL probe macros at the desired locations
+ in the source code
+
+ Recompile and verify that the new probes are available
+
Example:
+ Here is an example of how you would add a probe to trace all new
+ transactions by transaction ID.
+
+ Decide that the probe will be named transaction-start and
+ requires a parameter of type LocalTransactionId
+
+ Add the probe definition to src/backend/utils/probes.d:
+
+probe transaction__start(LocalTransactionId);
+
+ Note the use of the double underline in the probe name. In a DTrace
+ script using the probe, the double underline needs to be replaced with a
+ hyphen, so transaction-start is the name to document for
+ users.
+
+ At compile time, transaction__start is converted to a macro
+ called TRACE_POSTGRESQL_TRANSACTION_START (notice the
+ underscores are single here), which is available by including
+ pg_trace.h. Add the macro call to the appropriate location
+ in the source code. In this case, it looks like the following:
+
+
+ After recompiling and running the new binary, check that your newly added
+ probe is available by executing the following DTrace command. You
+ should see similar output:
+
+ There are a few things to be careful about when adding trace macros
+ to the C code:
+
+
+ You should take care that the data types specified for a probe's
+ parameters match the data types of the variables used in the macro.
+ Otherwise, you will get compilation errors.
+
+ On most platforms, if PostgreSQL is
+ built with --enable-dtrace, the arguments to a trace
+ macro will be evaluated whenever control passes through the
+ macro, even if no tracing is being done. This is
+ usually not worth worrying about if you are just reporting the
+ values of a few local variables. But beware of putting expensive
+ function calls into the arguments. If you need to do that,
+ consider protecting the macro with a check to see if the trace
+ is actually enabled:
+
+
+ The earthdistance module provides two different approaches to
+ calculating great circle distances on the surface of the Earth. The one
+ described first depends on the cube module.
+ The second one is based on the built-in point data type,
+ using longitude and latitude for the coordinates.
+
+ In this module, the Earth is assumed to be perfectly spherical.
+ (If that's too inaccurate for you, you might want to look at the
+ PostGIS
+ project.)
+
+ The cube module must be installed
+ before earthdistance can be installed
+ (although you can use the CASCADE option
+ of CREATE EXTENSION to install both in one command).
+
Caution
+ It is strongly recommended that earthdistance
+ and cube be installed in the same schema, and that
+ that schema be one for which CREATE privilege has not been and will not
+ be granted to any untrusted users.
+ Otherwise there are installation-time security hazards
+ if earthdistance's schema contains objects defined
+ by a hostile user.
+ Furthermore, when using earthdistance's functions
+ after installation, the entire search path should contain only trusted
+ schemas.
+
+ Data is stored in cubes that are points (both corners are the same) using 3
+ coordinates representing the x, y, and z distance from the center of the
+ Earth. A domain
+ earth over type cube is provided, which
+ includes constraint checks that the value meets these restrictions and
+ is reasonably close to the actual surface of the Earth.
+
+ The radius of the Earth is obtained from the earth()
+ function. It is given in meters. But by changing this one function you can
+ change the module to use some other units, or to use a different value of
+ the radius that you feel is more appropriate.
+
+ This package has applications to astronomical databases as well.
+ Astronomers will probably want to change earth() to return a
+ radius of 180/pi() so that distances are in degrees.
+
+ Functions are provided to support input in latitude and longitude (in
+ degrees), to support output of latitude and longitude, to calculate
+ the great circle distance between two points and to easily specify a
+ bounding box usable for index searches.
+
+ The provided functions are shown
+ in Table F.5.
+
Table F.5. Cube-Based Earthdistance Functions
+ Function
+
+
+ Description
+
+
+ earth ()
+ → float8
+
+
+ Returns the assumed radius of the Earth.
+
+
+ sec_to_gc ( float8 )
+ → float8
+
+
+ Converts the normal straight line
+ (secant) distance between two points on the surface of the Earth
+ to the great circle distance between them.
+
+
+ gc_to_sec ( float8 )
+ → float8
+
+
+ Converts the great circle distance between two points on the
+ surface of the Earth to the normal straight line (secant) distance
+ between them.
+
+
+ ll_to_earth ( float8, float8 )
+ → earth
+
+
+ Returns the location of a point on the surface of the Earth given
+ its latitude (argument 1) and longitude (argument 2) in degrees.
+
+
+ latitude ( earth )
+ → float8
+
+
+ Returns the latitude in degrees of a point on the surface of the
+ Earth.
+
+
+ longitude ( earth )
+ → float8
+
+
+ Returns the longitude in degrees of a point on the surface of the
+ Earth.
+
+
+ earth_distance ( earth, earth )
+ → float8
+
+
+ Returns the great circle distance between two points on the
+ surface of the Earth.
+
+
+ earth_box ( earth, float8 )
+ → cube
+
+
+ Returns a box suitable for an indexed search using the cube
+ @>
+ operator for points within a given great circle distance of a location.
+ Some points in this box are further than the specified great circle
+ distance from the location, so a second check using
+ earth_distance should be included in the query.
+
+ The second part of the module relies on representing Earth locations as
+ values of type point, in which the first component is taken to
+ represent longitude in degrees, and the second component is taken to
+ represent latitude in degrees. Points are taken as (longitude, latitude)
+ and not vice versa because longitude is closer to the intuitive idea of
+ x-axis and latitude to y-axis.
+
+ A single operator is provided, shown
+ in Table F.6.
+
Table F.6. Point-Based Earthdistance Operators
+ Operator
+
+
+ Description
+
+ point<@>point
+ → float8
+
+
+ Computes the distance in statute miles between
+ two points on the Earth's surface.
+
+ Note that unlike the cube-based part of the module, units
+ are hardwired here: changing the earth() function will
+ not affect the results of this operator.
+
+ One disadvantage of the longitude/latitude representation is that
+ you need to be careful about the edge conditions near the poles
+ and near +/- 180 degrees of longitude. The cube-based
+ representation avoids these discontinuities.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-commands.html b/pgsql/doc/postgresql/html/ecpg-commands.html
new file mode 100644
index 0000000000000000000000000000000000000000..db2602e4f0ba81eb37e5e0ef78942e29c703e797
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-commands.html
@@ -0,0 +1,163 @@
+
+36.3. Running SQL Commands
+EXEC SQL DELETE FROM foo WHERE number = 9999;
+EXEC SQL COMMIT;
+
+
+ Updates:
+
+EXEC SQL UPDATE foo
+ SET ascii = 'foobar'
+ WHERE number = 9999;
+EXEC SQL COMMIT;
+
+
+ SELECT statements that return a single result
+ row can also be executed using
+ EXEC SQL directly. To handle result sets with
+ multiple rows, an application has to use a cursor;
+ see Section 36.3.2 below. (As a special case, an
+ application can fetch multiple rows at once into an array host
+ variable; see Section 36.4.4.3.1.)
+
+ Single-row select:
+
+EXEC SQL SELECT foo INTO :FooBar FROM table1 WHERE ascii = 'doodad';
+
+
+ Also, a configuration parameter can be retrieved with the
+ SHOW command:
+
+EXEC SQL SHOW search_path INTO :var;
+
+
+ The tokens of the form
+ :something are
+ host variables, that is, they refer to
+ variables in the C program. They are explained in Section 36.4.
+
+ To retrieve a result set holding multiple rows, an application has
+ to declare a cursor and fetch each row from the cursor. The steps
+ to use a cursor are the following: declare a cursor, open it, fetch
+ a row from the cursor, repeat, and finally close it.
+
+ Select using cursors:
+
+EXEC SQL DECLARE foo_bar CURSOR FOR
+ SELECT number, ascii FROM foo
+ ORDER BY ascii;
+EXEC SQL OPEN foo_bar;
+EXEC SQL FETCH foo_bar INTO :FooBar, DooDad;
+...
+EXEC SQL CLOSE foo_bar;
+EXEC SQL COMMIT;
+
+
+ For more details about declaring a cursor, see DECLARE; for more details about fetching rows from a
+ cursor, see FETCH.
+
Note
+ The ECPG DECLARE command does not actually
+ cause a statement to be sent to the PostgreSQL backend. The
+ cursor is opened in the backend (using the
+ backend's DECLARE command) at the point when
+ the OPEN command is executed.
+
+ In the default mode, statements are committed only when
+ EXEC SQL COMMIT is issued. The embedded SQL
+ interface also supports autocommit of transactions (similar to
+ psql's default behavior) via the -t
+ command-line option to ecpg (see ecpg) or via the EXEC SQL SET AUTOCOMMIT TO
+ ON statement. In autocommit mode, each command is
+ automatically committed unless it is inside an explicit transaction
+ block. This mode can be explicitly turned off using EXEC
+ SQL SET AUTOCOMMIT TO OFF.
+
+ The following transaction management commands are available:
+
+
+ When the values to be passed to an SQL statement are not known at
+ compile time, or the same statement is going to be used many
+ times, then prepared statements can be useful.
+
+ The statement is prepared using the
+ command PREPARE. For the values that are not
+ known yet, use the
+ placeholder “?”:
+
+EXEC SQL PREPARE stmt1 FROM "SELECT oid, datname FROM pg_database WHERE oid = ?";
+
+
+ If a statement returns a single row, the application can
+ call EXECUTE after
+ PREPARE to execute the statement, supplying the
+ actual values for the placeholders with a USING
+ clause:
+
+EXEC SQL EXECUTE stmt1 INTO :dboid, :dbname USING 1;
+
+
+ If a statement returns multiple rows, the application can use a
+ cursor declared based on the prepared statement. To bind input
+ parameters, the cursor must be opened with
+ a USING clause:
+
+EXEC SQL PREPARE stmt1 FROM "SELECT oid,datname FROM pg_database WHERE oid > ?";
+EXEC SQL DECLARE foo_bar CURSOR FOR stmt1;
+
+/* when end of result set reached, break out of while loop */
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+EXEC SQL OPEN foo_bar USING 100;
+...
+while (1)
+{
+ EXEC SQL FETCH NEXT FROM foo_bar INTO :dboid, :dbname;
+ ...
+}
+EXEC SQL CLOSE foo_bar;
+
+
+ When you don't need the prepared statement anymore, you should
+ deallocate it:
+
+EXEC SQL DEALLOCATE PREPARE name;
+
+
+ For more details about PREPARE,
+ see PREPARE. Also
+ see Section 36.5 for more details about using
+ placeholders and input parameters.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-concept.html b/pgsql/doc/postgresql/html/ecpg-concept.html
new file mode 100644
index 0000000000000000000000000000000000000000..0f5a1f89e0aed09e8685a807eb8c522adcb4de56
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-concept.html
@@ -0,0 +1,52 @@
+
+36.1. The Concept
+ An embedded SQL program consists of code written in an ordinary
+ programming language, in this case C, mixed with SQL commands in
+ specially marked sections. To build the program, the source code (*.pgc)
+ is first passed through the embedded SQL preprocessor, which converts it
+ to an ordinary C program (*.c), and afterwards it can be processed by a C
+ compiler. (For details about the compiling and linking see Section 36.10.)
+ Converted ECPG applications call functions in the libpq library
+ through the embedded SQL library (ecpglib), and communicate with
+ the PostgreSQL server using the normal frontend-backend protocol.
+
+ Embedded SQL has advantages over other methods
+ for handling SQL commands from C code. First, it
+ takes care of the tedious passing of information to and from
+ variables in your C program. Second, the SQL
+ code in the program is checked at build time for syntactical
+ correctness. Third, embedded SQL in C is
+ specified in the SQL standard and supported by
+ many other SQL database systems. The
+ PostgreSQL implementation is designed to match this
+ standard as much as possible, and it is usually possible to port
+ embedded SQL programs written for other SQL
+ databases to PostgreSQL with relative
+ ease.
+
+ As already stated, programs written for the embedded
+ SQL interface are normal C programs with special
+ code inserted to perform database-related actions. This special
+ code always has the form:
+
+EXEC SQL ...;
+
+ These statements syntactically take the place of a C statement.
+ Depending on the particular statement, they can appear at the
+ global level or within a function.
+
+ Embedded
+ SQL statements follow the case-sensitivity rules of
+ normal SQL code, and not those of C. Also they allow nested
+ C-style comments as per the SQL standard. The C part of the
+ program, however, follows the C standard of not accepting nested comments.
+ Embedded SQL statements likewise use SQL rules, not
+ C rules, for parsing quoted strings and identifiers.
+ (See Section 4.1.2.1 and
+ Section 4.1.1 respectively. Note that
+ ECPG assumes that standard_conforming_strings
+ is on.)
+ Of course, the C part of the program follows C quoting rules.
+
+ The following sections explain all the embedded SQL statements.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-connect.html b/pgsql/doc/postgresql/html/ecpg-connect.html
new file mode 100644
index 0000000000000000000000000000000000000000..334b677175af6358ce34e5a438c6f55d1dd116f8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-connect.html
@@ -0,0 +1,247 @@
+
+36.2. Managing Database Connections
+ an SQL string literal containing one of the above forms
+
+ a reference to a character variable containing one of the above forms (see examples)
+
+ DEFAULT
+
+
+ The connection target DEFAULT initiates a connection
+ to the default database under the default user name. No separate
+ user name or connection name can be specified in that case.
+
+ If you specify the connection target directly (that is, not as a string
+ literal or variable reference), then the components of the target are
+ passed through normal SQL parsing; this means that, for example,
+ the hostname must look like one or more SQL
+ identifiers separated by dots, and those identifiers will be
+ case-folded unless double-quoted. Values of
+ any options must be SQL identifiers,
+ integers, or variable references. Of course, you can put nearly
+ anything into an SQL identifier by double-quoting it.
+ In practice, it is probably less error-prone to use a (single-quoted)
+ string literal or a variable reference than to write the connection
+ target directly.
+
+ There are also different ways to specify the user name:
+
+
+ username
+
+ username/password
+
+ username IDENTIFIED BY password
+
+ username USING password
+
+
+ As above, the parameters username and
+ password can be an SQL identifier, an
+ SQL string literal, or a reference to a character variable.
+
+ If the connection target includes any options,
+ those consist of
+ keyword=value
+ specifications separated by ampersands (&).
+ The allowed key words are the same ones recognized
+ by libpq (see
+ Section 34.1.2). Spaces are ignored before
+ any keyword or value,
+ though not within or after one. Note that there is no way to
+ write & within a value.
+
+ Notice that when specifying a socket connection
+ (with the unix: prefix), the host name must be
+ exactly localhost. To select a non-default
+ socket directory, write the directory's pathname as the value of
+ a host option in
+ the options part of the target.
+
+ The connection-name is used to handle
+ multiple connections in one program. It can be omitted if a
+ program uses only one connection. The most recently opened
+ connection becomes the current connection, which is used by default
+ when an SQL statement is to be executed (see later in this
+ chapter).
+
+ Here are some examples of CONNECT statements:
+
+EXEC SQL CONNECT TO mydb@sql.mydomain.com;
+
+EXEC SQL CONNECT TO tcp:postgresql://sql.mydomain.com/mydb AS myconnection USER john;
+
+EXEC SQL BEGIN DECLARE SECTION;
+const char *target = "mydb@sql.mydomain.com";
+const char *user = "john";
+const char *passwd = "secret";
+EXEC SQL END DECLARE SECTION;
+ ...
+EXEC SQL CONNECT TO :target USER :user USING :passwd;
+/* or EXEC SQL CONNECT TO :target USER :user/:passwd; */
+
+ The last example makes use of the feature referred to above as
+ character variable references. You will see in later sections how C
+ variables can be used in SQL statements when you prefix them with a
+ colon.
+
+ Be advised that the format of the connection target is not
+ specified in the SQL standard. So if you want to develop portable
+ applications, you might want to use something based on the last
+ example above to encapsulate the connection target string
+ somewhere.
+
+ If untrusted users have access to a database that has not adopted a
+ secure schema usage pattern,
+ begin each session by removing publicly-writable schemas
+ from search_path. For example,
+ add options=-c search_path=
+ to options, or
+ issue EXEC SQL SELECT pg_catalog.set_config('search_path', '',
+ false); after connecting. This consideration is not specific to
+ ECPG; it applies to every interface for executing arbitrary SQL commands.
+
+ SQL statements in embedded SQL programs are by default executed on
+ the current connection, that is, the most recently opened one. If
+ an application needs to manage multiple connections, then there are
+ three ways to handle this.
+
+ The first option is to explicitly choose a connection for each SQL
+ statement, for example:
+
+EXEC SQL AT connection-name SELECT ...;
+
+ This option is particularly suitable if the application needs to
+ use several connections in mixed order.
+
+ If your application uses multiple threads of execution, they cannot share a
+ connection concurrently. You must either explicitly control access to the connection
+ (using mutexes) or use a connection for each thread.
+
+ The second option is to execute a statement to switch the current
+ connection. That statement is:
+
+EXEC SQL SET CONNECTION connection-name;
+
+ This option is particularly convenient if many statements are to be
+ executed on the same connection.
+
+ Here is an example program managing multiple database connections:
+
+#include <stdio.h>
+
+EXEC SQL BEGIN DECLARE SECTION;
+ char dbname[1024];
+EXEC SQL END DECLARE SECTION;
+
+int
+main()
+{
+ EXEC SQL CONNECT TO testdb1 AS con1 USER testuser;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+ EXEC SQL CONNECT TO testdb2 AS con2 USER testuser;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+ EXEC SQL CONNECT TO testdb3 AS con3 USER testuser;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+
+ /* This query would be executed in the last opened database "testdb3". */
+ EXEC SQL SELECT current_database() INTO :dbname;
+ printf("current=%s (should be testdb3)\n", dbname);
+
+ /* Using "AT" to run a query in "testdb2" */
+ EXEC SQL AT con2 SELECT current_database() INTO :dbname;
+ printf("current=%s (should be testdb2)\n", dbname);
+
+ /* Switch the current connection to "testdb1". */
+ EXEC SQL SET CONNECTION con1;
+
+ EXEC SQL SELECT current_database() INTO :dbname;
+ printf("current=%s (should be testdb1)\n", dbname);
+
+ EXEC SQL DISCONNECT ALL;
+ return 0;
+}
+
+
+ This example would produce this output:
+
+current=testdb3 (should be testdb3)
+current=testdb2 (should be testdb2)
+current=testdb1 (should be testdb1)
+
+
+ The third option is to declare an SQL identifier linked to
+ the connection, for example:
+
+EXEC SQL AT connection-name DECLARE statement-name STATEMENT;
+EXEC SQL PREPARE statement-name FROM :dyn-string;
+
+ Once you link an SQL identifier to a connection, you execute dynamic SQL
+ without an AT clause. Note that this option behaves like preprocessor
+ directives, therefore the link is enabled only in the file.
+
+ Here is an example program using this option:
+
+#include <stdio.h>
+
+EXEC SQL BEGIN DECLARE SECTION;
+char dbname[128];
+char *dyn_sql = "SELECT current_database()";
+EXEC SQL END DECLARE SECTION;
+
+int main(){
+ EXEC SQL CONNECT TO postgres AS con1;
+ EXEC SQL CONNECT TO testdb AS con2;
+ EXEC SQL AT con1 DECLARE stmt STATEMENT;
+ EXEC SQL PREPARE stmt FROM :dyn_sql;
+ EXEC SQL EXECUTE stmt INTO :dbname;
+ printf("%s\n", dbname);
+
+ EXEC SQL DISCONNECT ALL;
+ return 0;
+}
+
+
+ This example would produce this output, even if the default connection is testdb:
+
+ To close a connection, use the following statement:
+
+EXEC SQL DISCONNECT [connection];
+
+ The connection can be specified
+ in the following ways:
+
+
+ connection-name
+
+ CURRENT
+
+ ALL
+
+
+ If no connection name is specified, the current connection is
+ closed.
+
+ It is good style that an application always explicitly disconnect
+ from every connection it opened.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-cpp.html b/pgsql/doc/postgresql/html/ecpg-cpp.html
new file mode 100644
index 0000000000000000000000000000000000000000..82b9c0fc9d8e36c609f2c2ff0cbc8689325b8ec5
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-cpp.html
@@ -0,0 +1,228 @@
+
+36.13. C++ Applications
+ ECPG has some limited support for C++ applications. This section
+ describes some caveats.
+
+ The ecpg preprocessor takes an input file
+ written in C (or something like C) and embedded SQL commands,
+ converts the embedded SQL commands into C language chunks, and
+ finally generates a .c file. The header file
+ declarations of the library functions used by the C language chunks
+ that ecpg generates are wrapped
+ in extern "C" { ... } blocks when used under
+ C++, so they should work seamlessly in C++.
+
+ In general, however, the ecpg preprocessor only
+ understands C; it does not handle the special syntax and reserved
+ words of the C++ language. So, some embedded SQL code written in
+ C++ application code that uses complicated features specific to C++
+ might fail to be preprocessed correctly or might not work as
+ expected.
+
+ A safe way to use the embedded SQL code in a C++ application is
+ hiding the ECPG calls in a C module, which the C++ application code
+ calls into to access the database, and linking that together with
+ the rest of the C++ code. See Section 36.13.2
+ about that.
+
+ The ecpg preprocessor understands the scope of
+ variables in C. In the C language, this is rather simple because
+ the scopes of variables is based on their code blocks. In C++,
+ however, the class member variables are referenced in a different
+ code block from the declared position, so
+ the ecpg preprocessor will not understand the
+ scope of the class member variables.
+
+ For example, in the following case, the ecpg
+ preprocessor cannot find any declaration for the
+ variable dbname in the test
+ method, so an error will occur.
+
+
+
+ This code will result in an error like this:
+
+ecpg test_cpp.pgc
+test_cpp.pgc:28: ERROR: variable "dbname" is not declared
+
+
+ To avoid this scope issue, the test method
+ could be modified to use a local variable as intermediate storage.
+ But this approach is only a poor workaround, because it uglifies
+ the code and reduces performance.
+
+
36.13.2. C++ Application Development with External C Module #
+ If you understand these technical limitations of
+ the ecpg preprocessor in C++, you might come to
+ the conclusion that linking C objects and C++ objects at the link
+ stage to enable C++ applications to use ECPG features could be
+ better than writing some embedded SQL commands in C++ code
+ directly. This section describes a way to separate some embedded
+ SQL commands from C++ application code with a simple example. In
+ this example, the application is implemented in C++, while C and
+ ECPG is used to connect to the PostgreSQL server.
+
+ Three kinds of files have to be created: a C file
+ (*.pgc), a header file, and a C++ file:
+
+
+ A header file with declarations of the functions in the C
+ module (test_mod.pgc). It is included by
+ test_cpp.cpp. This file has to have an
+ extern "C" block around the declarations,
+ because it will be linked from the C++ module.
+
+
+ To build the application, proceed as follows. Convert
+ test_mod.pgc into test_mod.c by
+ running ecpg, and generate
+ test_mod.o by compiling
+ test_mod.c with the C compiler:
+
+ Next, generate test_cpp.o by compiling
+ test_cpp.cpp with the C++ compiler:
+
+c++ -c test_cpp.cpp -o test_cpp.o
+
+
+ Finally, link these object files, test_cpp.o
+ and test_mod.o, into one executable, using the C++
+ compiler driver:
+
+c++ test_cpp.o test_mod.o -lecpg -o test_cpp
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-descriptors.html b/pgsql/doc/postgresql/html/ecpg-descriptors.html
new file mode 100644
index 0000000000000000000000000000000000000000..3100fbb5402c13f381ca202ecfb23da7394ba7eb
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-descriptors.html
@@ -0,0 +1,710 @@
+
+36.7. Using Descriptor Areas
+ An SQL descriptor area is a more sophisticated method for processing
+ the result of a SELECT, FETCH or
+ a DESCRIBE statement. An SQL descriptor area groups
+ the data of one row of data together with metadata items into one
+ data structure. The metadata is particularly useful when executing
+ dynamic SQL statements, where the nature of the result columns might
+ not be known ahead of time. PostgreSQL provides two ways to use
+ Descriptor Areas: the named SQL Descriptor Areas and the C-structure
+ SQLDAs.
+
+ A named SQL descriptor area consists of a header, which contains
+ information concerning the entire descriptor, and one or more item
+ descriptor areas, which basically each describe one column in the
+ result row.
+
+ Before you can use an SQL descriptor area, you need to allocate one:
+
+EXEC SQL ALLOCATE DESCRIPTOR identifier;
+
+ The identifier serves as the “variable name” of the
+ descriptor area.
+ When you don't need the descriptor anymore, you should deallocate
+ it:
+
+EXEC SQL DEALLOCATE DESCRIPTOR identifier;
+
+
+ To use a descriptor area, specify it as the storage target in an
+ INTO clause, instead of listing host variables:
+
+EXEC SQL FETCH NEXT FROM mycursor INTO SQL DESCRIPTOR mydesc;
+
+ If the result set is empty, the Descriptor Area will still contain
+ the metadata from the query, i.e., the field names.
+
+ For not yet executed prepared queries, the DESCRIBE
+ statement can be used to get the metadata of the result set:
+
+EXEC SQL BEGIN DECLARE SECTION;
+char *sql_stmt = "SELECT * FROM table1";
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL PREPARE stmt1 FROM :sql_stmt;
+EXEC SQL DESCRIBE stmt1 INTO SQL DESCRIPTOR mydesc;
+
+
+ Before PostgreSQL 9.0, the SQL keyword was optional,
+ so using DESCRIPTOR and SQL DESCRIPTOR
+ produced named SQL Descriptor Areas. Now it is mandatory, omitting
+ the SQL keyword produces SQLDA Descriptor Areas,
+ see Section 36.7.2.
+
+ In DESCRIBE and FETCH statements,
+ the INTO and USING keywords can be
+ used to similarly: they produce the result set and the metadata in a
+ Descriptor Area.
+
+ Now how do you get the data out of the descriptor area? You can
+ think of the descriptor area as a structure with named fields. To
+ retrieve the value of a field from the header and store it into a
+ host variable, use the following command:
+
+EXEC SQL GET DESCRIPTOR name :hostvar = field;
+
+ Currently, there is only one header field defined:
+ COUNT, which tells how many item
+ descriptor areas exist (that is, how many columns are contained in
+ the result). The host variable needs to be of an integer type. To
+ get a field from the item descriptor area, use the following
+ command:
+
+EXEC SQL GET DESCRIPTOR name VALUE num :hostvar = field;
+
+ num can be a literal integer or a host
+ variable containing an integer. Possible fields are:
+
+
+ When TYPE is 9,
+ DATETIME_INTERVAL_CODE will have a value of
+ 1 for DATE,
+ 2 for TIME,
+ 3 for TIMESTAMP,
+ 4 for TIME WITH TIME ZONE, or
+ 5 for TIMESTAMP WITH TIME ZONE.
+
+ In EXECUTE, DECLARE and OPEN
+ statements, the effect of the INTO and USING
+ keywords are different. A Descriptor Area can also be manually built to
+ provide the input parameters for a query or a cursor and
+ USING SQL DESCRIPTOR name
+ is the way to pass the input parameters into a parameterized query. The statement
+ to build a named SQL Descriptor Area is below:
+
+EXEC SQL SET DESCRIPTOR name VALUE numfield = :hostvar;
+
+
+ PostgreSQL supports retrieving more that one record in one FETCH
+ statement and storing the data in host variables in this case assumes that the
+ variable is an array. E.g.:
+
+EXEC SQL BEGIN DECLARE SECTION;
+int id[5];
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL FETCH 5 FROM mycursor INTO SQL DESCRIPTOR mydesc;
+
+EXEC SQL GET DESCRIPTOR mydesc VALUE 1 :id = DATA;
+
+ An SQLDA Descriptor Area is a C language structure which can be also used
+ to get the result set and the metadata of a query. One structure stores one
+ record from the result set.
+
+EXEC SQL include sqlda.h;
+sqlda_t *mysqlda;
+
+EXEC SQL FETCH 3 FROM mycursor INTO DESCRIPTOR mysqlda;
+
+ Note that the SQL keyword is omitted. The paragraphs about
+ the use cases of the INTO and USING
+ keywords in Section 36.7.1 also apply here with an addition.
+ In a DESCRIBE statement the DESCRIPTOR
+ keyword can be completely omitted if the INTO keyword is used:
+
+EXEC SQL DESCRIBE prepared_statement INTO mysqlda;
+
+
+ The general flow of a program that uses SQLDA is:
+
Prepare a query, and declare a cursor for it.
Declare an SQLDA for the result rows.
Declare an SQLDA for the input parameters, and initialize them (memory allocation, parameter settings).
Open a cursor with the input SQLDA.
Fetch rows from the cursor, and store them into an output SQLDA.
Read values from the output SQLDA into the host variables (with conversion if necessary).
Close the cursor.
Free the memory area allocated for the input SQLDA.
+ SQLDA uses three data structure
+ types: sqlda_t, sqlvar_t,
+ and struct sqlname.
+
Tip
+ PostgreSQL's SQLDA has a similar data structure to the one in
+ IBM DB2 Universal Database, so some technical information on
+ DB2's SQLDA could help understanding PostgreSQL's one better.
+
+ The structure type sqlda_t is the type of the
+ actual SQLDA. It holds one record. And two or
+ more sqlda_t structures can be connected in a
+ linked list with the pointer in
+ the desc_next field, thus
+ representing an ordered collection of rows. So, when two or
+ more rows are fetched, the application can read them by
+ following the desc_next pointer in
+ each sqlda_t node.
+
+ The definition of sqlda_t is:
+
+struct sqlda_struct
+{
+ char sqldaid[8];
+ long sqldabc;
+ short sqln;
+ short sqld;
+ struct sqlda_struct *desc_next;
+ struct sqlvar_struct sqlvar[1];
+};
+
+typedef struct sqlda_struct sqlda_t;
+
+ It contains the number of input parameters for a parameterized query in
+ case it's passed into OPEN, DECLARE or
+ EXECUTE statements using the USING
+ keyword. In case it's used as output of SELECT,
+ EXECUTE or FETCH statements,
+ its value is the same as sqld
+ statement
+
+ If the query returns more than one record, multiple linked
+ SQLDA structures are returned, and desc_next holds
+ a pointer to the next entry in the list.
+
+ Inside the loop, run another loop to retrieve each column data
+ (sqlvar_t structure) of the row.
+
+for (i = 0; i < cur_sqlda->sqld; i++)
+{
+ sqlvar_t v = cur_sqlda->sqlvar[i];
+ char *sqldata = v.sqldata;
+ short sqllen = v.sqllen;
+ ...
+}
+
+
+ To get a column value, check the sqltype value,
+ a member of the sqlvar_t structure. Then, switch
+ to an appropriate way, depending on the column type, to copy
+ data from the sqlvar field to a host variable.
+
36.7.2.3. Passing Query Parameters Using an SQLDA #
+ The general steps to use an SQLDA to pass input
+ parameters to a prepared query are:
+
Create a prepared query (prepared statement)
Declare an sqlda_t structure as an input SQLDA.
Allocate memory area (as sqlda_t structure) for the input SQLDA.
Set (copy) input values in the allocated memory.
Open a cursor with specifying the input SQLDA.
+ Here is an example.
+
+ First, create a prepared statement.
+
+EXEC SQL BEGIN DECLARE SECTION;
+char query[1024] = "SELECT d.oid, * FROM pg_database d, pg_stat_database s WHERE d.oid = s.datid AND (d.datname = ? OR d.oid = ?)";
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL PREPARE stmt1 FROM :query;
+
+
+ Next, allocate memory for an SQLDA, and set the number of input
+ parameters in sqln, a member variable of
+ the sqlda_t structure. When two or more input
+ parameters are required for the prepared query, the application
+ has to allocate additional memory space which is calculated by
+ (nr. of params - 1) * sizeof(sqlvar_t). The example shown here
+ allocates memory space for two input parameters.
+
+ After memory allocation, store the parameter values into the
+ sqlvar[] array. (This is same array used for
+ retrieving column values when the SQLDA is receiving a result
+ set.) In this example, the input parameters
+ are "postgres", having a string type,
+ and 1, having an integer type.
+
+ Here is an example program, which describes how to fetch access
+ statistics of the databases, specified by the input parameters,
+ from the system catalogs.
+
+ This application joins two system tables, pg_database and
+ pg_stat_database on the database OID, and also fetches and shows
+ the database statistics which are retrieved by two input
+ parameters (a database postgres, and OID 1).
+
+ First, declare an SQLDA for input and an SQLDA for output.
+
+EXEC SQL include sqlda.h;
+
+sqlda_t *sqlda1; /* an output descriptor */
+sqlda_t *sqlda2; /* an input descriptor */
+
+
+ Next, connect to the database, prepare a statement, and declare a
+ cursor for the prepared statement.
+
+int
+main(void)
+{
+ EXEC SQL BEGIN DECLARE SECTION;
+ char query[1024] = "SELECT d.oid,* FROM pg_database d, pg_stat_database s WHERE d.oid=s.datid AND ( d.datname=? OR d.oid=? )";
+ EXEC SQL END DECLARE SECTION;
+
+ EXEC SQL CONNECT TO testdb AS con1 USER testuser;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+
+ EXEC SQL PREPARE stmt1 FROM :query;
+ EXEC SQL DECLARE cur1 CURSOR FOR stmt1;
+
+
+ Next, put some values in the input SQLDA for the input
+ parameters. Allocate memory for the input SQLDA, and set the
+ number of input parameters to sqln. Store
+ type, value, and value length into sqltype,
+ sqldata, and sqllen in the
+ sqlvar structure.
+
+
+ After setting up the input SQLDA, open a cursor with the input
+ SQLDA.
+
+
+ /* Open a cursor with input parameters. */
+ EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2;
+
+
+ Fetch rows into the output SQLDA from the opened cursor.
+ (Generally, you have to call FETCH repeatedly
+ in the loop, to fetch all rows in the result set.)
+
+ while (1)
+ {
+ sqlda_t *cur_sqlda;
+
+ /* Assign descriptor to the cursor */
+ EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1;
+
+
+ Next, retrieve the fetched records from the SQLDA, by following
+ the linked list of the sqlda_t structure.
+
+ Read each columns in the first record. The number of columns is
+ stored in sqld, the actual data of the first
+ column is stored in sqlvar[0], both members of
+ the sqlda_t structure.
+
+
+ /* Print every column in a row. */
+ for (i = 0; i < sqlda1->sqld; i++)
+ {
+ sqlvar_t v = sqlda1->sqlvar[i];
+ char *sqldata = v.sqldata;
+ short sqllen = v.sqllen;
+
+ strncpy(name_buf, v.sqlname.data, v.sqlname.length);
+ name_buf[v.sqlname.length] = '\0';
+
+
+ Now, the column data is stored in the variable v.
+ Copy every datum into host variables, looking
+ at v.sqltype for the type of the column.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-develop.html b/pgsql/doc/postgresql/html/ecpg-develop.html
new file mode 100644
index 0000000000000000000000000000000000000000..ae31261b45d5f950d3b21acd2fbd885861ea46c9
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-develop.html
@@ -0,0 +1,124 @@
+
+36.17. Internals
+ This section explains how ECPG works
+ internally. This information can occasionally be useful to help
+ users understand how to use ECPG.
+
+ The first four lines written by ecpg to the
+ output are fixed lines. Two are comments and two are include
+ lines necessary to interface to the library. Then the
+ preprocessor reads through the file and writes output. Normally
+ it just echoes everything to the output.
+
+ When it sees an EXEC SQL statement, it
+ intervenes and changes it. The command starts with EXEC
+ SQL and ends with ;. Everything in
+ between is treated as an SQL statement and
+ parsed for variable substitution.
+
+ Variable substitution occurs when a symbol starts with a colon
+ (:). The variable with that name is looked up
+ among the variables that were previously declared within a
+ EXEC SQL DECLARE section.
+
+ The most important function in the library is
+ ECPGdo, which takes care of executing most
+ commands. It takes a variable number of arguments. This can easily
+ add up to 50 or so arguments, and we hope this will not be a
+ problem on any platform.
+
+ This is the SQL command that is to be issued.
+ It is modified by the input variables, i.e., the variables that
+ where not known at compile time but are to be entered in the
+ command. Where the variables should go the string contains
+ ?.
+
+ An enum telling that there are no more variables.
+
+
+ For every variable that is part of the SQL
+ command, the function gets ten arguments:
+
+
+ The type as a special symbol.
+
+ A pointer to the value or a pointer to the pointer.
+
+ The size of the variable if it is a char or varchar.
+
+ The number of elements in the array (for array fetches).
+
+ The offset to the next element in the array (for array fetches).
+
+ The type of the indicator variable as a special symbol.
+
+ A pointer to the indicator variable.
+
+ 0
+
+ The number of elements in the indicator array (for array fetches).
+
+ The offset to the next element in the indicator array (for
+ array fetches).
+
+
+ Note that not all SQL commands are treated in this way. For
+ instance, an open cursor statement like:
+
+EXEC SQL OPEN cursor;
+
+ is not copied to the output. Instead, the cursor's
+ DECLARE command is used at the position of the OPEN command
+ because it indeed opens the cursor.
+
+ Here is a complete example describing the output of the
+ preprocessor of a file foo.pgc (details might
+ change with each particular version of the preprocessor):
+
+EXEC SQL BEGIN DECLARE SECTION;
+int index;
+int result;
+EXEC SQL END DECLARE SECTION;
+...
+EXEC SQL SELECT res INTO :result FROM mytable WHERE index = :index;
+
+ is translated into:
+
+/* Processed by ecpg (2.6.0) */
+/* These two include files are added by the preprocessor */
+#include <ecpgtype.h>;
+#include <ecpglib.h>;
+
+/* exec sql begin declare section */
+
+#line 1 "foo.pgc"
+
+ int index;
+ int result;
+/* exec sql end declare section */
+...
+ECPGdo(__LINE__, NULL, "SELECT res FROM mytable WHERE index = ? ",
+ ECPGt_int,&(index),1L,1L,sizeof(int),
+ ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT,
+ ECPGt_int,&(result),1L,1L,sizeof(int),
+ ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);
+#line 147 "foo.pgc"
+
+
+ (The indentation here is added for readability and not
+ something the preprocessor does.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-dynamic.html b/pgsql/doc/postgresql/html/ecpg-dynamic.html
new file mode 100644
index 0000000000000000000000000000000000000000..14b355c701304f90845869bac960010e293041fb
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-dynamic.html
@@ -0,0 +1,103 @@
+
+36.5. Dynamic SQL
+ In many cases, the particular SQL statements that an application
+ has to execute are known at the time the application is written.
+ In some cases, however, the SQL statements are composed at run time
+ or provided by an external source. In these cases you cannot embed
+ the SQL statements directly into the C source code, but there is a
+ facility that allows you to call arbitrary SQL statements that you
+ provide in a string variable.
+
36.5.1. Executing Statements without a Result Set #
+ The simplest way to execute an arbitrary SQL statement is to use
+ the command EXECUTE IMMEDIATE. For example:
+
+ EXECUTE IMMEDIATE can be used for SQL
+ statements that do not return a result set (e.g.,
+ DDL, INSERT, UPDATE,
+ DELETE). You cannot execute statements that
+ retrieve data (e.g., SELECT) this way. The
+ next section describes how to do that.
+
36.5.2. Executing a Statement with Input Parameters #
+ A more powerful way to execute arbitrary SQL statements is to
+ prepare them once and execute the prepared statement as often as
+ you like. It is also possible to prepare a generalized version of
+ a statement and then execute specific versions of it by
+ substituting parameters. When preparing the statement, write
+ question marks where you want to substitute parameters later. For
+ example:
+
+EXEC SQL BEGIN DECLARE SECTION;
+const char *stmt = "INSERT INTO test1 VALUES(?, ?);";
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL PREPARE mystmt FROM :stmt;
+ ...
+EXEC SQL EXECUTE mystmt USING 42, 'foobar';
+
+
+ When you don't need the prepared statement anymore, you should
+ deallocate it:
+
+ To execute an SQL statement with a single result row,
+ EXECUTE can be used. To save the result, add
+ an INTO clause.
+
+EXEC SQL BEGIN DECLARE SECTION;
+const char *stmt = "SELECT a, b, c FROM test1 WHERE a > ?";
+int v1, v2;
+VARCHAR v3[50];
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL PREPARE mystmt FROM :stmt;
+ ...
+EXEC SQL EXECUTE mystmt INTO :v1, :v2, :v3 USING 37;
+
+
+ An EXECUTE command can have an
+ INTO clause, a USING clause,
+ both, or neither.
+
+ If a query is expected to return more than one result row, a
+ cursor should be used, as in the following example.
+ (See Section 36.3.2 for more details about the
+ cursor.)
+
+EXEC SQL BEGIN DECLARE SECTION;
+char dbaname[128];
+char datname[128];
+char *stmt = "SELECT u.usename as dbaname, d.datname "
+ " FROM pg_database d, pg_user u "
+ " WHERE d.datdba = u.usesysid";
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL CONNECT TO testdb AS con1 USER testuser;
+EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+
+EXEC SQL PREPARE stmt1 FROM :stmt;
+
+EXEC SQL DECLARE cursor1 CURSOR FOR stmt1;
+EXEC SQL OPEN cursor1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ EXEC SQL FETCH cursor1 INTO :dbaname,:datname;
+ printf("dbaname=%s, datname=%s\n", dbaname, datname);
+}
+
+EXEC SQL CLOSE cursor1;
+
+EXEC SQL COMMIT;
+EXEC SQL DISCONNECT ALL;
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-errors.html b/pgsql/doc/postgresql/html/ecpg-errors.html
new file mode 100644
index 0000000000000000000000000000000000000000..bc00efb32a480c9f09efd47f43af548a0644e5cd
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-errors.html
@@ -0,0 +1,441 @@
+
+36.8. Error Handling
+ This section describes how you can handle exceptional conditions
+ and warnings in an embedded SQL program. There are two
+ nonexclusive facilities for this.
+
+
+ Callbacks can be configured to handle warning and error
+ conditions using the WHENEVER command.
+
+ Detailed information about the error or warning can be obtained
+ from the sqlca variable.
+
+ The specified action is called whenever an SQL statement
+ retrieves or affects zero rows. (This condition is not an
+ error, but you might be interested in handling it specially.)
+
+ Execute the C statement continue. This should
+ only be used in loops statements. if executed, will cause the flow
+ of control to return to the top of the loop.
+
+ Call the specified C functions with the specified arguments. (This
+ use is different from the meaning of CALL
+ and DO in the normal PostgreSQL grammar.)
+
+
+ The SQL standard only provides for the actions
+ CONTINUE and GOTO (and
+ GO TO).
+
+ Here is an example that you might want to use in a simple program.
+ It prints a simple message when a warning occurs and aborts the
+ program when an error happens:
+
+ The statement EXEC SQL WHENEVER is a directive
+ of the SQL preprocessor, not a C statement. The error or warning
+ actions that it sets apply to all embedded SQL statements that
+ appear below the point where the handler is set, unless a
+ different action was set for the same condition between the first
+ EXEC SQL WHENEVER and the SQL statement causing
+ the condition, regardless of the flow of control in the C program.
+ So neither of the two following C program excerpts will have the
+ desired effect:
+
+ For more powerful error handling, the embedded SQL interface
+ provides a global variable with the name sqlca
+ (SQL communication area)
+ that has the following structure:
+
+struct
+{
+ char sqlcaid[8];
+ long sqlabc;
+ long sqlcode;
+ struct
+ {
+ int sqlerrml;
+ char sqlerrmc[SQLERRMC_LEN];
+ } sqlerrm;
+ char sqlerrp[8];
+ long sqlerrd[6];
+ char sqlwarn[8];
+ char sqlstate[5];
+} sqlca;
+
+ (In a multithreaded program, every thread automatically gets its
+ own copy of sqlca. This works similarly to the
+ handling of the standard C global variable
+ errno.)
+
+ sqlca covers both warnings and errors. If
+ multiple warnings or errors occur during the execution of a
+ statement, then sqlca will only contain
+ information about the last one.
+
+ If no error occurred in the last SQL statement,
+ sqlca.sqlcode will be 0 and
+ sqlca.sqlstate will be
+ "00000". If a warning or error occurred, then
+ sqlca.sqlcode will be negative and
+ sqlca.sqlstate will be different from
+ "00000". A positive
+ sqlca.sqlcode indicates a harmless condition,
+ such as that the last query returned zero rows.
+ sqlcode and sqlstate are two
+ different error code schemes; details appear below.
+
+ If the last SQL statement was successful, then
+ sqlca.sqlerrd[1] contains the OID of the
+ processed row, if applicable, and
+ sqlca.sqlerrd[2] contains the number of
+ processed or returned rows, if applicable to the command.
+
+ In case of an error or warning,
+ sqlca.sqlerrm.sqlerrmc will contain a string
+ that describes the error. The field
+ sqlca.sqlerrm.sqlerrml contains the length of
+ the error message that is stored in
+ sqlca.sqlerrm.sqlerrmc (the result of
+ strlen(), not really interesting for a C
+ programmer). Note that some messages are too long to fit in the
+ fixed-size sqlerrmc array; they will be truncated.
+
+ In case of a warning, sqlca.sqlwarn[2] is set
+ to W. (In all other cases, it is set to
+ something different from W.) If
+ sqlca.sqlwarn[1] is set to
+ W, then a value was truncated when it was
+ stored in a host variable. sqlca.sqlwarn[0] is
+ set to W if any of the other elements are set
+ to indicate a warning.
+
+ The fields sqlcaid,
+ sqlabc,
+ sqlerrp, and the remaining elements of
+ sqlerrd and
+ sqlwarn currently contain no useful
+ information.
+
+ The structure sqlca is not defined in the SQL
+ standard, but is implemented in several other SQL database
+ systems. The definitions are similar at the core, but if you want
+ to write portable applications, then you should investigate the
+ different implementations carefully.
+
+ Here is one example that combines the use of WHENEVER
+ and sqlca, printing out the contents
+ of sqlca when an error occurs. This is perhaps
+ useful for debugging or prototyping applications, before
+ installing a more “user-friendly” error handler.
+
+
+ The fields sqlca.sqlstate and
+ sqlca.sqlcode are two different schemes that
+ provide error codes. Both are derived from the SQL standard, but
+ SQLCODE has been marked deprecated in the SQL-92
+ edition of the standard and has been dropped in later editions.
+ Therefore, new applications are strongly encouraged to use
+ SQLSTATE.
+
+ SQLSTATE is a five-character array. The five
+ characters contain digits or upper-case letters that represent
+ codes of various error and warning conditions.
+ SQLSTATE has a hierarchical scheme: the first
+ two characters indicate the general class of the condition, the
+ last three characters indicate a subclass of the general
+ condition. A successful state is indicated by the code
+ 00000. The SQLSTATE codes are for
+ the most part defined in the SQL standard. The
+ PostgreSQL server natively supports
+ SQLSTATE error codes; therefore a high degree
+ of consistency can be achieved by using this error code scheme
+ throughout all applications. For further information see
+ Appendix A.
+
+ SQLCODE, the deprecated error code scheme, is a
+ simple integer. A value of 0 indicates success, a positive value
+ indicates success with additional information, a negative value
+ indicates an error. The SQL standard only defines the positive
+ value +100, which indicates that the last command returned or
+ affected zero rows, and no specific negative values. Therefore,
+ this scheme can only achieve poor portability and does not have a
+ hierarchical code assignment. Historically, the embedded SQL
+ processor for PostgreSQL has assigned
+ some specific SQLCODE values for its use, which
+ are listed below with their numeric value and their symbolic name.
+ Remember that these are not portable to other SQL implementations.
+ To simplify the porting of applications to the
+ SQLSTATE scheme, the corresponding
+ SQLSTATE is also listed. There is, however, no
+ one-to-one or one-to-many mapping between the two schemes (indeed
+ it is many-to-many), so you should consult the global
+ SQLSTATE listing in Appendix A
+ in each case.
+
+ This is a harmless condition indicating that the last command
+ retrieved or processed zero rows, or that you are at the end of
+ the cursor. (SQLSTATE 02000)
+
+ When processing a cursor in a loop, you could use this code as
+ a way to detect when to abort the loop, like this:
+
+ Indicates the preprocessor has generated something that the
+ library does not know about. Perhaps you are running
+ incompatible versions of the preprocessor and the
+ library. (SQLSTATE YE002)
+
+ This means a query has returned multiple rows but the statement
+ was only prepared to store one result row (for example, because
+ the specified variables are not arrays). (SQLSTATE 21000)
+
+ The host variable is of type int and the datum in
+ the database is of a different type and contains a value that
+ cannot be interpreted as an int. The library uses
+ strtol() for this conversion. (SQLSTATE
+ 42804)
+
+ The host variable is of type unsigned int and the
+ datum in the database is of a different type and contains a
+ value that cannot be interpreted as an unsigned
+ int. The library uses strtoul()
+ for this conversion. (SQLSTATE 42804)
+
+ The host variable is of type float and the datum
+ in the database is of another type and contains a value that
+ cannot be interpreted as a float. The library
+ uses strtod() for this conversion.
+ (SQLSTATE 42804)
+
+ The host variable is of type numeric and the datum
+ in the database is of another type and contains a value that
+ cannot be interpreted as a numeric value.
+ (SQLSTATE 42804)
+
+ The host variable is of type interval and the datum
+ in the database is of another type and contains a value that
+ cannot be interpreted as an interval value.
+ (SQLSTATE 42804)
+
+ The host variable is of type date and the datum in
+ the database is of another type and contains a value that
+ cannot be interpreted as a date value.
+ (SQLSTATE 42804)
+
+ The host variable is of type timestamp and the
+ datum in the database is of another type and contains a value
+ that cannot be interpreted as a timestamp value.
+ (SQLSTATE 42804)
+
+ The statement sent to the PostgreSQL
+ server was empty. (This cannot normally happen in an embedded
+ SQL program, so it might point to an internal error.) (SQLSTATE
+ YE002)
+
+ An existing cursor name was specified. (SQLSTATE 42P03)
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-informix-compat.html b/pgsql/doc/postgresql/html/ecpg-informix-compat.html
new file mode 100644
index 0000000000000000000000000000000000000000..fa50a9c9f44ae2156cfe123224201a907ca23518
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-informix-compat.html
@@ -0,0 +1,892 @@
+
+36.15. Informix Compatibility Mode
+ ecpg can be run in a so-called Informix compatibility mode. If
+ this mode is active, it tries to behave as if it were the Informix
+ precompiler for Informix E/SQL. Generally spoken this will allow you to use
+ the dollar sign instead of the EXEC SQL primitive to introduce
+ embedded SQL commands:
+
+$int j = 3;
+$CONNECT TO :dbname;
+$CREATE TABLE test(i INT PRIMARY KEY, j INT);
+$INSERT INTO test(i, j) VALUES (7, :j);
+$COMMIT;
+
+
Note
+ There must not be any white space between the $
+ and a following preprocessor directive, that is,
+ include, define, ifdef,
+ etc. Otherwise, the preprocessor will parse the token as a host
+ variable.
+
+ There are two compatibility modes: INFORMIX, INFORMIX_SE
+
+ When linking programs that use this compatibility mode, remember to link
+ against libcompat that is shipped with ECPG.
+
+ Besides the previously explained syntactic sugar, the Informix compatibility
+ mode ports some functions for input, output and transformation of data as
+ well as embedded SQL statements known from E/SQL to ECPG.
+
+ Informix compatibility mode is closely connected to the pgtypeslib library
+ of ECPG. pgtypeslib maps SQL data types to data types within the C host
+ program and most of the additional functions of the Informix compatibility
+ mode allow you to operate on those C host program types. Note however that
+ the extent of the compatibility is limited. It does not try to copy Informix
+ behavior; it allows you to do more or less the same operations and gives
+ you functions that have the same name and the same basic behavior but it is
+ no drop-in replacement if you are using Informix at the moment. Moreover,
+ some of the data types are different. For example,
+ PostgreSQL's datetime and interval types do not
+ know about ranges like for example YEAR TO MINUTE so you won't
+ find support in ECPG for that either.
+
+ The Informix-special "string" pseudo-type for storing right-trimmed character string data is now
+ supported in Informix-mode without using typedef. In fact, in Informix-mode,
+ ECPG refuses to process source files that contain typedef sometype string;
+
+EXEC SQL BEGIN DECLARE SECTION;
+string userid; /* this variable will contain trimmed data */
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL FETCH MYCUR INTO :userid;
+
+ Due to differences in how ECPG works compared to Informix's ESQL/C (namely, which steps
+ are purely grammar transformations and which steps rely on the underlying run-time library)
+ there is no FREE cursor_name statement in ECPG. This is because in ECPG,
+ DECLARE CURSOR doesn't translate to a function call into
+ the run-time library that uses to the cursor name. This means that there's no run-time
+ bookkeeping of SQL cursors in the ECPG run-time library, only in the PostgreSQL server.
+
+ Pointer to the NULL indicator. If returned by DESCRIBE or FETCH then it's always a valid pointer.
+ If used as input for EXECUTE ... USING sqlda; then NULL-pointer value means
+ that the value for this field is non-NULL. Otherwise a valid pointer and sqlitype
+ has to be properly set. Example:
+
+if (*(int2 *)sqldata->sqlvar[i].sqlind != 0)
+ printf("value is NULL\n");
+
+ Type of the NULL indicator data. It's always SQLSMINT when returning data from the server.
+ When the SQLDA is used for a parameterized query, the data is treated
+ according to the set type.
+
+ It equals to sqldata if sqllen is larger than 32kB.
+
+
+ Example:
+
+EXEC SQL INCLUDE sqlda.h;
+
+ sqlda_t *sqlda; /* This doesn't need to be under embedded DECLARE SECTION */
+
+ EXEC SQL BEGIN DECLARE SECTION;
+ char *prep_stmt = "select * from table1";
+ int i;
+ EXEC SQL END DECLARE SECTION;
+
+ ...
+
+ EXEC SQL PREPARE mystmt FROM :prep_stmt;
+
+ EXEC SQL DESCRIBE mystmt INTO sqlda;
+
+ printf("# of fields: %d\n", sqlda->sqld);
+ for (i = 0; i < sqlda->sqld; i++)
+ printf("field %d: \"%s\"\n", sqlda->sqlvar[i]->sqlname);
+
+ EXEC SQL DECLARE mycursor CURSOR FOR mystmt;
+ EXEC SQL OPEN mycursor;
+ EXEC SQL WHENEVER NOT FOUND GOTO out;
+
+ while (1)
+ {
+ EXEC SQL FETCH mycursor USING sqlda;
+ }
+
+ EXEC SQL CLOSE mycursor;
+
+ free(sqlda); /* The main structure is all to be free(),
+ * sqlda and sqlda->sqlvar is in one allocated area */
+
+ For more information, see the sqlda.h header and the
+ src/interfaces/ecpg/test/compat_informix/sqlda.pgc regression test.
+
+ The function receives a pointer to the first operand of type decimal
+ (arg1), a pointer to the second operand of type decimal
+ (arg2) and a pointer to a value of type decimal that will
+ contain the sum (sum). On success, the function returns 0.
+ ECPG_INFORMIX_NUM_OVERFLOW is returned in case of overflow and
+ ECPG_INFORMIX_NUM_UNDERFLOW in case of underflow. -1 is returned for
+ other failures and errno is set to the respective errno number of the
+ pgtypeslib.
+
+ The function receives a pointer to the first decimal value
+ (arg1), a pointer to the second decimal value
+ (arg2) and returns an integer value that indicates which is
+ the bigger value.
+
+ 1, if the value that arg1 points to is bigger than the
+ value that var2 points to
+
+ -1, if the value that arg1 points to is smaller than the
+ value that arg2 points to
+ 0, if the value that arg1 points to and the value that
+ arg2 points to are equal
+
+ The function receives a pointer to the decimal value that should be
+ copied as the first argument (src) and a pointer to the
+ target structure of type decimal (target) as the second
+ argument.
+
+ Convert a value from its ASCII representation into a decimal type.
+
+int deccvasc(char *cp, int len, decimal *np);
+
+ The function receives a pointer to string that contains the string
+ representation of the number to be converted (cp) as well
+ as its length len. np is a pointer to the
+ decimal value that saves the result of the operation.
+
+ Valid formats are for example:
+ -2,
+ .794,
+ +3.44,
+ 592.49E07 or
+ -32.84e-4.
+
+ The function returns 0 on success. If overflow or underflow occurred,
+ ECPG_INFORMIX_NUM_OVERFLOW or
+ ECPG_INFORMIX_NUM_UNDERFLOW is returned. If the ASCII
+ representation could not be parsed,
+ ECPG_INFORMIX_BAD_NUMERIC is returned or
+ ECPG_INFORMIX_BAD_EXPONENT if this problem occurred while
+ parsing the exponent.
+
+ Convert a value of type double to a value of type decimal.
+
+int deccvdbl(double dbl, decimal *np);
+
+ The function receives the variable of type double that should be
+ converted as its first argument (dbl). As the second
+ argument (np), the function receives a pointer to the
+ decimal variable that should hold the result of the operation.
+
+ The function returns 0 on success and a negative value if the
+ conversion failed.
+
+ Convert a value of type int to a value of type decimal.
+
+int deccvint(int in, decimal *np);
+
+ The function receives the variable of type int that should be
+ converted as its first argument (in). As the second
+ argument (np), the function receives a pointer to the
+ decimal variable that should hold the result of the operation.
+
+ The function returns 0 on success and a negative value if the
+ conversion failed.
+
+ Convert a value of type long to a value of type decimal.
+
+int deccvlong(long lng, decimal *np);
+
+ The function receives the variable of type long that should be
+ converted as its first argument (lng). As the second
+ argument (np), the function receives a pointer to the
+ decimal variable that should hold the result of the operation.
+
+ The function returns 0 on success and a negative value if the
+ conversion failed.
+
+ The function receives pointers to the variables that are the first
+ (n1) and the second (n2) operands and
+ calculates n1/n2. result is a
+ pointer to the variable that should hold the result of the operation.
+
+ On success, 0 is returned and a negative value if the division fails.
+ If overflow or underflow occurred, the function returns
+ ECPG_INFORMIX_NUM_OVERFLOW or
+ ECPG_INFORMIX_NUM_UNDERFLOW respectively. If an attempt to
+ divide by zero is observed, the function returns
+ ECPG_INFORMIX_DIVIDE_ZERO.
+
+ The function receives pointers to the variables that are the first
+ (n1) and the second (n2) operands and
+ calculates n1*n2. result is a
+ pointer to the variable that should hold the result of the operation.
+
+ On success, 0 is returned and a negative value if the multiplication
+ fails. If overflow or underflow occurred, the function returns
+ ECPG_INFORMIX_NUM_OVERFLOW or
+ ECPG_INFORMIX_NUM_UNDERFLOW respectively.
+
+ The function receives pointers to the variables that are the first
+ (n1) and the second (n2) operands and
+ calculates n1-n2. result is a
+ pointer to the variable that should hold the result of the operation.
+
+ On success, 0 is returned and a negative value if the subtraction
+ fails. If overflow or underflow occurred, the function returns
+ ECPG_INFORMIX_NUM_OVERFLOW or
+ ECPG_INFORMIX_NUM_UNDERFLOW respectively.
+
+ Convert a variable of type decimal to its ASCII representation in a C
+ char* string.
+
+int dectoasc(decimal *np, char *cp, int len, int right)
+
+ The function receives a pointer to a variable of type decimal
+ (np) that it converts to its textual representation.
+ cp is the buffer that should hold the result of the
+ operation. The parameter right specifies, how many digits
+ right of the decimal point should be included in the output. The result
+ will be rounded to this number of decimal digits. Setting
+ right to -1 indicates that all available decimal digits
+ should be included in the output. If the length of the output buffer,
+ which is indicated by len is not sufficient to hold the
+ textual representation including the trailing zero byte, only a
+ single * character is stored in the result and -1 is
+ returned.
+
+ The function returns either -1 if the buffer cp was too
+ small or ECPG_INFORMIX_OUT_OF_MEMORY if memory was
+ exhausted.
+
+ Convert a variable of type decimal to a double.
+
+int dectodbl(decimal *np, double *dblp);
+
+ The function receives a pointer to the decimal value to convert
+ (np) and a pointer to the double variable that
+ should hold the result of the operation (dblp).
+
+ On success, 0 is returned and a negative value if the conversion
+ failed.
+
+ Convert a variable of type decimal to an integer.
+
+int dectoint(decimal *np, int *ip);
+
+ The function receives a pointer to the decimal value to convert
+ (np) and a pointer to the integer variable that
+ should hold the result of the operation (ip).
+
+ On success, 0 is returned and a negative value if the conversion
+ failed. If an overflow occurred, ECPG_INFORMIX_NUM_OVERFLOW
+ is returned.
+
+ Note that the ECPG implementation differs from the Informix
+ implementation. Informix limits an integer to the range from -32767 to
+ 32767, while the limits in the ECPG implementation depend on the
+ architecture (INT_MIN .. INT_MAX).
+
+ Convert a variable of type decimal to a long integer.
+
+int dectolong(decimal *np, long *lngp);
+
+ The function receives a pointer to the decimal value to convert
+ (np) and a pointer to the long variable that
+ should hold the result of the operation (lngp).
+
+ On success, 0 is returned and a negative value if the conversion
+ failed. If an overflow occurred, ECPG_INFORMIX_NUM_OVERFLOW
+ is returned.
+
+ Note that the ECPG implementation differs from the Informix
+ implementation. Informix limits a long integer to the range from
+ -2,147,483,647 to 2,147,483,647, while the limits in the ECPG
+ implementation depend on the architecture (-LONG_MAX ..
+ LONG_MAX).
+
+ The function receives two arguments, the first one is the date to
+ convert (d) and the second one is a pointer to the target
+ string. The output format is always yyyy-mm-dd, so you need
+ to allocate at least 11 bytes (including the zero-byte terminator) for the
+ string.
+
+ The function returns 0 on success and a negative value in case of
+ error.
+
+ Note that ECPG's implementation differs from the Informix
+ implementation. In Informix the format can be influenced by setting
+ environment variables. In ECPG however, you cannot change the output
+ format.
+
+ The function receives the textual representation of the date to convert
+ (str) and a pointer to a variable of type date
+ (d). This function does not allow you to specify a format
+ mask. It uses the default format mask of Informix which is
+ mm/dd/yyyy. Internally, this function is implemented by
+ means of rdefmtdate. Therefore, rstrdate is
+ not faster and if you have the choice you should opt for
+ rdefmtdate which allows you to specify the format mask
+ explicitly.
+
+ The function returns the same values as rdefmtdate.
+
+ Extract the values for the day, the month and the year from a variable
+ of type date.
+
+int rjulmdy(date d, short mdy[3]);
+
+ The function receives the date d and a pointer to an array
+ of 3 short integer values mdy. The variable name indicates
+ the sequential order: mdy[0] will be set to contain the
+ number of the month, mdy[1] will be set to the value of the
+ day and mdy[2] will contain the year.
+
+ Use a format mask to convert a character string to a value of type
+ date.
+
+int rdefmtdate(date *d, char *fmt, char *str);
+
+ The function receives a pointer to the date value that should hold the
+ result of the operation (d), the format mask to use for
+ parsing the date (fmt) and the C char* string containing
+ the textual representation of the date (str). The textual
+ representation is expected to match the format mask. However you do not
+ need to have a 1:1 mapping of the string to the format mask. The
+ function only analyzes the sequential order and looks for the literals
+ yy or yyyy that indicate the
+ position of the year, mm to indicate the position of
+ the month and dd to indicate the position of the
+ day.
+
+ The function returns the following values:
+
+ 0 - The function terminated successfully.
+
+ ECPG_INFORMIX_ENOSHORTDATE - The date does not contain
+ delimiters between day, month and year. In this case the input
+ string must be exactly 6 or 8 bytes long but isn't.
+
+ ECPG_INFORMIX_ENOTDMY - The format string did not
+ correctly indicate the sequential order of year, month and day.
+
+ ECPG_INFORMIX_BAD_DAY - The input string does not
+ contain a valid day.
+
+ ECPG_INFORMIX_BAD_MONTH - The input string does not
+ contain a valid month.
+
+ ECPG_INFORMIX_BAD_YEAR - The input string does not
+ contain a valid year.
+
+
+ Internally this function is implemented to use the PGTYPESdate_defmt_asc function. See the reference there for a
+ table of example input.
+
+ Convert a variable of type date to its textual representation using a
+ format mask.
+
+int rfmtdate(date d, char *fmt, char *str);
+
+ The function receives the date to convert (d), the format
+ mask (fmt) and the string that will hold the textual
+ representation of the date (str).
+
+ On success, 0 is returned and a negative value if an error occurred.
+
+ Internally this function uses the PGTYPESdate_fmt_asc
+ function, see the reference there for examples.
+
+ Create a date value from an array of 3 short integers that specify the
+ day, the month and the year of the date.
+
+int rmdyjul(short mdy[3], date *d);
+
+ The function receives the array of the 3 short integers
+ (mdy) and a pointer to a variable of type date that should
+ hold the result of the operation.
+
+ Currently the function returns always 0.
+
+ Internally the function is implemented to use the function PGTYPESdate_mdyjul.
+
+ The function receives the string to parse (inbuf), the
+ format mask to use (fmtstr) and a pointer to the timestamp
+ variable that should hold the result of the operation
+ (dtvalue).
+
+ This function is implemented by means of the PGTYPEStimestamp_defmt_asc function. See the documentation
+ there for a list of format specifiers that can be used.
+
+ The function returns 0 on success and a negative value in case of
+ error.
+
+ The function will subtract the timestamp variable that ts2
+ points to from the timestamp variable that ts1 points to
+ and will store the result in the interval variable that iv
+ points to.
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ Convert a timestamp variable to a C char* string.
+
+int dttoasc(timestamp *ts, char *output);
+
+ The function receives a pointer to the timestamp variable to convert
+ (ts) and the string that should hold the result of the
+ operation (output). It converts ts to its
+ textual representation according to the SQL standard, which is
+ be YYYY-MM-DD HH:MM:SS.
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ Convert a timestamp variable to a C char* using a format mask.
+
+int dttofmtasc(timestamp *ts, char *output, int str_len, char *fmtstr);
+
+ The function receives a pointer to the timestamp to convert as its
+ first argument (ts), a pointer to the output buffer
+ (output), the maximal length that has been allocated for
+ the output buffer (str_len) and the format mask to
+ use for the conversion (fmtstr).
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ Internally, this function uses the PGTYPEStimestamp_fmt_asc function. See the reference there for
+ information on what format mask specifiers can be used.
+
+ Convert an interval variable to a C char* string.
+
+int intoasc(interval *i, char *str);
+
+ The function receives a pointer to the interval variable to convert
+ (i) and the string that should hold the result of the
+ operation (str). It converts i to its
+ textual representation according to the SQL standard, which is
+ be YYYY-MM-DD HH:MM:SS.
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ The function receives the long value lng_val, the format
+ mask fmt and a pointer to the output buffer
+ outbuf. It converts the long value according to the format
+ mask to its textual representation.
+
+ The format mask can be composed of the following format specifying
+ characters:
+
+ * (asterisk) - if this position would be blank
+ otherwise, fill it with an asterisk.
+
+ & (ampersand) - if this position would be
+ blank otherwise, fill it with a zero.
+
+ # - turn leading zeroes into blanks.
+
+ < - left-justify the number in the string.
+
+ , (comma) - group numbers of four or more digits
+ into groups of three digits separated by a comma.
+
+ . (period) - this character separates the
+ whole-number part of the number from the fractional part.
+
+ - (minus) - the minus sign appears if the number
+ is a negative value.
+
+ + (plus) - the plus sign appears if the number is
+ a positive value.
+
+ ( - this replaces the minus sign in front of the
+ negative number. The minus sign will not appear.
+
+ ) - this character replaces the minus and is
+ printed behind the negative value.
+
+ Return the number of characters in a string without counting trailing
+ blanks.
+
+int byleng(char *str, int len);
+
+ The function expects a fixed-length string as its first argument
+ (str) and its length as its second argument
+ (len). It returns the number of significant characters,
+ that is the length of the string without trailing blanks.
+
+ Copy a fixed-length string into a null-terminated string.
+
+void ldchar(char *src, int len, char *dest);
+
+ The function receives the fixed-length string to copy
+ (src), its length (len) and a pointer to the
+ destination memory (dest). Note that you need to reserve at
+ least len+1 bytes for the string that dest
+ points to. The function copies at most len bytes to the new
+ location (less if the source string has trailing blanks) and adds the
+ null-terminator.
+
+ The function receives an integer that indicates the type of the
+ variable and a pointer to the variable itself that is cast to a C
+ char* pointer.
+
+ The following types exist:
+
+ CCHARTYPE - For a variable of type char or char*
+
+ CSHORTTYPE - For a variable of type short int
+
+ CINTTYPE - For a variable of type int
+
+ CBOOLTYPE - For a variable of type boolean
+
+ CFLOATTYPE - For a variable of type float
+
+ CLONGTYPE - For a variable of type long
+
+ CDOUBLETYPE - For a variable of type double
+
+ CDECIMALTYPE - For a variable of type decimal
+
+ CDATETYPE - For a variable of type date
+
+ CDTIMETYPE - For a variable of type timestamp
+
+
+ Here is an example of a call to this function:
+
+ The function receives the type of the variable to test (t)
+ as well a pointer to this variable (ptr). Note that the
+ latter needs to be cast to a char*. See the function rsetnull for a list of possible variable types.
+
+ Here is an example of how to use this function:
+
+ Note that all constants here describe errors and all of them are defined
+ to represent negative values. In the descriptions of the different
+ constants you can also find the value that the constants represent in the
+ current implementation. However you should not rely on this number. You can
+ however rely on the fact all of them are defined to represent negative
+ values.
+
+ Functions return this value if a bad value for a year was found while
+ parsing a date. Internally it is defined as -1204 (the Informix
+ definition).
+
+ Functions return this value if a bad value for a month was found while
+ parsing a date. Internally it is defined as -1205 (the Informix
+ definition).
+
+ Functions return this value if a bad value for a day was found while
+ parsing a date. Internally it is defined as -1206 (the Informix
+ definition).
+
+ Functions return this value if a parsing routine needs a short date
+ representation but did not get the date string in the right length.
+ Internally it is defined as -1209 (the Informix definition).
+
+ Functions return this value if a parsing routine was supposed to get a
+ format mask (like mmddyy) but not all fields were listed
+ correctly. Internally it is defined as -1212 (the Informix definition).
+
+ Functions return this value either if a parsing routine cannot parse
+ the textual representation for a numeric value because it contains
+ errors or if a routine cannot complete a calculation involving numeric
+ variables because at least one of the numeric variables is invalid.
+ Internally it is defined as -1213 (the Informix definition).
+
+ Functions return this value if a parsing routine is passed extra
+ characters it cannot parse. Internally it is defined as -1264 (the
+ Informix definition).
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-library.html b/pgsql/doc/postgresql/html/ecpg-library.html
new file mode 100644
index 0000000000000000000000000000000000000000..e0418249841415987a4b0fc4f7faee01cffc16f1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-library.html
@@ -0,0 +1,46 @@
+
+36.11. Library Functions
+ The libecpg library primarily contains
+ “hidden” functions that are used to implement the
+ functionality expressed by the embedded SQL commands. But there
+ are some functions that can usefully be called directly. Note that
+ this makes your code unportable.
+
+ ECPGdebug(int on, FILE
+ *stream) turns on debug
+ logging if called with the first argument non-zero. Debug logging
+ is done on stream. The log contains
+ all SQL statements with all the input
+ variables inserted, and the results from the
+ PostgreSQL server. This can be very
+ useful when searching for errors in your SQL
+ statements.
+
Note
+ On Windows, if the ecpg libraries and an application are
+ compiled with different flags, this function call will crash the
+ application because the internal representation of the
+ FILE pointers differ. Specifically,
+ multithreaded/single-threaded, release/debug, and static/dynamic
+ flags should be the same for the library and all applications using
+ that library.
+
+ ECPGget_PGconn(const char *connection_name)
+ returns the library database connection handle identified by the given name.
+ If connection_name is set to NULL, the current
+ connection handle is returned. If no connection handle can be identified, the function returns
+ NULL. The returned connection handle can be used to call any other functions
+ from libpq, if necessary.
+
Note
+ It is a bad idea to manipulate database connection handles made from ecpg directly
+ with libpq routines.
+
+ ECPGtransactionStatus(const char *connection_name)
+ returns the current transaction status of the given connection identified by connection_name.
+ See Section 34.2 and libpq's PQtransactionStatus for details about the returned status codes.
+
+ ECPGstatus(int lineno,
+ const char* connection_name)
+ returns true if you are connected to a database and false if not.
+ connection_name can be NULL
+ if a single connection is being used.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-lo.html b/pgsql/doc/postgresql/html/ecpg-lo.html
new file mode 100644
index 0000000000000000000000000000000000000000..f3853aa77755838b4a7933882750f5dc33c8a1da
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-lo.html
@@ -0,0 +1,100 @@
+
+36.12. Large Objects
+ Large objects are not directly supported by ECPG, but ECPG
+ application can manipulate large objects through the libpq large
+ object functions, obtaining the necessary PGconn
+ object by calling the ECPGget_PGconn()
+ function. (However, use of
+ the ECPGget_PGconn() function and touching
+ PGconn objects directly should be done very carefully
+ and ideally not mixed with other ECPG database access calls.)
+
+ For more details about the ECPGget_PGconn(), see
+ Section 36.11. For information about the large
+ object function interface, see Chapter 35.
+
+ Large object functions have to be called in a transaction block, so
+ when autocommit is off, BEGIN commands have to
+ be issued explicitly.
+
+ Example 36.2 shows an example program that
+ illustrates how to create, write, and read a large object in an
+ ECPG application.
+
Example 36.2. ECPG Program Accessing Large Objects
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-oracle-compat.html b/pgsql/doc/postgresql/html/ecpg-oracle-compat.html
new file mode 100644
index 0000000000000000000000000000000000000000..9f37667409b968600fba71432971ac5827631ff6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-oracle-compat.html
@@ -0,0 +1,19 @@
+
+36.16. Oracle Compatibility Mode
+ ecpg can be run in a so-called Oracle
+ compatibility mode. If this mode is active, it tries to
+ behave as if it were Oracle Pro*C.
+
+ Specifically, this mode changes ecpg in three ways:
+
+
+ Pad character arrays receiving character string types with
+ trailing spaces to the specified length
+
+ Zero byte terminate these character arrays, and set the indicator
+ variable if truncation occurs
+
+ Set the null indicator to -1 when character
+ arrays receive empty character string types
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-pgtypes.html b/pgsql/doc/postgresql/html/ecpg-pgtypes.html
new file mode 100644
index 0000000000000000000000000000000000000000..3ba5d318f3ac7e5caaa886ace41d0277b59f1c88
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-pgtypes.html
@@ -0,0 +1,765 @@
+
+36.6. pgtypes Library
+ The pgtypes library maps PostgreSQL database
+ types to C equivalents that can be used in C programs. It also offers
+ functions to do basic calculations with those types within C, i.e., without
+ the help of the PostgreSQL server. See the
+ following example:
+
+EXEC SQL BEGIN DECLARE SECTION;
+ date date1;
+ timestamp ts1, tsout;
+ interval iv1;
+ char *out;
+EXEC SQL END DECLARE SECTION;
+
+PGTYPESdate_today(&date1);
+EXEC SQL SELECT started, duration INTO :ts1, :iv1 FROM datetbl WHERE d=:date1;
+PGTYPEStimestamp_add_interval(&ts1, &iv1, &tsout);
+out = PGTYPEStimestamp_to_asc(&tsout);
+printf("Started + duration: %s\n", out);
+PGTYPESchar_free(out);
+
+
+ Some functions such as PGTYPESnumeric_to_asc return
+ a pointer to a freshly allocated character string. These results should be
+ freed with PGTYPESchar_free instead of
+ free. (This is important only on Windows, where
+ memory allocation and release sometimes need to be done by the same
+ library.)
+
+ The numeric type offers to do calculations with arbitrary precision. See
+ Section 8.1 for the equivalent type in the
+ PostgreSQL server. Because of the arbitrary precision this
+ variable needs to be able to expand and shrink dynamically. That's why you
+ can only create numeric variables on the heap, by means of the
+ PGTYPESnumeric_new and PGTYPESnumeric_free
+ functions. The decimal type, which is similar but limited in precision,
+ can be created on the stack as well as on the heap.
+
+ The following functions can be used to work with the numeric type:
+
+ Valid formats are for example:
+ -2,
+ .794,
+ +3.44,
+ 592.49E07 or
+ -32.84e-4.
+ If the value could be parsed successfully, a valid pointer is returned,
+ else the NULL pointer. At the moment ECPG always parses the complete
+ string and so it currently does not support to store the address of the
+ first invalid character in *endptr. You can safely
+ set endptr to NULL.
+
+ Returns a pointer to a string allocated by malloc that contains the string
+ representation of the numeric type num.
+
+char *PGTYPESnumeric_to_asc(numeric *num, int dscale);
+
+ The numeric value will be printed with dscale decimal
+ digits, with rounding applied if necessary.
+ The result must be freed with PGTYPESchar_free().
+
+ The function subtracts the variable var2 from
+ the variable var1. The result of the operation is
+ stored in the variable result.
+ The function returns 0 on success and -1 in case of error.
+
+ The function multiplies the variables var1 and
+ var2. The result of the operation is stored in the
+ variable result.
+ The function returns 0 on success and -1 in case of error.
+
+ The function divides the variables var1 by
+ var2. The result of the operation is stored in the
+ variable result.
+ The function returns 0 on success and -1 in case of error.
+
+ This function compares two numeric variables. In case of error,
+ INT_MAX is returned. On success, the function
+ returns one of three possible results:
+
+ Convert an int variable to a numeric variable.
+
+int PGTYPESnumeric_from_int(signed int int_val, numeric *var);
+
+ This function accepts a variable of type signed int and stores it
+ in the numeric variable var. Upon success, 0 is returned and
+ -1 in case of a failure.
+
+ Convert a long int variable to a numeric variable.
+
+int PGTYPESnumeric_from_long(signed long int long_val, numeric *var);
+
+ This function accepts a variable of type signed long int and stores it
+ in the numeric variable var. Upon success, 0 is returned and
+ -1 in case of a failure.
+
+ This function copies over the value of the variable that
+ src points to into the variable that dst
+ points to. It returns 0 on success and -1 if an error occurs.
+
+ This function accepts a variable of type double and stores the result
+ in the variable that dst points to. It returns 0 on success
+ and -1 if an error occurs.
+
+ The function converts the numeric value from the variable that
+ nv points to into the double variable that dp points
+ to. It returns 0 on success and -1 if an error occurs, including
+ overflow. On overflow, the global variable errno will be set
+ to PGTYPES_NUM_OVERFLOW additionally.
+
+int PGTYPESnumeric_to_int(numeric *nv, int *ip);
+
+ The function converts the numeric value from the variable that
+ nv points to into the integer variable that ip
+ points to. It returns 0 on success and -1 if an error occurs, including
+ overflow. On overflow, the global variable errno will be set
+ to PGTYPES_NUM_OVERFLOW additionally.
+
+int PGTYPESnumeric_to_long(numeric *nv, long *lp);
+
+ The function converts the numeric value from the variable that
+ nv points to into the long integer variable that
+ lp points to. It returns 0 on success and -1 if an error
+ occurs, including overflow. On overflow, the global variable
+ errno will be set to PGTYPES_NUM_OVERFLOW
+ additionally.
+
+ The function converts the numeric value from the variable that
+ src points to into the decimal variable that
+ dst points to. It returns 0 on success and -1 if an error
+ occurs, including overflow. On overflow, the global variable
+ errno will be set to PGTYPES_NUM_OVERFLOW
+ additionally.
+
+ The function converts the decimal value from the variable that
+ src points to into the numeric variable that
+ dst points to. It returns 0 on success and -1 if an error
+ occurs. Since the decimal type is implemented as a limited version of
+ the numeric type, overflow cannot occur with this conversion.
+
+ The date type in C enables your programs to deal with data of the SQL type
+ date. See Section 8.5 for the equivalent type in the
+ PostgreSQL server.
+
+ The following functions can be used to work with the date type:
+
+ The function receives a C char* string str and a pointer to
+ a C char* string endptr. At the moment ECPG always parses
+ the complete string and so it currently does not support to store the
+ address of the first invalid character in *endptr.
+ You can safely set endptr to NULL.
+
+ Note that the function always assumes MDY-formatted dates and there is
+ currently no variable to change that within ECPG.
+
+ Return the textual representation of a date variable.
+
+char *PGTYPESdate_to_asc(date dDate);
+
+ The function receives the date dDate as its only parameter.
+ It will output the date in the form 1999-01-18, i.e., in the
+ YYYY-MM-DD format.
+ The result must be freed with PGTYPESchar_free().
+
+ Extract the values for the day, the month and the year from a variable
+ of type date.
+
+void PGTYPESdate_julmdy(date d, int *mdy);
+
+
+ The function receives the date d and a pointer to an array
+ of 3 integer values mdy. The variable name indicates
+ the sequential order: mdy[0] will be set to contain the
+ number of the month, mdy[1] will be set to the value of the
+ day and mdy[2] will contain the year.
+
+ Create a date value from an array of 3 integers that specify the
+ day, the month and the year of the date.
+
+void PGTYPESdate_mdyjul(int *mdy, date *jdate);
+
+ The function receives the array of the 3 integers (mdy) as
+ its first argument and as its second argument a pointer to a variable
+ of type date that should hold the result of the operation.
+
+ The function receives the date to convert (dDate), the
+ format mask (fmtstring) and the string that will hold the
+ textual representation of the date (outbuf).
+
+ On success, 0 is returned and a negative value if an error occurred.
+
+ The following literals are the field specifiers you can use:
+
+ dd - The number of the day of the month.
+
+ mm - The number of the month of the year.
+
+ yy - The number of the year as a two digit number.
+
+ yyyy - The number of the year as a four digit number.
+
+ ddd - The name of the day (abbreviated).
+
+ mmm - The name of the month (abbreviated).
+
+ All other characters are copied 1:1 to the output string.
+
+ Table 36.3 indicates a few possible formats. This will give
+ you an idea of how to use this function. All output lines are based on
+ the same date: November 23, 1959.
+
Table 36.3. Valid Input Formats for PGTYPESdate_fmt_asc
+
+ The function receives a pointer to the date value that should hold the
+ result of the operation (d), the format mask to use for
+ parsing the date (fmt) and the C char* string containing
+ the textual representation of the date (str). The textual
+ representation is expected to match the format mask. However you do not
+ need to have a 1:1 mapping of the string to the format mask. The
+ function only analyzes the sequential order and looks for the literals
+ yy or yyyy that indicate the
+ position of the year, mm to indicate the position of
+ the month and dd to indicate the position of the
+ day.
+
+ Table 36.4 indicates a few possible formats. This will give
+ you an idea of how to use this function.
+
Table 36.4. Valid Input Formats for rdefmtdate
Format
String
Result
ddmmyy
21-2-54
1954-02-21
ddmmyy
2-12-54
1954-12-02
ddmmyy
20111954
1954-11-20
ddmmyy
130464
1964-04-13
mmm.dd.yyyy
MAR-12-1967
1967-03-12
yy/mm/dd
1954, February 3rd
1954-02-03
mmm.dd.yyyy
041269
1969-04-12
yy/mm/dd
In the year 2525, in the month of July, mankind will be alive on the 28th day
+ The timestamp type in C enables your programs to deal with data of the SQL
+ type timestamp. See Section 8.5 for the equivalent
+ type in the PostgreSQL server.
+
+ The following functions can be used to work with the timestamp type:
+
+ The function receives the string to parse (str) and a
+ pointer to a C char* (endptr).
+ At the moment ECPG always parses
+ the complete string and so it currently does not support to store the
+ address of the first invalid character in *endptr.
+ You can safely set endptr to NULL.
+
+ The function returns the parsed timestamp on success. On error,
+ PGTYPESInvalidTimestamp is returned and errno is
+ set to PGTYPES_TS_BAD_TIMESTAMP. See PGTYPESInvalidTimestamp for important notes on this value.
+
+ In general, the input string can contain any combination of an allowed
+ date specification, a whitespace character and an allowed time
+ specification. Note that time zones are not supported by ECPG. It can
+ parse them but does not apply any calculation as the
+ PostgreSQL server does for example. Timezone
+ specifiers are silently discarded.
+
+ Table 36.5 contains a few examples for input strings.
+
Table 36.5. Valid Input Formats for PGTYPEStimestamp_from_asc
Input
Result
1999-01-08 04:05:06
1999-01-08 04:05:06
January 8 04:05:06 1999 PST
1999-01-08 04:05:06
1999-Jan-08 04:05:06.789-8
1999-01-08 04:05:06.789 (time zone specifier ignored)
+ The function receives the timestamp tstamp as
+ its only argument and returns an allocated string that contains the
+ textual representation of the timestamp.
+ The result must be freed with PGTYPESchar_free().
+
+ Convert a timestamp variable to a C char* using a format mask.
+
+int PGTYPEStimestamp_fmt_asc(timestamp *ts, char *output, int str_len, char *fmtstr);
+
+ The function receives a pointer to the timestamp to convert as its
+ first argument (ts), a pointer to the output buffer
+ (output), the maximal length that has been allocated for
+ the output buffer (str_len) and the format mask to
+ use for the conversion (fmtstr).
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ You can use the following format specifiers for the format mask. The
+ format specifiers are the same ones that are used in the
+ strftime function in libc. Any
+ non-format specifier will be copied into the output buffer.
+
+
+ %A - is replaced by national representation of
+ the full weekday name.
+
+ %a - is replaced by national representation of
+ the abbreviated weekday name.
+
+ %B - is replaced by national representation of
+ the full month name.
+
+ %b - is replaced by national representation of
+ the abbreviated month name.
+
+ %C - is replaced by (year / 100) as decimal
+ number; single digits are preceded by a zero.
+
+ %c - is replaced by national representation of
+ time and date.
+
+ %D - is equivalent to
+ %m/%d/%y.
+
+ %d - is replaced by the day of the month as a
+ decimal number (01–31).
+
+ Additionally %OB implemented to represent
+ alternative months names (used standalone, without day mentioned).
+
+ %e - is replaced by the day of month as a decimal
+ number (1–31); single digits are preceded by a blank.
+
+ %F - is equivalent to %Y-%m-%d.
+
+ %G - is replaced by a year as a decimal number
+ with century. This year is the one that contains the greater part of
+ the week (Monday as the first day of the week).
+
+ %g - is replaced by the same year as in
+ %G, but as a decimal number without century
+ (00–99).
+
+ %H - is replaced by the hour (24-hour clock) as a
+ decimal number (00–23).
+
+ %h - the same as %b.
+
+ %I - is replaced by the hour (12-hour clock) as a
+ decimal number (01–12).
+
+ %j - is replaced by the day of the year as a
+ decimal number (001–366).
+
+ %k - is replaced by the hour (24-hour clock) as a
+ decimal number (0–23); single digits are preceded by a blank.
+
+ %l - is replaced by the hour (12-hour clock) as a
+ decimal number (1–12); single digits are preceded by a blank.
+
+ %M - is replaced by the minute as a decimal
+ number (00–59).
+
+ %m - is replaced by the month as a decimal number
+ (01–12).
+
+ %n - is replaced by a newline.
+
+ %O* - the same as %E*.
+
+ %p - is replaced by national representation of
+ either “ante meridiem” or “post meridiem” as appropriate.
+
+ %R - is equivalent to %H:%M.
+
+ %r - is equivalent to %I:%M:%S
+ %p.
+
+ %S - is replaced by the second as a decimal
+ number (00–60).
+
+ %s - is replaced by the number of seconds since
+ the Epoch, UTC.
+
+ %T - is equivalent to %H:%M:%S
+
+ %t - is replaced by a tab.
+
+ %U - is replaced by the week number of the year
+ (Sunday as the first day of the week) as a decimal number (00–53).
+
+ %u - is replaced by the weekday (Monday as the
+ first day of the week) as a decimal number (1–7).
+
+ %V - is replaced by the week number of the year
+ (Monday as the first day of the week) as a decimal number (01–53).
+ If the week containing January 1 has four or more days in the new
+ year, then it is week 1; otherwise it is the last week of the
+ previous year, and the next week is week 1.
+
+ %v - is equivalent to
+ %e-%b-%Y.
+
+ %W - is replaced by the week number of the year
+ (Monday as the first day of the week) as a decimal number (00–53).
+
+ %w - is replaced by the weekday (Sunday as the
+ first day of the week) as a decimal number (0–6).
+
+ %X - is replaced by national representation of
+ the time.
+
+ %x - is replaced by national representation of
+ the date.
+
+ %Y - is replaced by the year with century as a
+ decimal number.
+
+ %y - is replaced by the year without century as a
+ decimal number (00–99).
+
+ %Z - is replaced by the time zone name.
+
+ %z - is replaced by the time zone offset from
+ UTC; a leading plus sign stands for east of UTC, a minus sign for
+ west of UTC, hours and minutes follow with two digits each and no
+ delimiter between them (common form for RFC 822 date headers).
+
+ %+ - is replaced by national representation of
+ the date and time.
+
+ %-* - GNU libc extension. Do not do any padding
+ when performing numerical outputs.
+
+ $_* - GNU libc extension. Explicitly specify space for padding.
+
+ %0* - GNU libc extension. Explicitly specify zero
+ for padding.
+
+ The function will subtract the timestamp variable that ts2
+ points to from the timestamp variable that ts1 points to
+ and will store the result in the interval variable that iv
+ points to.
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ The function receives the textual representation of a timestamp in the
+ variable str as well as the formatting mask to use in the
+ variable fmt. The result will be stored in the variable
+ that d points to.
+
+ If the formatting mask fmt is NULL, the function will fall
+ back to the default formatting mask which is %Y-%m-%d
+ %H:%M:%S.
+
+ This is the reverse function to PGTYPEStimestamp_fmt_asc. See the documentation there in
+ order to find out about the possible formatting mask entries.
+
+ The function receives a pointer to a timestamp variable tin
+ and a pointer to an interval variable span. It adds the
+ interval to the timestamp and saves the resulting timestamp in the
+ variable that tout points to.
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ The function subtracts the interval variable that span
+ points to from the timestamp variable that tin points to
+ and saves the result into the variable that tout points
+ to.
+
+ Upon success, the function returns 0 and a negative value if an
+ error occurred.
+
+ The interval type in C enables your programs to deal with data of the SQL
+ type interval. See Section 8.5 for the equivalent
+ type in the PostgreSQL server.
+
+ The following functions can be used to work with the interval type:
+
+ The function parses the input string str and returns a
+ pointer to an allocated interval variable.
+ At the moment ECPG always parses
+ the complete string and so it currently does not support to store the
+ address of the first invalid character in *endptr.
+ You can safely set endptr to NULL.
+
+ Convert a variable of type interval to its textual representation.
+
+char *PGTYPESinterval_to_asc(interval *span);
+
+ The function converts the interval variable that span
+ points to into a C char*. The output looks like this example:
+ @ 1 day 12 hours 59 mins 10 secs.
+ The result must be freed with PGTYPESchar_free().
+
+ The function copies the interval variable that intvlsrc
+ points to into the variable that intvldest points to. Note
+ that you need to allocate the memory for the destination variable
+ before.
+
+ The decimal type is similar to the numeric type. However it is limited to
+ a maximum precision of 30 significant digits. In contrast to the numeric
+ type which can be created on the heap only, the decimal type can be
+ created either on the stack or on the heap (by means of the functions
+ PGTYPESdecimal_new and
+ PGTYPESdecimal_free).
+ There are a lot of other functions that deal with the decimal type in the
+ Informix compatibility mode described in Section 36.15.
+
+ The following functions can be used to work with the decimal type and are
+ not only contained in the libcompat library.
+
+ An overflow occurred. Since the numeric type can deal with almost
+ arbitrary precision, converting a numeric variable into other types
+ might cause overflow.
+
+ An underflow occurred. Since the numeric type can deal with almost
+ arbitrary precision, converting a numeric variable into other types
+ might cause underflow.
+
+ An invalid interval string was passed to the
+ PGTYPESinterval_from_asc function, or an
+ invalid interval value was passed to the
+ PGTYPESinterval_to_asc function.
+
+ An invalid timestamp string pass passed to
+ the PGTYPEStimestamp_from_asc function,
+ or an invalid timestamp value was passed to
+ the PGTYPEStimestamp_to_asc function.
+
+ A value of type timestamp representing an invalid time stamp. This is
+ returned by the function PGTYPEStimestamp_from_asc on
+ parse error.
+ Note that due to the internal representation of the timestamp data type,
+ PGTYPESInvalidTimestamp is also a valid timestamp at
+ the same time. It is set to 1899-12-31 23:59:59. In order
+ to detect errors, make sure that your application does not only test
+ for PGTYPESInvalidTimestamp but also for
+ errno != 0 after each call to
+ PGTYPEStimestamp_from_asc.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-preproc.html b/pgsql/doc/postgresql/html/ecpg-preproc.html
new file mode 100644
index 0000000000000000000000000000000000000000..7561cd2bbfbfa785361243817cc323470e2b1705
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-preproc.html
@@ -0,0 +1,135 @@
+
+36.9. Preprocessor Directives
+ To include an external file into your embedded SQL program, use:
+
+EXEC SQL INCLUDE filename;
+EXEC SQL INCLUDE <filename>;
+EXEC SQL INCLUDE "filename";
+
+ The embedded SQL preprocessor will look for a file named
+ filename.h,
+ preprocess it, and include it in the resulting C output. Thus,
+ embedded SQL statements in the included file are handled correctly.
+
+ The ecpg preprocessor will search a file at
+ several directories in following order:
+
+
current directory
/usr/local/include
PostgreSQL include directory, defined at build time (e.g., /usr/local/pgsql/include)
/usr/include
+
+ But when EXEC SQL INCLUDE
+ "filename" is used, only the
+ current directory is searched.
+
+ In each directory, the preprocessor will first look for the file
+ name as given, and if not found will append .h
+ to the file name and try again (unless the specified file name
+ already has that suffix).
+
+ Note that EXEC SQL INCLUDE is not the same as:
+
+#include <filename.h>
+
+ because this file would not be subject to SQL command preprocessing.
+ Naturally, you can continue to use the C
+ #include directive to include other header
+ files.
+
Note
+ The include file name is case-sensitive, even though the rest of
+ the EXEC SQL INCLUDE command follows the normal
+ SQL case-sensitivity rules.
+
+ Of course you can continue to use the C versions #define
+ and #undef in your embedded SQL program. The difference
+ is where your defined values get evaluated. If you use EXEC SQL
+ DEFINE then the ecpg preprocessor evaluates the defines and substitutes
+ the values. For example if you write:
+
+EXEC SQL DEFINE MYNUMBER 12;
+...
+EXEC SQL UPDATE Tbl SET col = MYNUMBER;
+
+ then ecpg will already do the substitution and your C compiler will never
+ see any name or identifier MYNUMBER. Note that you cannot use
+ #define for a constant that you are going to use in an
+ embedded SQL query because in this case the embedded SQL precompiler is not
+ able to see this declaration.
+
+ If multiple input files are named on the ecpg
+ preprocessor's command line, the effects of EXEC SQL
+ DEFINE and EXEC SQL UNDEF do not carry
+ across files: each file starts with only the symbols defined
+ by -D switches on the command line.
+
36.9.3. ifdef, ifndef, elif, else, and endif Directives #
+ You can use the following directives to compile code sections conditionally:
+
+
+ Begins an optional alternative section after an
+ EXEC SQL ifdef name or
+ EXEC SQL ifndef name
+ directive. Any number of elif sections can appear.
+ Lines following an elif will be processed
+ if name has been
+ defined and no previous section of the same
+ ifdef/ifndef...endif
+ construct has been processed.
+
+ Begins an optional, final alternative section after an
+ EXEC SQL ifdef name or
+ EXEC SQL ifndef name
+ directive. Subsequent lines will be processed if no previous section
+ of the same
+ ifdef/ifndef...endif
+ construct has been processed.
+
+ Now that you have an idea how to form embedded SQL C programs, you
+ probably want to know how to compile them. Before compiling you
+ run the file through the embedded SQL
+ C preprocessor, which converts the
+ SQL statements you used to special function
+ calls. After compiling, you must link with a special library that
+ contains the needed functions. These functions fetch information
+ from the arguments, perform the SQL command using
+ the libpq interface, and put the result
+ in the arguments specified for output.
+
+ The preprocessor program is called ecpg and is
+ included in a normal PostgreSQL installation.
+ Embedded SQL programs are typically named with an extension
+ .pgc. If you have a program file called
+ prog1.pgc, you can preprocess it by simply
+ calling:
+
+ecpg prog1.pgc
+
+ This will create a file called prog1.c. If
+ your input files do not follow the suggested naming pattern, you
+ can specify the output file explicitly using the
+ -o option.
+
+ The preprocessed file can be compiled normally, for example:
+
+cc -c prog1.c
+
+ The generated C source files include header files from the
+ PostgreSQL installation, so if you installed
+ PostgreSQL in a location that is not searched by
+ default, you have to add an option such as
+ -I/usr/local/pgsql/include to the compilation
+ command line.
+
+ To link an embedded SQL program, you need to include the
+ libecpg library, like so:
+
+cc -o myprog prog1.o prog2.o ... -lecpg
+
+ Again, you might have to add an option like
+ -L/usr/local/pgsql/lib to that command line.
+
+ You can
+ use pg_config
+ or pkg-config with package name libecpg to
+ get the paths for your installation.
+
+ If you manage the build process of a larger project using
+ make, it might be convenient to include
+ the following implicit rule to your makefiles:
+
+ECPG = ecpg
+
+%.c: %.pgc
+ $(ECPG) $<
+
+
+ The complete syntax of the ecpg command is
+ detailed in ecpg.
+
+ The ecpg library is thread-safe by
+ default. However, you might need to use some threading
+ command-line options to compile your client code.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-allocate-descriptor.html b/pgsql/doc/postgresql/html/ecpg-sql-allocate-descriptor.html
new file mode 100644
index 0000000000000000000000000000000000000000..bef258682a070f7bc01916bbf5b2f83dfdaaf105
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-allocate-descriptor.html
@@ -0,0 +1,19 @@
+
+ALLOCATE DESCRIPTOR
ALLOCATE DESCRIPTOR — allocate an SQL descriptor area
Synopsis
+ALLOCATE DESCRIPTOR name
+
Description
+ ALLOCATE DESCRIPTOR allocates a new named SQL
+ descriptor area, which can be used to exchange data between the
+ PostgreSQL server and the host program.
+
+ Descriptor areas should be freed after use using
+ the DEALLOCATE DESCRIPTOR command.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-commands.html b/pgsql/doc/postgresql/html/ecpg-sql-commands.html
new file mode 100644
index 0000000000000000000000000000000000000000..91d704ec1241e971c7fce01313a75a122df278b4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-commands.html
@@ -0,0 +1,7 @@
+
+36.14. Embedded SQL Commands
WHENEVER — specify the action to be taken when an SQL statement causes a specific class condition to be raised
+ This section describes all SQL commands that are specific to
+ embedded SQL. Also refer to the SQL commands listed
+ in SQL Commands, which can also be used in
+ embedded SQL, unless stated otherwise.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-connect.html b/pgsql/doc/postgresql/html/ecpg-sql-connect.html
new file mode 100644
index 0000000000000000000000000000000000000000..b44ba244047de230d56c94c7b91ed85164929a00
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-connect.html
@@ -0,0 +1,109 @@
+
+CONNECT
+CONNECT TO connection_target [ AS connection_name ] [ USER connection_user ]
+CONNECT TO DEFAULT
+CONNECT connection_user
+DATABASE connection_target
+
Description
+ The CONNECT command establishes a connection
+ between the client and the PostgreSQL server.
+
+ This parameter can also specify user name and password, using one the forms
+ user_name/password,
+ user_name IDENTIFIED BY password, or
+ user_name USING password.
+
+ User name and password can be SQL identifiers, string
+ constants, or host variables.
+
+ Use all default connection parameters, as defined by libpq.
+
Examples
+ Here a several variants for specifying connection parameters:
+
+EXEC SQL CONNECT TO "connectdb" AS main;
+EXEC SQL CONNECT TO "connectdb" AS second;
+EXEC SQL CONNECT TO "unix:postgresql://200.46.204.71/connectdb" AS main USER connectuser;
+EXEC SQL CONNECT TO "unix:postgresql://localhost/connectdb" AS main USER connectuser;
+EXEC SQL CONNECT TO 'connectdb' AS main;
+EXEC SQL CONNECT TO 'unix:postgresql://localhost/connectdb' AS main USER :user;
+EXEC SQL CONNECT TO :db AS :id;
+EXEC SQL CONNECT TO :db USER connectuser USING :pw;
+EXEC SQL CONNECT TO @localhost AS main USER connectdb;
+EXEC SQL CONNECT TO REGRESSDB1 as main;
+EXEC SQL CONNECT TO AS main USER connectdb;
+EXEC SQL CONNECT TO connectdb AS :id;
+EXEC SQL CONNECT TO connectdb AS main USER connectuser/connectdb;
+EXEC SQL CONNECT TO connectdb AS main;
+EXEC SQL CONNECT TO connectdb@localhost AS main;
+EXEC SQL CONNECT TO tcp:postgresql://localhost/ USER connectdb;
+EXEC SQL CONNECT TO tcp:postgresql://localhost/connectdb USER connectuser IDENTIFIED BY connectpw;
+EXEC SQL CONNECT TO tcp:postgresql://localhost:20/connectdb USER connectuser IDENTIFIED BY connectpw;
+EXEC SQL CONNECT TO unix:postgresql://localhost/ AS main USER connectdb;
+EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb AS main USER connectuser;
+EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb USER connectuser IDENTIFIED BY "connectpw";
+EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb USER connectuser USING "connectpw";
+EXEC SQL CONNECT TO unix:postgresql://localhost/connectdb?connect_timeout=14 USER connectuser;
+
+
+ Here is an example program that illustrates the use of host
+ variables to specify connection parameters:
+
+int
+main(void)
+{
+EXEC SQL BEGIN DECLARE SECTION;
+ char *dbname = "testdb"; /* database name */
+ char *user = "testuser"; /* connection user name */
+ char *connection = "tcp:postgresql://localhost:5432/testdb";
+ /* connection string */
+ char ver[256]; /* buffer to store the version string */
+EXEC SQL END DECLARE SECTION;
+
+ ECPGdebug(1, stderr);
+
+ EXEC SQL CONNECT TO :dbname USER :user;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+ EXEC SQL SELECT version() INTO :ver;
+ EXEC SQL DISCONNECT;
+
+ printf("version: %s\n", ver);
+
+ EXEC SQL CONNECT TO :connection USER :user;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+ EXEC SQL SELECT version() INTO :ver;
+ EXEC SQL DISCONNECT;
+
+ printf("version: %s\n", ver);
+
+ return 0;
+}
+
+
Compatibility
+ CONNECT is specified in the SQL standard, but
+ the format of the connection parameters is
+ implementation-specific.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-deallocate-descriptor.html b/pgsql/doc/postgresql/html/ecpg-sql-deallocate-descriptor.html
new file mode 100644
index 0000000000000000000000000000000000000000..472835e1ade00fabd5cb83b5bdfb6818f0a0b8ae
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-deallocate-descriptor.html
@@ -0,0 +1,16 @@
+
+DEALLOCATE DESCRIPTOR
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-declare-statement.html b/pgsql/doc/postgresql/html/ecpg-sql-declare-statement.html
new file mode 100644
index 0000000000000000000000000000000000000000..49d33d78efd46bef0a923b4f644efceeaf9c45a0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-declare-statement.html
@@ -0,0 +1,33 @@
+
+DECLARE STATEMENT
+EXEC SQL [ AT connection_name ] DECLARE statement_name STATEMENT
+
Description
+ DECLARE STATEMENT declares an SQL statement identifier.
+ SQL statement identifier can be associated with the connection.
+ When the identifier is used by dynamic SQL statements, the statements
+ are executed using the associated connection.
+ The namespace of the declaration is the precompile unit, and multiple
+ declarations to the same SQL statement identifier are not allowed.
+ Note that if the precompiler runs in Informix compatibility mode and
+ some SQL statement is declared, "database" can not be used as a cursor
+ name.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-declare.html b/pgsql/doc/postgresql/html/ecpg-sql-declare.html
new file mode 100644
index 0000000000000000000000000000000000000000..4ed79ad7aa9a3d296bcec1780804ae6918355a51
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-declare.html
@@ -0,0 +1,43 @@
+
+DECLARE
+DECLARE cursor_name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR prepared_name
+DECLARE cursor_name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR query
+
Description
+ DECLARE declares a cursor for iterating over
+ the result set of a prepared statement. This command has
+ slightly different semantics from the direct SQL
+ command DECLARE: Whereas the latter executes a
+ query and prepares the result set for retrieval, this embedded
+ SQL command merely declares a name as a “loop
+ variable” for iterating over the result set of a query;
+ the actual execution happens when the cursor is opened with
+ the OPEN command.
+
+ A SELECT or
+ VALUES command which will provide the
+ rows to be returned by the cursor.
+
+ For the meaning of the cursor options,
+ see DECLARE.
+
Examples
+ Examples declaring a cursor for a query:
+
+EXEC SQL DECLARE C CURSOR FOR SELECT * FROM My_Table;
+EXEC SQL DECLARE C CURSOR FOR SELECT Item1 FROM T;
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT version();
+
+
+ An example declaring a cursor for a prepared statement:
+
+EXEC SQL PREPARE stmt1 AS SELECT version();
+EXEC SQL DECLARE cur1 CURSOR FOR stmt1;
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-describe.html b/pgsql/doc/postgresql/html/ecpg-sql-describe.html
new file mode 100644
index 0000000000000000000000000000000000000000..6db53ada9dcb7ead33d0e3301ad498842e74ab2c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-describe.html
@@ -0,0 +1,26 @@
+
+DESCRIBE
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-disconnect.html b/pgsql/doc/postgresql/html/ecpg-sql-disconnect.html
new file mode 100644
index 0000000000000000000000000000000000000000..0bfd048b43acf88dedd61e6920ba5976ce3ab870
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-disconnect.html
@@ -0,0 +1,35 @@
+
+DISCONNECT
+ Close the “current” connection, which is either
+ the most recently opened connection, or the connection set by
+ the SET CONNECTION command. This is also
+ the default if no argument is given to
+ the DISCONNECT command.
+
+int
+main(void)
+{
+ EXEC SQL CONNECT TO testdb AS con1 USER testuser;
+ EXEC SQL CONNECT TO testdb AS con2 USER testuser;
+ EXEC SQL CONNECT TO testdb AS con3 USER testuser;
+
+ EXEC SQL DISCONNECT CURRENT; /* close con3 */
+ EXEC SQL DISCONNECT ALL; /* close con2 and con1 */
+
+ return 0;
+}
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-execute-immediate.html b/pgsql/doc/postgresql/html/ecpg-sql-execute-immediate.html
new file mode 100644
index 0000000000000000000000000000000000000000..2e46ed854587a0e911c75b4d4b6b02a38cc4179a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-execute-immediate.html
@@ -0,0 +1,37 @@
+
+EXECUTE IMMEDIATE
+ A literal string or a host variable containing the SQL
+ statement to be executed.
+
Notes
+ In typical usage, the string is a host
+ variable reference to a string containing a dynamically-constructed
+ SQL statement. The case of a literal string is not very useful;
+ you might as well just write the SQL statement directly, without
+ the extra typing of EXECUTE IMMEDIATE.
+
+ If you do use a literal string, keep in mind that any double quotes
+ you might wish to include in the SQL statement must be written as
+ octal escapes (\042) not the usual C
+ idiom \". This is because the string is inside
+ an EXEC SQL section, so the ECPG lexer parses it
+ according to SQL rules not C rules. Any embedded backslashes will
+ later be handled according to C rules; but \"
+ causes an immediate syntax error because it is seen as ending the
+ literal.
+
Examples
+ Here is an example that executes an INSERT
+ statement using EXECUTE IMMEDIATE and a host
+ variable named command:
+
+sprintf(command, "INSERT INTO test (name, amount, letter) VALUES ('db: ''r1''', 1, 'f')");
+EXEC SQL EXECUTE IMMEDIATE :command;
+
+
Compatibility
+ EXECUTE IMMEDIATE is specified in the SQL standard.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-get-descriptor.html b/pgsql/doc/postgresql/html/ecpg-sql-get-descriptor.html
new file mode 100644
index 0000000000000000000000000000000000000000..5c3a8b15635fe115624468733ede2cb281a7e814
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-get-descriptor.html
@@ -0,0 +1,104 @@
+
+GET DESCRIPTOR
+ GET DESCRIPTOR retrieves information about a
+ query result set from an SQL descriptor area and stores it into
+ host variables. A descriptor area is typically populated
+ using FETCH or SELECT
+ before using this command to transfer the information into host
+ language variables.
+
+ This command has two forms: The first form retrieves
+ descriptor “header” items, which apply to the result
+ set in its entirety. One example is the row count. The second
+ form, which requires the column number as additional parameter,
+ retrieves information about a particular column. Examples are
+ the column name and the actual column value.
+
+ A token identifying which header information item to retrieve.
+ Only COUNT, to get the number of columns in the
+ result set, is currently supported.
+
+ A host variable that will receive the data retrieved from the
+ descriptor area.
+
Examples
+ An example to retrieve the number of columns in a result set:
+
+EXEC SQL GET DESCRIPTOR d :d_count = COUNT;
+
+
+ An example to retrieve a data length in the first column:
+
+EXEC SQL GET DESCRIPTOR d VALUE 1 :d_returned_octet_length = RETURNED_OCTET_LENGTH;
+
+
+ An example to retrieve the data body of the second column as a
+ string:
+
+EXEC SQL GET DESCRIPTOR d VALUE 2 :d_data = DATA;
+
+
+ Here is an example for a whole procedure of
+ executing SELECT current_database(); and showing the number of
+ columns, the column data length, and the column data:
+
+int
+main(void)
+{
+EXEC SQL BEGIN DECLARE SECTION;
+ int d_count;
+ char d_data[1024];
+ int d_returned_octet_length;
+EXEC SQL END DECLARE SECTION;
+
+ EXEC SQL CONNECT TO testdb AS con1 USER testuser;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+ EXEC SQL ALLOCATE DESCRIPTOR d;
+
+ /* Declare, open a cursor, and assign a descriptor to the cursor */
+ EXEC SQL DECLARE cur CURSOR FOR SELECT current_database();
+ EXEC SQL OPEN cur;
+ EXEC SQL FETCH NEXT FROM cur INTO SQL DESCRIPTOR d;
+
+ /* Get a number of total columns */
+ EXEC SQL GET DESCRIPTOR d :d_count = COUNT;
+ printf("d_count = %d\n", d_count);
+
+ /* Get length of a returned column */
+ EXEC SQL GET DESCRIPTOR d VALUE 1 :d_returned_octet_length = RETURNED_OCTET_LENGTH;
+ printf("d_returned_octet_length = %d\n", d_returned_octet_length);
+
+ /* Fetch the returned column as a string */
+ EXEC SQL GET DESCRIPTOR d VALUE 1 :d_data = DATA;
+ printf("d_data = %s\n", d_data);
+
+ /* Closing */
+ EXEC SQL CLOSE cur;
+ EXEC SQL COMMIT;
+
+ EXEC SQL DEALLOCATE DESCRIPTOR d;
+ EXEC SQL DISCONNECT ALL;
+
+ return 0;
+}
+
+ When the example is executed, the result will look like this:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-open.html b/pgsql/doc/postgresql/html/ecpg-sql-open.html
new file mode 100644
index 0000000000000000000000000000000000000000..c7147436479e17cb8a5786f726a0c33e7f08c34c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-open.html
@@ -0,0 +1,31 @@
+
+OPEN
+OPEN cursor_name
+OPEN cursor_name USING value [, ... ]
+OPEN cursor_name USING SQL DESCRIPTOR descriptor_name
+
Description
+ OPEN opens a cursor and optionally binds
+ actual values to the placeholders in the cursor's declaration.
+ The cursor must previously have been declared with
+ the DECLARE command. The execution
+ of OPEN causes the query to start executing on
+ the server.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-prepare.html b/pgsql/doc/postgresql/html/ecpg-sql-prepare.html
new file mode 100644
index 0000000000000000000000000000000000000000..7c7cd5a498c8b22c2d8097f79f3b0b91a1149662
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-prepare.html
@@ -0,0 +1,42 @@
+
+PREPARE
+ PREPARE prepares a statement dynamically
+ specified as a string for execution. This is different from the
+ direct SQL statement PREPARE, which can also
+ be used in embedded programs. The EXECUTE
+ command is used to execute either kind of prepared statement.
+
+ A literal string or a host variable containing a preparable
+ SQL statement, one of SELECT, INSERT, UPDATE, or DELETE.
+ Use question marks (?) for parameter values
+ to be supplied at execution.
+
Notes
+ In typical usage, the string is a host
+ variable reference to a string containing a dynamically-constructed
+ SQL statement. The case of a literal string is not very useful;
+ you might as well just write a direct SQL PREPARE
+ statement.
+
+ If you do use a literal string, keep in mind that any double quotes
+ you might wish to include in the SQL statement must be written as
+ octal escapes (\042) not the usual C
+ idiom \". This is because the string is inside
+ an EXEC SQL section, so the ECPG lexer parses it
+ according to SQL rules not C rules. Any embedded backslashes will
+ later be handled according to C rules; but \"
+ causes an immediate syntax error because it is seen as ending the
+ literal.
+
Examples
+char *stmt = "SELECT * FROM test1 WHERE a = ? AND b = ?";
+
+EXEC SQL ALLOCATE DESCRIPTOR outdesc;
+EXEC SQL PREPARE foo FROM :stmt;
+
+EXEC SQL EXECUTE foo USING SQL DESCRIPTOR indesc INTO SQL DESCRIPTOR outdesc;
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-set-autocommit.html b/pgsql/doc/postgresql/html/ecpg-sql-set-autocommit.html
new file mode 100644
index 0000000000000000000000000000000000000000..603f57e3ab168b1ad46e0a23044acc68a31b1c2f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-set-autocommit.html
@@ -0,0 +1,13 @@
+
+SET AUTOCOMMIT
SET AUTOCOMMIT — set the autocommit behavior of the current session
Synopsis
+SET AUTOCOMMIT { = | TO } { ON | OFF }
+
Description
+ SET AUTOCOMMIT sets the autocommit behavior of
+ the current database session. By default, embedded SQL programs
+ are not in autocommit mode,
+ so COMMIT needs to be issued explicitly when
+ desired. This command can change the session to autocommit mode,
+ where each individual statement is committed implicitly.
+
Compatibility
+ SET AUTOCOMMIT is an extension of PostgreSQL ECPG.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-set-connection.html b/pgsql/doc/postgresql/html/ecpg-sql-set-connection.html
new file mode 100644
index 0000000000000000000000000000000000000000..a55a4063cd12dc81aaf9d952d17f89ab2dfbf99b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-set-connection.html
@@ -0,0 +1,18 @@
+
+SET CONNECTION
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-set-descriptor.html b/pgsql/doc/postgresql/html/ecpg-sql-set-descriptor.html
new file mode 100644
index 0000000000000000000000000000000000000000..e02ce1048713a3288cb57bb3d8858f104d319126
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-set-descriptor.html
@@ -0,0 +1,38 @@
+
+SET DESCRIPTOR
SET DESCRIPTOR — set information in an SQL descriptor area
Synopsis
+SET DESCRIPTOR descriptor_namedescriptor_header_item = value [, ... ]
+SET DESCRIPTOR descriptor_name VALUE numberdescriptor_item = value [, ...]
+
Description
+ SET DESCRIPTOR populates an SQL descriptor
+ area with values. The descriptor area is then typically used to
+ bind parameters in a prepared query execution.
+
+ This command has two forms: The first form applies to the
+ descriptor “header”, which is independent of a
+ particular datum. The second form assigns values to particular
+ datums, identified by number.
+
+ A value to store into the descriptor item. This can be an SQL
+ constant or a host variable.
+
Examples
+EXEC SQL SET DESCRIPTOR indesc COUNT = 1;
+EXEC SQL SET DESCRIPTOR indesc VALUE 1 DATA = 2;
+EXEC SQL SET DESCRIPTOR indesc VALUE 1 DATA = :val1;
+EXEC SQL SET DESCRIPTOR indesc VALUE 2 INDICATOR = :val1, DATA = 'some string';
+EXEC SQL SET DESCRIPTOR indesc VALUE 2 INDICATOR = :val2null, DATA = :val2;
+
Compatibility
+ SET DESCRIPTOR is specified in the SQL standard.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-type.html b/pgsql/doc/postgresql/html/ecpg-sql-type.html
new file mode 100644
index 0000000000000000000000000000000000000000..52ee8995e9606e4cc3cbcc83464d3e3256684089
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-type.html
@@ -0,0 +1,88 @@
+
+TYPE
+EXEC SQL TYPE customer IS
+ struct
+ {
+ varchar name[50];
+ int phone;
+ };
+
+EXEC SQL TYPE cust_ind IS
+ struct ind
+ {
+ short name_ind;
+ short phone_ind;
+ };
+
+EXEC SQL TYPE c IS char reference;
+EXEC SQL TYPE ind IS union { int integer; short smallint; };
+EXEC SQL TYPE intarray IS int[AMOUNT];
+EXEC SQL TYPE str IS varchar[BUFFERSIZ];
+EXEC SQL TYPE string IS char[11];
+
+ Here is an example program that uses EXEC SQL
+ TYPE:
+
+EXEC SQL WHENEVER SQLERROR SQLPRINT;
+
+EXEC SQL TYPE tt IS
+ struct
+ {
+ varchar v[256];
+ int i;
+ };
+
+EXEC SQL TYPE tt_ind IS
+ struct ind {
+ short v_ind;
+ short i_ind;
+ };
+
+int
+main(void)
+{
+EXEC SQL BEGIN DECLARE SECTION;
+ tt t;
+ tt_ind t_ind;
+EXEC SQL END DECLARE SECTION;
+
+ EXEC SQL CONNECT TO testdb AS con1;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+
+ EXEC SQL SELECT current_database(), 256 INTO :t:t_ind LIMIT 1;
+
+ printf("t.v = %s\n", t.v.arr);
+ printf("t.i = %d\n", t.i);
+
+ printf("t_ind.v_ind = %d\n", t_ind.v_ind);
+ printf("t_ind.i_ind = %d\n", t_ind.i_ind);
+
+ EXEC SQL DISCONNECT con1;
+
+ return 0;
+}
+
+
+ The output from this program looks like this:
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-var.html b/pgsql/doc/postgresql/html/ecpg-sql-var.html
new file mode 100644
index 0000000000000000000000000000000000000000..c16713adafc48085cf38645ae0d59f257f65f681
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-var.html
@@ -0,0 +1,19 @@
+
+VAR
+Exec sql begin declare section;
+short a;
+exec sql end declare section;
+EXEC SQL VAR a IS int;
+
Compatibility
+ The VAR command is a PostgreSQL extension.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-sql-whenever.html b/pgsql/doc/postgresql/html/ecpg-sql-whenever.html
new file mode 100644
index 0000000000000000000000000000000000000000..4b601bac3d3cbdea11cec2425343a9dd048f6626
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-sql-whenever.html
@@ -0,0 +1,57 @@
+
+WHENEVER
WHENEVER — specify the action to be taken when an SQL statement causes a specific class condition to be raised
Synopsis
+WHENEVER { NOT FOUND | SQLERROR | SQLWARNING } action
+
Description
+ Define a behavior which is called on the special cases (Rows not
+ found, SQL warnings or errors) in the result of SQL execution.
+
Parameters
+ See Section 36.8.1 for a description of the
+ parameters.
+
Examples
+EXEC SQL WHENEVER NOT FOUND CONTINUE;
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+EXEC SQL WHENEVER NOT FOUND DO CONTINUE;
+EXEC SQL WHENEVER SQLWARNING SQLPRINT;
+EXEC SQL WHENEVER SQLWARNING DO warn();
+EXEC SQL WHENEVER SQLERROR sqlprint;
+EXEC SQL WHENEVER SQLERROR CALL print2();
+EXEC SQL WHENEVER SQLERROR DO handle_error("select");
+EXEC SQL WHENEVER SQLERROR DO sqlnotice(NULL, NONO);
+EXEC SQL WHENEVER SQLERROR DO sqlprint();
+EXEC SQL WHENEVER SQLERROR GOTO error_label;
+EXEC SQL WHENEVER SQLERROR STOP;
+
+ A typical application is the use of WHENEVER NOT FOUND
+ BREAK to handle looping through result sets:
+
+int
+main(void)
+{
+ EXEC SQL CONNECT TO testdb AS con1;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+ EXEC SQL ALLOCATE DESCRIPTOR d;
+ EXEC SQL DECLARE cur CURSOR FOR SELECT current_database(), 'hoge', 256;
+ EXEC SQL OPEN cur;
+
+ /* when end of result set reached, break out of while loop */
+ EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+ while (1)
+ {
+ EXEC SQL FETCH NEXT FROM cur INTO SQL DESCRIPTOR d;
+ ...
+ }
+
+ EXEC SQL CLOSE cur;
+ EXEC SQL COMMIT;
+
+ EXEC SQL DEALLOCATE DESCRIPTOR d;
+ EXEC SQL DISCONNECT ALL;
+
+ return 0;
+}
+
+
Compatibility
+ WHENEVER is specified in the SQL standard, but
+ most of the actions are PostgreSQL extensions.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg-variables.html b/pgsql/doc/postgresql/html/ecpg-variables.html
new file mode 100644
index 0000000000000000000000000000000000000000..636d901743c819fce5bd5b7445da11bc7c1b9111
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg-variables.html
@@ -0,0 +1,908 @@
+
+36.4. Using Host Variables
+ In Section 36.3 you saw how you can execute SQL
+ statements from an embedded SQL program. Some of those statements
+ only used fixed values and did not provide a way to insert
+ user-supplied values into statements or have the program process
+ the values returned by the query. Those kinds of statements are
+ not really useful in real applications. This section explains in
+ detail how you can pass data between your C program and the
+ embedded SQL statements using a simple mechanism called
+ host variables. In an embedded SQL program we
+ consider the SQL statements to be guests in the C
+ program code which is the host language. Therefore
+ the variables of the C program are called host
+ variables.
+
+ Another way to exchange values between PostgreSQL backends and ECPG
+ applications is the use of SQL descriptors, described
+ in Section 36.7.
+
+ Passing data between the C program and the SQL statements is
+ particularly simple in embedded SQL. Instead of having the
+ program paste the data into the statement, which entails various
+ complications, such as properly quoting the value, you can simply
+ write the name of a C variable into the SQL statement, prefixed by
+ a colon. For example:
+
+EXEC SQL INSERT INTO sometable VALUES (:v1, 'foo', :v2);
+
+ This statement refers to two C variables named
+ v1 and v2 and also uses a
+ regular SQL string literal, to illustrate that you are not
+ restricted to use one kind of data or the other.
+
+ This style of inserting C variables in SQL statements works
+ anywhere a value expression is expected in an SQL statement.
+
+ To pass data from the program to the database, for example as
+ parameters in a query, or to pass data from the database back to
+ the program, the C variables that are intended to contain this
+ data need to be declared in specially marked sections, so the
+ embedded SQL preprocessor is made aware of them.
+
+ This section starts with:
+
+EXEC SQL BEGIN DECLARE SECTION;
+
+ and ends with:
+
+EXEC SQL END DECLARE SECTION;
+
+ Between those lines, there must be normal C variable declarations,
+ such as:
+
+int x = 4;
+char foo[16], bar[16];
+
+ As you can see, you can optionally assign an initial value to the variable.
+ The variable's scope is determined by the location of its declaring
+ section within the program.
+ You can also declare variables with the following syntax which implicitly
+ creates a declare section:
+
+EXEC SQL int i = 4;
+
+ You can have as many declare sections in a program as you like.
+
+ The declarations are also echoed to the output file as normal C
+ variables, so there's no need to declare them again. Variables
+ that are not intended to be used in SQL commands can be declared
+ normally outside these special sections.
+
+ The definition of a structure or union also must be listed inside
+ a DECLARE section. Otherwise the preprocessor cannot
+ handle these types since it does not know the definition.
+
+ Now you should be able to pass data generated by your program into
+ an SQL command. But how do you retrieve the results of a query?
+ For that purpose, embedded SQL provides special variants of the
+ usual commands SELECT and
+ FETCH. These commands have a special
+ INTO clause that specifies which host variables
+ the retrieved values are to be stored in.
+ SELECT is used for a query that returns only
+ single row, and FETCH is used for a query that
+ returns multiple rows, using a cursor.
+
+ Here is an example:
+
+/*
+ * assume this table:
+ * CREATE TABLE test1 (a int, b varchar(50));
+ */
+
+EXEC SQL BEGIN DECLARE SECTION;
+int v1;
+VARCHAR v2;
+EXEC SQL END DECLARE SECTION;
+
+ ...
+
+EXEC SQL SELECT a, b INTO :v1, :v2 FROM test;
+
+ So the INTO clause appears between the select
+ list and the FROM clause. The number of
+ elements in the select list and the list after
+ INTO (also called the target list) must be
+ equal.
+
+ Here is an example using the command FETCH:
+
+EXEC SQL BEGIN DECLARE SECTION;
+int v1;
+VARCHAR v2;
+EXEC SQL END DECLARE SECTION;
+
+ ...
+
+EXEC SQL DECLARE foo CURSOR FOR SELECT a, b FROM test;
+
+ ...
+
+do
+{
+ ...
+ EXEC SQL FETCH NEXT FROM foo INTO :v1, :v2;
+ ...
+} while (...);
+
+ Here the INTO clause appears after all the
+ normal clauses.
+
+ When ECPG applications exchange values between the PostgreSQL
+ server and the C application, such as when retrieving query
+ results from the server or executing SQL statements with input
+ parameters, the values need to be converted between PostgreSQL
+ data types and host language variable types (C language data
+ types, concretely). One of the main points of ECPG is that it
+ takes care of this automatically in most cases.
+
+ In this respect, there are two kinds of data types: Some simple
+ PostgreSQL data types, such as integer
+ and text, can be read and written by the application
+ directly. Other PostgreSQL data types, such
+ as timestamp and numeric can only be
+ accessed through special library functions; see
+ Section 36.4.4.2.
+
+ Table 36.1 shows which PostgreSQL
+ data types correspond to which C data types. When you wish to
+ send or receive a value of a given PostgreSQL data type, you
+ should declare a C variable of the corresponding C data type in
+ the declare section.
+
Table 36.1. Mapping Between PostgreSQL Data Types and C Variable Types
+ To handle SQL character string data types, such
+ as varchar and text, there are two
+ possible ways to declare the host variables.
+
+ One way is using char[], an array
+ of char, which is the most common way to handle
+ character data in C.
+
+EXEC SQL BEGIN DECLARE SECTION;
+ char str[50];
+EXEC SQL END DECLARE SECTION;
+
+ Note that you have to take care of the length yourself. If you
+ use this host variable as the target variable of a query which
+ returns a string with more than 49 characters, a buffer overflow
+ occurs.
+
+ The other way is using the VARCHAR type, which is a
+ special type provided by ECPG. The definition on an array of
+ type VARCHAR is converted into a
+ named struct for every variable. A declaration like:
+
+VARCHAR var[180];
+
+ is converted into:
+
+struct varchar_var { int len; char arr[180]; } var;
+
+ The member arr hosts the string
+ including a terminating zero byte. Thus, to store a string in
+ a VARCHAR host variable, the host variable has to be
+ declared with the length including the zero byte terminator. The
+ member len holds the length of the
+ string stored in the arr without the
+ terminating zero byte. When a host variable is used as input for
+ a query, if strlen(arr)
+ and len are different, the shorter one
+ is used.
+
+ VARCHAR can be written in upper or lower case, but
+ not in mixed case.
+
+ char and VARCHAR host variables can
+ also hold values of other SQL types, which will be stored in
+ their string forms.
+
+ ECPG contains some special types that help you to interact easily
+ with some special data types from the PostgreSQL server. In
+ particular, it has implemented support for the
+ numeric, decimal, date, timestamp,
+ and interval types. These data types cannot usefully be
+ mapped to primitive host variable types (such
+ as int, long long int,
+ or char[]), because they have a complex internal
+ structure. Applications deal with these types by declaring host
+ variables in special types and accessing them using functions in
+ the pgtypes library. The pgtypes library, described in detail
+ in Section 36.6 contains basic functions to deal
+ with those types, such that you do not need to send a query to
+ the SQL server just for adding an interval to a time stamp for
+ example.
+
+ The follow subsections describe these special data types. For
+ more details about pgtypes library functions,
+ see Section 36.6.
+
+ Here is a pattern for handling timestamp variables
+ in the ECPG host application.
+
+ First, the program has to include the header file for the
+ timestamp type:
+
+#include <pgtypes_timestamp.h>
+
+
+ Next, declare a host variable as type timestamp in
+ the declare section:
+
+EXEC SQL BEGIN DECLARE SECTION;
+timestamp ts;
+EXEC SQL END DECLARE SECTION;
+
+
+ And after reading a value into the host variable, process it
+ using pgtypes library functions. In following example, the
+ timestamp value is converted into text (ASCII) form
+ with the PGTYPEStimestamp_to_asc()
+ function:
+
+ This example will show some result like following:
+
+ts = 2010-06-27 18:03:56.949343
+
+
+ In addition, the DATE type can be handled in the same way. The
+ program has to include pgtypes_date.h, declare a host variable
+ as the date type and convert a DATE value into a text form using
+ PGTYPESdate_to_asc() function. For more details about the
+ pgtypes library functions, see Section 36.6.
+
+ The handling of the interval type is also similar
+ to the timestamp and date types. It
+ is required, however, to allocate memory for
+ an interval type value explicitly. In other words,
+ the memory space for the variable has to be allocated in the
+ heap memory, not in the stack memory.
+
+ The handling of the numeric
+ and decimal types is similar to the
+ interval type: It requires defining a pointer,
+ allocating some memory space on the heap, and accessing the
+ variable using the pgtypes library functions. For more details
+ about the pgtypes library functions,
+ see Section 36.6.
+
+ No functions are provided specifically for
+ the decimal type. An application has to convert it
+ to a numeric variable using a pgtypes library
+ function to do further processing.
+
+ Here is an example program handling numeric
+ and decimal type variables.
+
+ The handling of the bytea type is similar to
+ that of VARCHAR. The definition on an array of type
+ bytea is converted into a named struct for every
+ variable. A declaration like:
+
+bytea var[180];
+
+ is converted into:
+
+struct bytea_var { int len; char arr[180]; } var;
+
+ The member arr hosts binary format
+ data. It can also handle '\0' as part of
+ data, unlike VARCHAR.
+ The data is converted from/to hex format and sent/received by
+ ecpglib.
+
Note
+ bytea variable can be used only when
+ bytea_output is set to hex.
+
36.4.4.3. Host Variables with Nonprimitive Types #
+ As a host variable you can also use arrays, typedefs, structs, and
+ pointers.
+
+ There are two use cases for arrays as host variables. The first
+ is a way to store some text string in char[]
+ or VARCHAR[], as
+ explained in Section 36.4.4.1. The second use case is to
+ retrieve multiple rows from a query result without using a
+ cursor. Without an array, to process a query result consisting
+ of multiple rows, it is required to use a cursor and
+ the FETCH command. But with array host
+ variables, multiple rows can be received at once. The length of
+ the array has to be defined to be able to accommodate all rows,
+ otherwise a buffer overflow will likely occur.
+
+ Following example scans the pg_database
+ system table and shows all OIDs and names of the available
+ databases:
+
+int
+main(void)
+{
+EXEC SQL BEGIN DECLARE SECTION;
+ int dbid[8];
+ char dbname[8][16];
+ int i;
+EXEC SQL END DECLARE SECTION;
+
+ memset(dbname, 0, sizeof(char)* 16 * 8);
+ memset(dbid, 0, sizeof(int) * 8);
+
+ EXEC SQL CONNECT TO testdb;
+ EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;
+
+ /* Retrieve multiple rows into arrays at once. */
+ EXEC SQL SELECT oid,datname INTO :dbid, :dbname FROM pg_database;
+
+ for (i = 0; i < 8; i++)
+ printf("oid=%d, dbname=%s\n", dbid[i], dbname[i]);
+
+ EXEC SQL COMMIT;
+ EXEC SQL DISCONNECT ALL;
+ return 0;
+}
+
+
+ This example shows following result. (The exact values depend on
+ local circumstances.)
+
+ A structure whose member names match the column names of a query
+ result, can be used to retrieve multiple columns at once. The
+ structure enables handling multiple column values in a single
+ host variable.
+
+ The following example retrieves OIDs, names, and sizes of the
+ available databases from the pg_database
+ system table and using
+ the pg_database_size() function. In this
+ example, a structure variable dbinfo_t with
+ members whose names match each column in
+ the SELECT result is used to retrieve one
+ result row without putting multiple host variables in
+ the FETCH statement.
+
+EXEC SQL BEGIN DECLARE SECTION;
+ typedef struct
+ {
+ int oid;
+ char datname[65];
+ long long int size;
+ } dbinfo_t;
+
+ dbinfo_t dbval;
+EXEC SQL END DECLARE SECTION;
+
+ memset(&dbval, 0, sizeof(dbinfo_t));
+
+ EXEC SQL DECLARE cur1 CURSOR FOR SELECT oid, datname, pg_database_size(oid) AS size FROM pg_database;
+ EXEC SQL OPEN cur1;
+
+ /* when end of result set reached, break out of while loop */
+ EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+ while (1)
+ {
+ /* Fetch multiple columns into one structure. */
+ EXEC SQL FETCH FROM cur1 INTO :dbval;
+
+ /* Print members of the structure. */
+ printf("oid=%d, datname=%s, size=%lld\n", dbval.oid, dbval.datname, dbval.size);
+ }
+
+ EXEC SQL CLOSE cur1;
+
+
+ This example shows following result. (The exact values depend on
+ local circumstances.)
+
+ Structure host variables “absorb” as many columns
+ as the structure as fields. Additional columns can be assigned
+ to other host variables. For example, the above program could
+ also be restructured like this, with the size
+ variable outside the structure:
+
+EXEC SQL BEGIN DECLARE SECTION;
+ typedef struct
+ {
+ int oid;
+ char datname[65];
+ } dbinfo_t;
+
+ dbinfo_t dbval;
+ long long int size;
+EXEC SQL END DECLARE SECTION;
+
+ memset(&dbval, 0, sizeof(dbinfo_t));
+
+ EXEC SQL DECLARE cur1 CURSOR FOR SELECT oid, datname, pg_database_size(oid) AS size FROM pg_database;
+ EXEC SQL OPEN cur1;
+
+ /* when end of result set reached, break out of while loop */
+ EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+ while (1)
+ {
+ /* Fetch multiple columns into one structure. */
+ EXEC SQL FETCH FROM cur1 INTO :dbval, :size;
+
+ /* Print members of the structure. */
+ printf("oid=%d, datname=%s, size=%lld\n", dbval.oid, dbval.datname, size);
+ }
+
+ EXEC SQL CLOSE cur1;
+
+ Use the typedef keyword to map new types to already
+ existing types.
+
+EXEC SQL BEGIN DECLARE SECTION;
+ typedef char mychartype[40];
+ typedef long serial_t;
+EXEC SQL END DECLARE SECTION;
+
+ Note that you could also use:
+
+EXEC SQL TYPE serial_t IS long;
+
+ This declaration does not need to be part of a declare section;
+ that is, you can also write typedefs as normal C statements.
+
+ Any word you declare as a typedef cannot be used as an SQL keyword
+ in EXEC SQL commands later in the same program.
+ For example, this won't work:
+
+EXEC SQL BEGIN DECLARE SECTION;
+ typedef int start;
+EXEC SQL END DECLARE SECTION;
+...
+EXEC SQL START TRANSACTION;
+
+ ECPG will report a syntax error for START
+ TRANSACTION, because it no longer
+ recognizes START as an SQL keyword,
+ only as a typedef.
+ (If you have such a conflict, and renaming the typedef
+ seems impractical, you could write the SQL command
+ using dynamic SQL.)
+
Note
+ In PostgreSQL releases before v16, use
+ of SQL keywords as typedef names was likely to result in syntax
+ errors associated with use of the typedef itself, rather than use
+ of the name as an SQL keyword. The new behavior is less likely to
+ cause problems when an existing ECPG application is recompiled in
+ a new PostgreSQL release with new
+ keywords.
+
+ You can declare pointers to the most common types. Note however
+ that you cannot use pointers as target variables of queries
+ without auto-allocation. See Section 36.7
+ for more information on auto-allocation.
+
+
+EXEC SQL BEGIN DECLARE SECTION;
+ int *intp;
+ char **charp;
+EXEC SQL END DECLARE SECTION;
+
+ This section contains information on how to handle nonscalar and
+ user-defined SQL-level data types in ECPG applications. Note that
+ this is distinct from the handling of host variables of
+ nonprimitive types, described in the previous section.
+
+ Multi-dimensional SQL-level arrays are not directly supported in ECPG.
+ One-dimensional SQL-level arrays can be mapped into C array host
+ variables and vice-versa. However, when creating a statement ecpg does
+ not know the types of the columns, so that it cannot check if a C array
+ is input into a corresponding SQL-level array. When processing the
+ output of an SQL statement, ecpg has the necessary information and thus
+ checks if both are arrays.
+
+ If a query accesses elements of an array
+ separately, then this avoids the use of arrays in ECPG. Then, a
+ host variable with a type that can be mapped to the element type
+ should be used. For example, if a column type is array of
+ integer, a host variable of type int
+ can be used. Also if the element type is varchar
+ or text, a host variable of type char[]
+ or VARCHAR[] can be used.
+
+ Here is an example. Assume the following table:
+
+CREATE TABLE t3 (
+ ii integer[]
+);
+
+testdb=> SELECT * FROM t3;
+ ii
+-------------
+ {1,2,3,4,5}
+(1 row)
+
+
+ The following example program retrieves the 4th element of the
+ array and stores it into a host variable of
+ type int:
+
+EXEC SQL BEGIN DECLARE SECTION;
+int ii;
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii[4] FROM t3;
+EXEC SQL OPEN cur1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ EXEC SQL FETCH FROM cur1 INTO :ii ;
+ printf("ii=%d\n", ii);
+}
+
+EXEC SQL CLOSE cur1;
+
+
+ This example shows the following result:
+
+ii=4
+
+
+ To map multiple array elements to the multiple elements in an
+ array type host variables each element of array column and each
+ element of the host variable array have to be managed separately,
+ for example:
+
+EXEC SQL BEGIN DECLARE SECTION;
+int ii_a[8];
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii[1], ii[2], ii[3], ii[4] FROM t3;
+EXEC SQL OPEN cur1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ EXEC SQL FETCH FROM cur1 INTO :ii_a[0], :ii_a[1], :ii_a[2], :ii_a[3];
+ ...
+}
+
+
+ Note again that
+
+EXEC SQL BEGIN DECLARE SECTION;
+int ii_a[8];
+EXEC SQL END DECLARE SECTION;
+
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT ii FROM t3;
+EXEC SQL OPEN cur1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ /* WRONG */
+ EXEC SQL FETCH FROM cur1 INTO :ii_a;
+ ...
+}
+
+ would not work correctly in this case, because you cannot map an
+ array type column to an array host variable directly.
+
+ Another workaround is to store arrays in their external string
+ representation in host variables of type char[]
+ or VARCHAR[]. For more details about this
+ representation, see Section 8.15.2. Note that
+ this means that the array cannot be accessed naturally as an
+ array in the host program (without further processing that parses
+ the text representation).
+
+ Composite types are not directly supported in ECPG, but an easy workaround is possible.
+ The
+ available workarounds are similar to the ones described for
+ arrays above: Either access each attribute separately or use the
+ external string representation.
+
+ For the following examples, assume the following type and table:
+
+CREATE TYPE comp_t AS (intval integer, textval varchar(32));
+CREATE TABLE t4 (compval comp_t);
+INSERT INTO t4 VALUES ( (256, 'PostgreSQL') );
+
+
+ The most obvious solution is to access each attribute separately.
+ The following program retrieves data from the example table by
+ selecting each attribute of the type comp_t
+ separately:
+
+EXEC SQL BEGIN DECLARE SECTION;
+int intval;
+varchar textval[33];
+EXEC SQL END DECLARE SECTION;
+
+/* Put each element of the composite type column in the SELECT list. */
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).intval, (compval).textval FROM t4;
+EXEC SQL OPEN cur1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ /* Fetch each element of the composite type column into host variables. */
+ EXEC SQL FETCH FROM cur1 INTO :intval, :textval;
+
+ printf("intval=%d, textval=%s\n", intval, textval.arr);
+}
+
+EXEC SQL CLOSE cur1;
+
+
+ To enhance this example, the host variables to store values in
+ the FETCH command can be gathered into one
+ structure. For more details about the host variable in the
+ structure form, see Section 36.4.4.3.2.
+ To switch to the structure, the example can be modified as below.
+ The two host variables, intval
+ and textval, become members of
+ the comp_t structure, and the structure
+ is specified on the FETCH command.
+
+EXEC SQL BEGIN DECLARE SECTION;
+typedef struct
+{
+ int intval;
+ varchar textval[33];
+} comp_t;
+
+comp_t compval;
+EXEC SQL END DECLARE SECTION;
+
+/* Put each element of the composite type column in the SELECT list. */
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).intval, (compval).textval FROM t4;
+EXEC SQL OPEN cur1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ /* Put all values in the SELECT list into one structure. */
+ EXEC SQL FETCH FROM cur1 INTO :compval;
+
+ printf("intval=%d, textval=%s\n", compval.intval, compval.textval.arr);
+}
+
+EXEC SQL CLOSE cur1;
+
+
+ Although a structure is used in the FETCH
+ command, the attribute names in the SELECT
+ clause are specified one by one. This can be enhanced by using
+ a * to ask for all attributes of the composite
+ type value.
+
+...
+EXEC SQL DECLARE cur1 CURSOR FOR SELECT (compval).* FROM t4;
+EXEC SQL OPEN cur1;
+
+EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+while (1)
+{
+ /* Put all values in the SELECT list into one structure. */
+ EXEC SQL FETCH FROM cur1 INTO :compval;
+
+ printf("intval=%d, textval=%s\n", compval.intval, compval.textval.arr);
+}
+...
+
+ This way, composite types can be mapped into structures almost
+ seamlessly, even though ECPG does not understand the composite
+ type itself.
+
+ Finally, it is also possible to store composite type values in
+ their external string representation in host variables of
+ type char[] or VARCHAR[]. But that
+ way, it is not easily possible to access the fields of the value
+ from the host program.
+
+ New user-defined base types are not directly supported by ECPG.
+ You can use the external string representation and host variables
+ of type char[] or VARCHAR[], and this
+ solution is indeed appropriate and sufficient for many types.
+
+ Here is an example using the data type complex from
+ the example in Section 38.13. The external string
+ representation of that type is (%f,%f),
+ which is defined in the
+ functions complex_in()
+ and complex_out() functions
+ in Section 38.13. The following example inserts the
+ complex type values (1,1)
+ and (3,3) into the
+ columns a and b, and select
+ them from the table after that.
+
+
+EXEC SQL BEGIN DECLARE SECTION;
+ varchar a[64];
+ varchar b[64];
+EXEC SQL END DECLARE SECTION;
+
+ EXEC SQL INSERT INTO test_complex VALUES ('(1,1)', '(3,3)');
+
+ EXEC SQL DECLARE cur1 CURSOR FOR SELECT a, b FROM test_complex;
+ EXEC SQL OPEN cur1;
+
+ EXEC SQL WHENEVER NOT FOUND DO BREAK;
+
+ while (1)
+ {
+ EXEC SQL FETCH FROM cur1 INTO :a, :b;
+ printf("a=%s, b=%s\n", a.arr, b.arr);
+ }
+
+ EXEC SQL CLOSE cur1;
+
+
+ This example shows following result:
+
+a=(1,1), b=(3,3)
+
+
+ Another workaround is avoiding the direct use of the user-defined
+ types in ECPG and instead create a function or cast that converts
+ between the user-defined type and a primitive type that ECPG can
+ handle. Note, however, that type casts, especially implicit
+ ones, should be introduced into the type system very carefully.
+
+ The examples above do not handle null values. In fact, the
+ retrieval examples will raise an error if they fetch a null value
+ from the database. To be able to pass null values to the database
+ or retrieve null values from the database, you need to append a
+ second host variable specification to each host variable that
+ contains data. This second host variable is called the
+ indicator and contains a flag that tells
+ whether the datum is null, in which case the value of the real
+ host variable is ignored. Here is an example that handles the
+ retrieval of null values correctly:
+
+EXEC SQL BEGIN DECLARE SECTION;
+VARCHAR val;
+int val_ind;
+EXEC SQL END DECLARE SECTION:
+
+ ...
+
+EXEC SQL SELECT b INTO :val :val_ind FROM test1;
+
+ The indicator variable val_ind will be zero if
+ the value was not null, and it will be negative if the value was
+ null. (See Section 36.16 to enable
+ Oracle-specific behavior.)
+
+ The indicator has another function: if the indicator value is
+ positive, it means that the value is not null, but it was
+ truncated when it was stored in the host variable.
+
+ If the argument -r no_indicator is passed to
+ the preprocessor ecpg, it works in
+ “no-indicator” mode. In no-indicator mode, if no
+ indicator variable is specified, null values are signaled (on
+ input and output) for character string types as empty string and
+ for integer types as the lowest possible value for type (for
+ example, INT_MIN for int).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/ecpg.html b/pgsql/doc/postgresql/html/ecpg.html
new file mode 100644
index 0000000000000000000000000000000000000000..9779e8e8811041aa0c1e1c55450574b00f0b488a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/ecpg.html
@@ -0,0 +1,13 @@
+
+Chapter 36. ECPG — Embedded SQL in C
+ This chapter describes the embedded SQL package
+ for PostgreSQL. It was written by
+ Linus Tolke (<linus@epact.se>) and Michael Meskes
+ (<meskes@postgresql.org>). Originally it was written to work with
+ C. It also works with C++, but
+ it does not recognize all C++ constructs yet.
+
+ This documentation is quite incomplete. But since this
+ interface is standardized, additional information can be found in
+ many resources about SQL.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/encryption-options.html b/pgsql/doc/postgresql/html/encryption-options.html
new file mode 100644
index 0000000000000000000000000000000000000000..0c97a93e268e79feb7b4b3b935c4d95711ae41d2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/encryption-options.html
@@ -0,0 +1,84 @@
+
+19.8. Encryption Options
+ PostgreSQL offers encryption at several
+ levels, and provides flexibility in protecting data from disclosure
+ due to database server theft, unscrupulous administrators, and
+ insecure networks. Encryption might also be required to secure
+ sensitive data such as medical records or financial transactions.
+
Password Encryption
+ Database user passwords are stored as hashes (determined by the setting
+ password_encryption), so the administrator cannot
+ determine the actual password assigned to the user. If SCRAM or MD5
+ encryption is used for client authentication, the unencrypted password is
+ never even temporarily present on the server because the client encrypts
+ it before being sent across the network. SCRAM is preferred, because it
+ is an Internet standard and is more secure than the PostgreSQL-specific
+ MD5 authentication protocol.
+
Encryption For Specific Columns
+ The pgcrypto module allows certain fields to be
+ stored encrypted.
+ This is useful if only some of the data is sensitive.
+ The client supplies the decryption key and the data is decrypted
+ on the server and then sent to the client.
+
+ The decrypted data and the decryption key are present on the
+ server for a brief time while it is being decrypted and
+ communicated between the client and server. This presents a brief
+ moment where the data and keys can be intercepted by someone with
+ complete access to the database server, such as the system
+ administrator.
+
Data Partition Encryption
+ Storage encryption can be performed at the file system level or the
+ block level. Linux file system encryption options include eCryptfs
+ and EncFS, while FreeBSD uses PEFS. Block level or full disk
+ encryption options include dm-crypt + LUKS on Linux and GEOM
+ modules geli and gbde on FreeBSD. Many other operating systems
+ support this functionality, including Windows.
+
+ This mechanism prevents unencrypted data from being read from the
+ drives if the drives or the entire computer is stolen. This does
+ not protect against attacks while the file system is mounted,
+ because when mounted, the operating system provides an unencrypted
+ view of the data. However, to mount the file system, you need some
+ way for the encryption key to be passed to the operating system,
+ and sometimes the key is stored somewhere on the host that mounts
+ the disk.
+
Encrypting Data Across A Network
+ SSL connections encrypt all data sent across the network: the
+ password, the queries, and the data returned. The
+ pg_hba.conf file allows administrators to specify
+ which hosts can use non-encrypted connections (host)
+ and which require SSL-encrypted connections
+ (hostssl). Also, clients can specify that they
+ connect to servers only via SSL.
+
+ GSSAPI-encrypted connections encrypt all data sent across the network,
+ including queries and data returned. (No password is sent across the
+ network.) The pg_hba.conf file allows
+ administrators to specify which hosts can use non-encrypted connections
+ (host) and which require GSSAPI-encrypted connections
+ (hostgssenc). Also, clients can specify that they
+ connect to servers only on GSSAPI-encrypted connections
+ (gssencmode=require).
+
+ Stunnel or
+ SSH can also be used to encrypt
+ transmissions.
+
SSL Host Authentication
+ It is possible for both the client and server to provide SSL
+ certificates to each other. It takes some extra configuration
+ on each side, but this provides stronger verification of identity
+ than the mere use of passwords. It prevents a computer from
+ pretending to be the server just long enough to read the password
+ sent by the client. It also helps prevent “man in the middle”
+ attacks where a computer between the client and server pretends to
+ be the server and reads and passes all data between the client and
+ server.
+
Client-Side Encryption
+ If the system administrator for the server's machine cannot be trusted,
+ it is necessary
+ for the client to encrypt the data; this way, unencrypted data
+ never appears on the database server. Data is encrypted on the
+ client before being sent to the server, and database results have
+ to be decrypted on the client before being used.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/errcodes-appendix.html b/pgsql/doc/postgresql/html/errcodes-appendix.html
new file mode 100644
index 0000000000000000000000000000000000000000..d9acaac7ad8c00fae400192aac3fde5d14ebe331
--- /dev/null
+++ b/pgsql/doc/postgresql/html/errcodes-appendix.html
@@ -0,0 +1,45 @@
+
+Appendix A. PostgreSQL Error Codes
+ All messages emitted by the PostgreSQL
+ server are assigned five-character error codes that follow the SQL
+ standard's conventions for “SQLSTATE” codes. Applications
+ that need to know which error condition has occurred should usually
+ test the error code, rather than looking at the textual error
+ message. The error codes are less likely to change across
+ PostgreSQL releases, and also are not subject to
+ change due to localization of error messages. Note that some, but
+ not all, of the error codes produced by PostgreSQL
+ are defined by the SQL standard; some additional error codes for
+ conditions not defined by the standard have been invented or
+ borrowed from other databases.
+
+ According to the standard, the first two characters of an error code
+ denote a class of errors, while the last three characters indicate
+ a specific condition within that class. Thus, an application that
+ does not recognize the specific error code might still be able to infer
+ what to do from the error class.
+
+ Table A.1 lists all the error codes defined in
+ PostgreSQL 16.3. (Some are not actually
+ used at present, but are defined by the SQL standard.)
+ The error classes are also shown. For each error class there is a
+ “standard” error code having the last three characters
+ 000. This code is used only for error conditions that fall
+ within the class but do not have any more-specific code assigned.
+
+ The symbol shown in the column “Condition Name” is
+ the condition name to use in PL/pgSQL. Condition
+ names can be written in either upper or lower case. (Note that
+ PL/pgSQL does not recognize warning, as opposed to error,
+ condition names; those are classes 00, 01, and 02.)
+
+ For some types of errors, the server reports the name of a database object
+ (a table, table column, data type, or constraint) associated with the error;
+ for example, the name of the unique constraint that caused a
+ unique_violation error. Such names are supplied in separate
+ fields of the error report message so that applications need not try to
+ extract them from the possibly-localized human-readable text of the message.
+ As of PostgreSQL 9.3, complete coverage for this feature
+ exists only for errors in SQLSTATE class 23 (integrity constraint
+ violation), but this is likely to be expanded in future.
+
Table A.1. PostgreSQL Error Codes
Error Code
Condition Name
Class 00 — Successful Completion
00000
successful_completion
Class 01 — Warning
01000
warning
0100C
dynamic_result_sets_returned
01008
implicit_zero_bit_padding
01003
null_value_eliminated_in_set_function
01007
privilege_not_granted
01006
privilege_not_revoked
01004
string_data_right_truncation
01P01
deprecated_feature
Class 02 — No Data (this is also a warning class per the SQL standard)
Class 2B — Dependent Privilege Descriptors Still Exist
2B000
dependent_privilege_descriptors_still_exist
2BP01
dependent_objects_still_exist
Class 2D — Invalid Transaction Termination
2D000
invalid_transaction_termination
Class 2F — SQL Routine Exception
2F000
sql_routine_exception
2F005
function_executed_no_return_statement
2F002
modifying_sql_data_not_permitted
2F003
prohibited_sql_statement_attempted
2F004
reading_sql_data_not_permitted
Class 34 — Invalid Cursor Name
34000
invalid_cursor_name
Class 38 — External Routine Exception
38000
external_routine_exception
38001
containing_sql_not_permitted
38002
modifying_sql_data_not_permitted
38003
prohibited_sql_statement_attempted
38004
reading_sql_data_not_permitted
Class 39 — External Routine Invocation Exception
39000
external_routine_invocation_exception
39001
invalid_sqlstate_returned
39004
null_value_not_allowed
39P01
trigger_protocol_violated
39P02
srf_protocol_violated
39P03
event_trigger_protocol_violated
Class 3B — Savepoint Exception
3B000
savepoint_exception
3B001
invalid_savepoint_specification
Class 3D — Invalid Catalog Name
3D000
invalid_catalog_name
Class 3F — Invalid Schema Name
3F000
invalid_schema_name
Class 40 — Transaction Rollback
40000
transaction_rollback
40002
transaction_integrity_constraint_violation
40001
serialization_failure
40003
statement_completion_unknown
40P01
deadlock_detected
Class 42 — Syntax Error or Access Rule Violation
42000
syntax_error_or_access_rule_violation
42601
syntax_error
42501
insufficient_privilege
42846
cannot_coerce
42803
grouping_error
42P20
windowing_error
42P19
invalid_recursion
42830
invalid_foreign_key
42602
invalid_name
42622
name_too_long
42939
reserved_name
42804
datatype_mismatch
42P18
indeterminate_datatype
42P21
collation_mismatch
42P22
indeterminate_collation
42809
wrong_object_type
428C9
generated_always
42703
undefined_column
42883
undefined_function
42P01
undefined_table
42P02
undefined_parameter
42704
undefined_object
42701
duplicate_column
42P03
duplicate_cursor
42P04
duplicate_database
42723
duplicate_function
42P05
duplicate_prepared_statement
42P06
duplicate_schema
42P07
duplicate_table
42712
duplicate_alias
42710
duplicate_object
42702
ambiguous_column
42725
ambiguous_function
42P08
ambiguous_parameter
42P09
ambiguous_alias
42P10
invalid_column_reference
42611
invalid_column_definition
42P11
invalid_cursor_definition
42P12
invalid_database_definition
42P13
invalid_function_definition
42P14
invalid_prepared_statement_definition
42P15
invalid_schema_definition
42P16
invalid_table_definition
42P17
invalid_object_definition
Class 44 — WITH CHECK OPTION Violation
44000
with_check_option_violation
Class 53 — Insufficient Resources
53000
insufficient_resources
53100
disk_full
53200
out_of_memory
53300
too_many_connections
53400
configuration_limit_exceeded
Class 54 — Program Limit Exceeded
54000
program_limit_exceeded
54001
statement_too_complex
54011
too_many_columns
54023
too_many_arguments
Class 55 — Object Not In Prerequisite State
55000
object_not_in_prerequisite_state
55006
object_in_use
55P02
cant_change_runtime_param
55P03
lock_not_available
55P04
unsafe_new_enum_value_usage
Class 57 — Operator Intervention
57000
operator_intervention
57014
query_canceled
57P01
admin_shutdown
57P02
crash_shutdown
57P03
cannot_connect_now
57P04
database_dropped
57P05
idle_session_timeout
Class 58 — System Error (errors external to PostgreSQL itself)
58000
system_error
58030
io_error
58P01
undefined_file
58P02
duplicate_file
Class 72 — Snapshot Failure
72000
snapshot_too_old
Class F0 — Configuration File Error
F0000
config_file_error
F0001
lock_file_exists
Class HV — Foreign Data Wrapper Error (SQL/MED)
HV000
fdw_error
HV005
fdw_column_name_not_found
HV002
fdw_dynamic_parameter_value_needed
HV010
fdw_function_sequence_error
HV021
fdw_inconsistent_descriptor_information
HV024
fdw_invalid_attribute_value
HV007
fdw_invalid_column_name
HV008
fdw_invalid_column_number
HV004
fdw_invalid_data_type
HV006
fdw_invalid_data_type_descriptors
HV091
fdw_invalid_descriptor_field_identifier
HV00B
fdw_invalid_handle
HV00C
fdw_invalid_option_index
HV00D
fdw_invalid_option_name
HV090
fdw_invalid_string_length_or_buffer_length
HV00A
fdw_invalid_string_format
HV009
fdw_invalid_use_of_null_pointer
HV014
fdw_too_many_handles
HV001
fdw_out_of_memory
HV00P
fdw_no_schemas
HV00J
fdw_option_name_not_found
HV00K
fdw_reply_handle
HV00Q
fdw_schema_not_found
HV00R
fdw_table_not_found
HV00L
fdw_unable_to_create_execution
HV00M
fdw_unable_to_create_reply
HV00N
fdw_unable_to_establish_connection
Class P0 — PL/pgSQL Error
P0000
plpgsql_error
P0001
raise_exception
P0002
no_data_found
P0003
too_many_rows
P0004
assert_failure
Class XX — Internal Error
XX000
internal_error
XX001
data_corrupted
XX002
index_corrupted
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/error-message-reporting.html b/pgsql/doc/postgresql/html/error-message-reporting.html
new file mode 100644
index 0000000000000000000000000000000000000000..47b2863da47464805d6544b0cf33941985398193
--- /dev/null
+++ b/pgsql/doc/postgresql/html/error-message-reporting.html
@@ -0,0 +1,250 @@
+
+56.2. Reporting Errors Within the Server
+ Error, warning, and log messages generated within the server code
+ should be created using ereport, or its older cousin
+ elog. The use of this function is complex enough to
+ require some explanation.
+
+ There are two required elements for every message: a severity level
+ (ranging from DEBUG to PANIC) and a primary
+ message text. In addition there are optional elements, the most
+ common of which is an error identifier code that follows the SQL spec's
+ SQLSTATE conventions.
+ ereport itself is just a shell macro that exists
+ mainly for the syntactic convenience of making message generation
+ look like a single function call in the C source code. The only parameter
+ accepted directly by ereport is the severity level.
+ The primary message text and any optional message elements are
+ generated by calling auxiliary functions, such as errmsg,
+ within the ereport call.
+
+ A typical call to ereport might look like this:
+
+ereport(ERROR,
+ errcode(ERRCODE_DIVISION_BY_ZERO),
+ errmsg("division by zero"));
+
+ This specifies error severity level ERROR (a run-of-the-mill
+ error). The errcode call specifies the SQLSTATE error code
+ using a macro defined in src/include/utils/errcodes.h. The
+ errmsg call provides the primary message text.
+
+ You will also frequently see this older style, with an extra set of
+ parentheses surrounding the auxiliary function calls:
+
+ereport(ERROR,
+ (errcode(ERRCODE_DIVISION_BY_ZERO),
+ errmsg("division by zero")));
+
+ The extra parentheses were required
+ before PostgreSQL version 12, but are now
+ optional.
+
+ Here is a more complex example:
+
+ereport(ERROR,
+ errcode(ERRCODE_AMBIGUOUS_FUNCTION),
+ errmsg("function %s is not unique",
+ func_signature_string(funcname, nargs,
+ NIL, actual_arg_types)),
+ errhint("Unable to choose a best candidate function. "
+ "You might need to add explicit typecasts."));
+
+ This illustrates the use of format codes to embed run-time values into
+ a message text. Also, an optional “hint” message is provided.
+ The auxiliary function calls can be written in any order, but
+ conventionally errcode
+ and errmsg appear first.
+
+ If the severity level is ERROR or higher,
+ ereport aborts execution of the current query
+ and does not return to the caller. If the severity level is
+ lower than ERROR, ereport returns normally.
+
+ The available auxiliary routines for ereport are:
+
+ errcode(sqlerrcode) specifies the SQLSTATE error identifier
+ code for the condition. If this routine is not called, the error
+ identifier defaults to
+ ERRCODE_INTERNAL_ERROR when the error severity level is
+ ERROR or higher, ERRCODE_WARNING when the
+ error level is WARNING, otherwise (for NOTICE
+ and below) ERRCODE_SUCCESSFUL_COMPLETION.
+ While these defaults are often convenient, always think whether they
+ are appropriate before omitting the errcode() call.
+
+ errmsg(const char *msg, ...) specifies the primary error
+ message text, and possibly run-time values to insert into it. Insertions
+ are specified by sprintf-style format codes. In addition to
+ the standard format codes accepted by sprintf, the format
+ code %m can be used to insert the error message returned
+ by strerror for the current value of errno.
+ [16]
+ %m does not require any
+ corresponding entry in the parameter list for errmsg.
+ Note that the message string will be run through gettext
+ for possible localization before format codes are processed.
+
+ errmsg_internal(const char *msg, ...) is the same as
+ errmsg, except that the message string will not be
+ translated nor included in the internationalization message dictionary.
+ This should be used for “cannot happen” cases that are probably
+ not worth expending translation effort on.
+
+ errmsg_plural(const char *fmt_singular, const char *fmt_plural,
+ unsigned long n, ...) is like errmsg, but with
+ support for various plural forms of the message.
+ fmt_singular is the English singular format,
+ fmt_plural is the English plural format,
+ n is the integer value that determines which plural
+ form is needed, and the remaining arguments are formatted according
+ to the selected format string. For more information see
+ Section 57.2.2.
+
+ errdetail(const char *msg, ...) supplies an optional
+ “detail” message; this is to be used when there is additional
+ information that seems inappropriate to put in the primary message.
+ The message string is processed in just the same way as for
+ errmsg.
+
+ errdetail_internal(const char *msg, ...) is the same
+ as errdetail, except that the message string will not be
+ translated nor included in the internationalization message dictionary.
+ This should be used for detail messages that are not worth expending
+ translation effort on, for instance because they are too technical to be
+ useful to most users.
+
+ errdetail_plural(const char *fmt_singular, const char *fmt_plural,
+ unsigned long n, ...) is like errdetail, but with
+ support for various plural forms of the message.
+ For more information see Section 57.2.2.
+
+ errdetail_log(const char *msg, ...) is the same as
+ errdetail except that this string goes only to the server
+ log, never to the client. If both errdetail (or one of
+ its equivalents above) and
+ errdetail_log are used then one string goes to the client
+ and the other to the log. This is useful for error details that are
+ too security-sensitive or too bulky to include in the report
+ sent to the client.
+
+ errdetail_log_plural(const char *fmt_singular, const char
+ *fmt_plural, unsigned long n, ...) is like
+ errdetail_log, but with support for various plural forms of
+ the message.
+ For more information see Section 57.2.2.
+
+ errhint(const char *msg, ...) supplies an optional
+ “hint” message; this is to be used when offering suggestions
+ about how to fix the problem, as opposed to factual details about
+ what went wrong.
+ The message string is processed in just the same way as for
+ errmsg.
+
+ errhint_plural(const char *fmt_singular, const char *fmt_plural,
+ unsigned long n, ...) is like errhint, but with
+ support for various plural forms of the message.
+ For more information see Section 57.2.2.
+
+ errcontext(const char *msg, ...) is not normally called
+ directly from an ereport message site; rather it is used
+ in error_context_stack callback functions to provide
+ information about the context in which an error occurred, such as the
+ current location in a PL function.
+ The message string is processed in just the same way as for
+ errmsg. Unlike the other auxiliary functions, this can
+ be called more than once per ereport call; the successive
+ strings thus supplied are concatenated with separating newlines.
+
+ errposition(int cursorpos) specifies the textual location
+ of an error within a query string. Currently it is only useful for
+ errors detected in the lexical and syntactic analysis phases of
+ query processing.
+
+ errtable(Relation rel) specifies a relation whose
+ name and schema name should be included as auxiliary fields in the error
+ report.
+
+ errtablecol(Relation rel, int attnum) specifies
+ a column whose name, table name, and schema name should be included as
+ auxiliary fields in the error report.
+
+ errtableconstraint(Relation rel, const char *conname)
+ specifies a table constraint whose name, table name, and schema name
+ should be included as auxiliary fields in the error report. Indexes
+ should be considered to be constraints for this purpose, whether or
+ not they have an associated pg_constraint entry. Be
+ careful to pass the underlying heap relation, not the index itself, as
+ rel.
+
+ errdatatype(Oid datatypeOid) specifies a data
+ type whose name and schema name should be included as auxiliary fields
+ in the error report.
+
+ errdomainconstraint(Oid datatypeOid, const char *conname)
+ specifies a domain constraint whose name, domain name, and schema name
+ should be included as auxiliary fields in the error report.
+
+ errcode_for_file_access() is a convenience function that
+ selects an appropriate SQLSTATE error identifier for a failure in a
+ file-access-related system call. It uses the saved
+ errno to determine which error code to generate.
+ Usually this should be used in combination with %m in the
+ primary error message text.
+
+ errcode_for_socket_access() is a convenience function that
+ selects an appropriate SQLSTATE error identifier for a failure in a
+ socket-related system call.
+
+ errhidestmt(bool hide_stmt) can be called to specify
+ suppression of the STATEMENT: portion of a message in the
+ postmaster log. Generally this is appropriate if the message text
+ includes the current statement already.
+
+ errhidecontext(bool hide_ctx) can be called to
+ specify suppression of the CONTEXT: portion of a message in
+ the postmaster log. This should only be used for verbose debugging
+ messages where the repeated inclusion of context would bloat the log
+ too much.
+
+
Note
+ At most one of the functions errtable,
+ errtablecol, errtableconstraint,
+ errdatatype, or errdomainconstraint should
+ be used in an ereport call. These functions exist to
+ allow applications to extract the name of a database object associated
+ with the error condition without having to examine the
+ potentially-localized error message text.
+ These functions should be used in error reports for which it's likely
+ that applications would wish to have automatic error handling. As of
+ PostgreSQL 9.3, complete coverage exists only for
+ errors in SQLSTATE class 23 (integrity constraint violation), but this
+ is likely to be expanded in future.
+
+ There is an older function elog that is still heavily used.
+ An elog call:
+
+ Notice that the SQLSTATE error code is always defaulted, and the message
+ string is not subject to translation.
+ Therefore, elog should be used only for internal errors and
+ low-level debug logging. Any message that is likely to be of interest to
+ ordinary users should go through ereport. Nonetheless,
+ there are enough internal “cannot happen” error checks in the
+ system that elog is still widely used; it is preferred for
+ those messages for its notational simplicity.
+
+ Advice about writing good error messages can be found in
+ Section 56.3.
+
[16]
+ That is, the value that was current when the ereport call
+ was reached; changes of errno within the auxiliary reporting
+ routines will not affect it. That would not be true if you were to
+ write strerror(errno) explicitly in errmsg's
+ parameter list; accordingly, do not do so.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/error-style-guide.html b/pgsql/doc/postgresql/html/error-style-guide.html
new file mode 100644
index 0000000000000000000000000000000000000000..2ae9328640fb41bc08e2c38e6cb9bab993af505b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/error-style-guide.html
@@ -0,0 +1,250 @@
+
+56.3. Error Message Style Guide
+ The primary message should be short, factual, and avoid reference to
+ implementation details such as specific function names.
+ “Short” means “should fit on one line under normal
+ conditions”. Use a detail message if needed to keep the primary
+ message short, or if you feel a need to mention implementation details
+ such as the particular system call that failed. Both primary and detail
+ messages should be factual. Use a hint message for suggestions about what
+ to do to fix the problem, especially if the suggestion might not always be
+ applicable.
+
+ For example, instead of:
+
+IpcMemoryCreate: shmget(key=%d, size=%u, 0%o) failed: %m
+(plus a long addendum that is basically a hint)
+
+ write:
+
+Primary: could not create shared memory segment: %m
+Detail: Failed syscall was shmget(key=%d, size=%u, 0%o).
+Hint: the addendum
+
+
+ Rationale: keeping the primary message short helps keep it to the point,
+ and lets clients lay out screen space on the assumption that one line is
+ enough for error messages. Detail and hint messages can be relegated to a
+ verbose mode, or perhaps a pop-up error-details window. Also, details and
+ hints would normally be suppressed from the server log to save
+ space. Reference to implementation details is best avoided since users
+ aren't expected to know the details.
+
+ Don't put any specific assumptions about formatting into the message
+ texts. Expect clients and the server log to wrap lines to fit their own
+ needs. In long messages, newline characters (\n) can be used to indicate
+ suggested paragraph breaks. Don't end a message with a newline. Don't
+ use tabs or other formatting characters. (In error context displays,
+ newlines are automatically added to separate levels of context such as
+ function calls.)
+
+ Rationale: Messages are not necessarily displayed on terminal-type
+ displays. In GUI displays or browsers these formatting instructions are
+ at best ignored.
+
+ English text should use double quotes when quoting is appropriate.
+ Text in other languages should consistently use one kind of quotes that is
+ consistent with publishing customs and computer output of other programs.
+
+ Rationale: The choice of double quotes over single quotes is somewhat
+ arbitrary, but tends to be the preferred use. Some have suggested
+ choosing the kind of quotes depending on the type of object according to
+ SQL conventions (namely, strings single quoted, identifiers double
+ quoted). But this is a language-internal technical issue that many users
+ aren't even familiar with, it won't scale to other kinds of quoted terms,
+ it doesn't translate to other languages, and it's pretty pointless, too.
+
+ Always use quotes to delimit file names, user-supplied identifiers, and
+ other variables that might contain words. Do not use them to mark up
+ variables that will not contain words (for example, operator names).
+
+ There are functions in the backend that will double-quote their own output
+ as needed (for example, format_type_be()). Do not put
+ additional quotes around the output of such functions.
+
+ Rationale: Objects can have names that create ambiguity when embedded in a
+ message. Be consistent about denoting where a plugged-in name starts and
+ ends. But don't clutter messages with unnecessary or duplicate quote
+ marks.
+
+ The rules are different for primary error messages and for detail/hint
+ messages:
+
+ Primary error messages: Do not capitalize the first letter. Do not end a
+ message with a period. Do not even think about ending a message with an
+ exclamation point.
+
+ Detail and hint messages: Use complete sentences, and end each with
+ a period. Capitalize the first word of sentences. Put two spaces after
+ the period if another sentence follows (for English text; might be
+ inappropriate in other languages).
+
+ Error context strings: Do not capitalize the first letter and do
+ not end the string with a period. Context strings should normally
+ not be complete sentences.
+
+ Rationale: Avoiding punctuation makes it easier for client applications to
+ embed the message into a variety of grammatical contexts. Often, primary
+ messages are not grammatically complete sentences anyway. (And if they're
+ long enough to be more than one sentence, they should be split into
+ primary and detail parts.) However, detail and hint messages are longer
+ and might need to include multiple sentences. For consistency, they should
+ follow complete-sentence style even when there's only one sentence.
+
+ Use lower case for message wording, including the first letter of a
+ primary error message. Use upper case for SQL commands and key words if
+ they appear in the message.
+
+ Rationale: It's easier to make everything look more consistent this
+ way, since some messages are complete sentences and some not.
+
+ Use the active voice. Use complete sentences when there is an acting
+ subject (“A could not do B”). Use telegram style without
+ subject if the subject would be the program itself; do not use
+ “I” for the program.
+
+ Rationale: The program is not human. Don't pretend otherwise.
+
+ Use past tense if an attempt to do something failed, but could perhaps
+ succeed next time (perhaps after fixing some problem). Use present tense
+ if the failure is certainly permanent.
+
+ There is a nontrivial semantic difference between sentences of the form:
+
+could not open file "%s": %m
+
+and:
+
+cannot open file "%s"
+
+ The first one means that the attempt to open the file failed. The
+ message should give a reason, such as “disk full” or
+ “file doesn't exist”. The past tense is appropriate because
+ next time the disk might not be full anymore or the file in question might
+ exist.
+
+ The second form indicates that the functionality of opening the named file
+ does not exist at all in the program, or that it's conceptually
+ impossible. The present tense is appropriate because the condition will
+ persist indefinitely.
+
+ Rationale: Granted, the average user will not be able to draw great
+ conclusions merely from the tense of the message, but since the language
+ provides us with a grammar we should use it correctly.
+
+ When a message includes text that is generated elsewhere, embed it in
+ this style:
+
+could not open file %s: %m
+
+
+ Rationale: It would be difficult to account for all possible error codes
+ to paste this into a single smooth sentence, so some sort of punctuation
+ is needed. Putting the embedded text in parentheses has also been
+ suggested, but it's unnatural if the embedded text is likely to be the
+ most important part of the message, as is often the case.
+
+ Don't include the name of the reporting routine in the error text. We have
+ other mechanisms for finding that out when needed, and for most users it's
+ not helpful information. If the error text doesn't make as much sense
+ without the function name, reword it.
+
+BAD: pg_strtoint32: error in "z": cannot parse "z"
+BETTER: invalid input syntax for type integer: "z"
+
+
+ Avoid mentioning called function names, either; instead say what the code
+ was trying to do:
+
+BAD: open() failed: %m
+BETTER: could not open file %s: %m
+
+ If it really seems necessary, mention the system call in the detail
+ message. (In some cases, providing the actual values passed to the
+ system call might be appropriate information for the detail message.)
+
+ Rationale: Users don't know what all those functions do.
+
Unable.
+ “Unable” is nearly the passive voice. Better use
+ “cannot” or “could not”, as appropriate.
+
Bad.
+ Error messages like “bad result” are really hard to interpret
+ intelligently. It's better to write why the result is “bad”,
+ e.g., “invalid format”.
+
Illegal.
+ “Illegal” stands for a violation of the law, the rest is
+ “invalid”. Better yet, say why it's invalid.
+
Unknown.
+ Try to avoid “unknown”. Consider “error: unknown
+ response”. If you don't know what the response is, how do you know
+ it's erroneous? “Unrecognized” is often a better choice.
+ Also, be sure to include the value being complained of.
+
+BAD: unknown node type
+BETTER: unrecognized node type: 42
+
+
Find vs. Exists.
+ If the program uses a nontrivial algorithm to locate a resource (e.g., a
+ path search) and that algorithm fails, it is fair to say that the program
+ couldn't “find” the resource. If, on the other hand, the
+ expected location of the resource is known but the program cannot access
+ it there then say that the resource doesn't “exist”. Using
+ “find” in this case sounds weak and confuses the issue.
+
May vs. Can vs. Might.
+ “May” suggests permission (e.g., "You may borrow my rake."),
+ and has little use in documentation or error messages.
+ “Can” suggests ability (e.g., "I can lift that log."),
+ and “might” suggests possibility (e.g., "It might rain
+ today."). Using the proper word clarifies meaning and assists
+ translation.
+
Contractions.
+ Avoid contractions, like “can't”; use
+ “cannot” instead.
+
Non-negative.
+ Avoid “non-negative” as it is ambiguous
+ about whether it accepts zero. It's better to use
+ “greater than zero” or
+ “greater than or equal to zero”.
+
+ Keep in mind that error message texts need to be translated into other
+ languages. Follow the guidelines in Section 57.2.2
+ to avoid making life difficult for translators.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-log-registration.html b/pgsql/doc/postgresql/html/event-log-registration.html
new file mode 100644
index 0000000000000000000000000000000000000000..b09f32837a7a3640f14f16b18e7d442a0c01d13c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-log-registration.html
@@ -0,0 +1,28 @@
+
+19.12. Registering Event Log on Windows
+ To enable event logging in the database server, modify
+ log_destination to include
+ eventlog in postgresql.conf.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-trigger-definition.html b/pgsql/doc/postgresql/html/event-trigger-definition.html
new file mode 100644
index 0000000000000000000000000000000000000000..64f0385a013ba65a9fc522b3714e3d21dbc635f7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-trigger-definition.html
@@ -0,0 +1,78 @@
+
+40.1. Overview of Event Trigger Behavior
+ An event trigger fires whenever the event with which it is associated
+ occurs in the database in which it is defined. Currently, the only
+ supported events are
+ ddl_command_start,
+ ddl_command_end,
+ table_rewrite
+ and sql_drop.
+ Support for additional events may be added in future releases.
+
+ The ddl_command_start event occurs just before the
+ execution of a CREATE, ALTER, DROP,
+ SECURITY LABEL,
+ COMMENT, GRANT or REVOKE
+ command. No check whether the affected object exists or doesn't exist is
+ performed before the event trigger fires.
+ As an exception, however, this event does not occur for
+ DDL commands targeting shared objects — databases, roles, and tablespaces
+ — or for commands targeting event triggers themselves. The event trigger
+ mechanism does not support these object types.
+ ddl_command_start also occurs just before the execution of a
+ SELECT INTO command, since this is equivalent to
+ CREATE TABLE AS.
+
+ The ddl_command_end event occurs just after the execution of
+ this same set of commands. To obtain more details on the DDL
+ operations that took place, use the set-returning function
+ pg_event_trigger_ddl_commands() from the
+ ddl_command_end event trigger code (see
+ Section 9.29). Note that the trigger fires
+ after the actions have taken place (but before the transaction commits),
+ and thus the system catalogs can be read as already changed.
+
+ The sql_drop event occurs just before the
+ ddl_command_end event trigger for any operation that drops
+ database objects. To list the objects that have been dropped, use the
+ set-returning function pg_event_trigger_dropped_objects() from the
+ sql_drop event trigger code (see
+ Section 9.29). Note that
+ the trigger is executed after the objects have been deleted from the
+ system catalogs, so it's not possible to look them up anymore.
+
+ The table_rewrite event occurs just before a table is
+ rewritten by some actions of the commands ALTER TABLE and
+ ALTER TYPE. While other
+ control statements are available to rewrite a table,
+ like CLUSTER and VACUUM,
+ the table_rewrite event is not triggered by them.
+
+ Event triggers (like other functions) cannot be executed in an aborted
+ transaction. Thus, if a DDL command fails with an error, any associated
+ ddl_command_end triggers will not be executed. Conversely,
+ if a ddl_command_start trigger fails with an error, no
+ further event triggers will fire, and no attempt will be made to execute
+ the command itself. Similarly, if a ddl_command_end trigger
+ fails with an error, the effects of the DDL statement will be rolled
+ back, just as they would be in any other case where the containing
+ transaction aborts.
+
+ For a complete list of commands supported by the event trigger mechanism,
+ see Section 40.2.
+
+ Event triggers are created using the command CREATE EVENT TRIGGER.
+ In order to create an event trigger, you must first create a function with
+ the special return type event_trigger. This function
+ need not (and may not) return a value; the return type serves merely as
+ a signal that the function is to be invoked as an event trigger.
+
+ If more than one event trigger is defined for a particular event, they will
+ fire in alphabetical order by trigger name.
+
+ A trigger definition can also specify a WHEN
+ condition so that, for example, a ddl_command_start
+ trigger can be fired only for particular commands which the user wishes
+ to intercept. A common use of such triggers is to restrict the range of
+ DDL operations which users may perform.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-trigger-example.html b/pgsql/doc/postgresql/html/event-trigger-example.html
new file mode 100644
index 0000000000000000000000000000000000000000..98c8846402c7503de1fe1ad9ad388e0537fd0d62
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-trigger-example.html
@@ -0,0 +1,78 @@
+
+40.4. A Complete Event Trigger Example
+ Here is a very simple example of an event trigger function written in C.
+ (Examples of triggers written in procedural languages can be found in
+ the documentation of the procedural languages.)
+
+ The function noddl raises an exception each time it is called.
+ The event trigger definition associated the function with
+ the ddl_command_start event. The effect is that all DDL
+ commands (with the exceptions mentioned
+ in Section 40.1) are prevented from running.
+
+ This is the source code of the trigger function:
+
+ After you have compiled the source code (see Section 38.10.5),
+ declare the function and the triggers:
+
+CREATE FUNCTION noddl() RETURNS event_trigger
+ AS 'noddl' LANGUAGE C;
+
+CREATE EVENT TRIGGER noddl ON ddl_command_start
+ EXECUTE FUNCTION noddl();
+
+
+ Now you can test the operation of the trigger:
+
+=# \dy
+ List of event triggers
+ Name | Event | Owner | Enabled | Function | Tags
+-------+-------------------+-------+---------+----------+------
+ noddl | ddl_command_start | dim | enabled | noddl |
+(1 row)
+
+=# CREATE TABLE foo(id serial);
+ERROR: command "CREATE TABLE" denied
+
+
+ In this situation, in order to be able to run some DDL commands when you
+ need to do so, you have to either drop the event trigger or disable it. It
+ can be convenient to disable the trigger for only the duration of a
+ transaction:
+
+ (Recall that DDL commands on event triggers themselves are not affected by
+ event triggers.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-trigger-interface.html b/pgsql/doc/postgresql/html/event-trigger-interface.html
new file mode 100644
index 0000000000000000000000000000000000000000..28a3b38760e8cbe89611d99e2241ddcb5dea5b82
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-trigger-interface.html
@@ -0,0 +1,68 @@
+
+40.3. Writing Event Trigger Functions in C
+ This section describes the low-level details of the interface to an
+ event trigger function. This information is only needed when writing
+ event trigger functions in C. If you are using a higher-level language
+ then these details are handled for you. In most cases you should
+ consider using a procedural language before writing your event triggers
+ in C. The documentation of each procedural language explains how to
+ write an event trigger in that language.
+
+ Event trigger functions must use the “version 1” function
+ manager interface.
+
+ When a function is called by the event trigger manager, it is not passed
+ any normal arguments, but it is passed a “context” pointer
+ pointing to a EventTriggerData structure. C functions can
+ check whether they were called from the event trigger manager or not by
+ executing the macro:
+
+ If this returns true, then it is safe to cast
+ fcinfo->context to type EventTriggerData
+ * and make use of the pointed-to
+ EventTriggerData structure. The function must
+ not alter the EventTriggerData
+ structure or any of the data it points to.
+
+ struct EventTriggerData is defined in
+ commands/event_trigger.h:
+
+
+ Describes the event for which the function is called, one of
+ "ddl_command_start", "ddl_command_end",
+ "sql_drop", "table_rewrite".
+ See Section 40.1 for the meaning of these
+ events.
+
parsetree
+ A pointer to the parse tree of the command. Check the PostgreSQL
+ source code for details. The parse tree structure is subject to change
+ without notice.
+
tag
+ The command tag associated with the event for which the event trigger
+ is run, for example "CREATE FUNCTION".
+
+
+ An event trigger function must return a NULL pointer
+ (not an SQL null value, that is, do not
+ set isNull true).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-trigger-matrix.html b/pgsql/doc/postgresql/html/event-trigger-matrix.html
new file mode 100644
index 0000000000000000000000000000000000000000..53e3d1225a9c3c8653a83acba514e180589d3bef
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-trigger-matrix.html
@@ -0,0 +1,5 @@
+
+40.2. Event Trigger Firing Matrix
+ Table 40.1 lists all commands
+ for which event triggers are supported.
+
Table 40.1. Event Trigger Support by Command Tag
Command Tag
ddl_command_start
ddl_command_end
sql_drop
table_rewrite
Notes
ALTER AGGREGATE
X
X
-
-
ALTER COLLATION
X
X
-
-
ALTER CONVERSION
X
X
-
-
ALTER DOMAIN
X
X
-
-
ALTER DEFAULT PRIVILEGES
X
X
-
-
ALTER EXTENSION
X
X
-
-
ALTER FOREIGN DATA WRAPPER
X
X
-
-
ALTER FOREIGN TABLE
X
X
X
-
ALTER FUNCTION
X
X
-
-
ALTER LANGUAGE
X
X
-
-
ALTER LARGE OBJECT
X
X
-
-
ALTER MATERIALIZED VIEW
X
X
-
X
ALTER OPERATOR
X
X
-
-
ALTER OPERATOR CLASS
X
X
-
-
ALTER OPERATOR FAMILY
X
X
-
-
ALTER POLICY
X
X
-
-
ALTER PROCEDURE
X
X
-
-
ALTER PUBLICATION
X
X
-
-
ALTER ROUTINE
X
X
-
-
ALTER SCHEMA
X
X
-
-
ALTER SEQUENCE
X
X
-
-
ALTER SERVER
X
X
-
-
ALTER STATISTICS
X
X
-
-
ALTER SUBSCRIPTION
X
X
-
-
ALTER TABLE
X
X
X
X
ALTER TEXT SEARCH CONFIGURATION
X
X
-
-
ALTER TEXT SEARCH DICTIONARY
X
X
-
-
ALTER TEXT SEARCH PARSER
X
X
-
-
ALTER TEXT SEARCH TEMPLATE
X
X
-
-
ALTER TRIGGER
X
X
-
-
ALTER TYPE
X
X
-
X
ALTER USER MAPPING
X
X
-
-
ALTER VIEW
X
X
-
-
COMMENT
X
X
-
-
Only for local objects
CREATE ACCESS METHOD
X
X
-
-
CREATE AGGREGATE
X
X
-
-
CREATE CAST
X
X
-
-
CREATE COLLATION
X
X
-
-
CREATE CONVERSION
X
X
-
-
CREATE DOMAIN
X
X
-
-
CREATE EXTENSION
X
X
-
-
CREATE FOREIGN DATA WRAPPER
X
X
-
-
CREATE FOREIGN TABLE
X
X
-
-
CREATE FUNCTION
X
X
-
-
CREATE INDEX
X
X
-
-
CREATE LANGUAGE
X
X
-
-
CREATE MATERIALIZED VIEW
X
X
-
-
CREATE OPERATOR
X
X
-
-
CREATE OPERATOR CLASS
X
X
-
-
CREATE OPERATOR FAMILY
X
X
-
-
CREATE POLICY
X
X
-
-
CREATE PROCEDURE
X
X
-
-
CREATE PUBLICATION
X
X
-
-
CREATE RULE
X
X
-
-
CREATE SCHEMA
X
X
-
-
CREATE SEQUENCE
X
X
-
-
CREATE SERVER
X
X
-
-
CREATE STATISTICS
X
X
-
-
CREATE SUBSCRIPTION
X
X
-
-
CREATE TABLE
X
X
-
-
CREATE TABLE AS
X
X
-
-
CREATE TEXT SEARCH CONFIGURATION
X
X
-
-
CREATE TEXT SEARCH DICTIONARY
X
X
-
-
CREATE TEXT SEARCH PARSER
X
X
-
-
CREATE TEXT SEARCH TEMPLATE
X
X
-
-
CREATE TRIGGER
X
X
-
-
CREATE TYPE
X
X
-
-
CREATE USER MAPPING
X
X
-
-
CREATE VIEW
X
X
-
-
DROP ACCESS METHOD
X
X
X
-
DROP AGGREGATE
X
X
X
-
DROP CAST
X
X
X
-
DROP COLLATION
X
X
X
-
DROP CONVERSION
X
X
X
-
DROP DOMAIN
X
X
X
-
DROP EXTENSION
X
X
X
-
DROP FOREIGN DATA WRAPPER
X
X
X
-
DROP FOREIGN TABLE
X
X
X
-
DROP FUNCTION
X
X
X
-
DROP INDEX
X
X
X
-
DROP LANGUAGE
X
X
X
-
DROP MATERIALIZED VIEW
X
X
X
-
DROP OPERATOR
X
X
X
-
DROP OPERATOR CLASS
X
X
X
-
DROP OPERATOR FAMILY
X
X
X
-
DROP OWNED
X
X
X
-
DROP POLICY
X
X
X
-
DROP PROCEDURE
X
X
X
-
DROP PUBLICATION
X
X
X
-
DROP ROUTINE
X
X
X
-
DROP RULE
X
X
X
-
DROP SCHEMA
X
X
X
-
DROP SEQUENCE
X
X
X
-
DROP SERVER
X
X
X
-
DROP STATISTICS
X
X
X
-
DROP SUBSCRIPTION
X
X
X
-
DROP TABLE
X
X
X
-
DROP TEXT SEARCH CONFIGURATION
X
X
X
-
DROP TEXT SEARCH DICTIONARY
X
X
X
-
DROP TEXT SEARCH PARSER
X
X
X
-
DROP TEXT SEARCH TEMPLATE
X
X
X
-
DROP TRIGGER
X
X
X
-
DROP TYPE
X
X
X
-
DROP USER MAPPING
X
X
X
-
DROP VIEW
X
X
X
-
GRANT
X
X
-
-
Only for local objects
IMPORT FOREIGN SCHEMA
X
X
-
-
REFRESH MATERIALIZED VIEW
X
X
-
-
REVOKE
X
X
-
-
Only for local objects
SECURITY LABEL
X
X
-
-
Only for local objects
SELECT INTO
X
X
-
-
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-trigger-table-rewrite-example.html b/pgsql/doc/postgresql/html/event-trigger-table-rewrite-example.html
new file mode 100644
index 0000000000000000000000000000000000000000..e487cdd55ecce697e7cd40e651bc0104dcc8549d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-trigger-table-rewrite-example.html
@@ -0,0 +1,48 @@
+
+40.5. A Table Rewrite Event Trigger Example
+ Thanks to the table_rewrite event, it is possible to implement
+ a table rewriting policy only allowing the rewrite in maintenance windows.
+
+ Here's an example implementing such a policy.
+
+CREATE OR REPLACE FUNCTION no_rewrite()
+ RETURNS event_trigger
+ LANGUAGE plpgsql AS
+$$
+---
+--- Implement local Table Rewriting policy:
+--- public.foo is not allowed rewriting, ever
+--- other tables are only allowed rewriting between 1am and 6am
+--- unless they have more than 100 blocks
+---
+DECLARE
+ table_oid oid := pg_event_trigger_table_rewrite_oid();
+ current_hour integer := extract('hour' from current_time);
+ pages integer;
+ max_pages integer := 100;
+BEGIN
+ IF pg_event_trigger_table_rewrite_oid() = 'public.foo'::regclass
+ THEN
+ RAISE EXCEPTION 'you''re not allowed to rewrite the table %',
+ table_oid::regclass;
+ END IF;
+
+ SELECT INTO pages relpages FROM pg_class WHERE oid = table_oid;
+ IF pages > max_pages
+ THEN
+ RAISE EXCEPTION 'rewrites only allowed for table with less than % pages',
+ max_pages;
+ END IF;
+
+ IF current_hour NOT BETWEEN 1 AND 6
+ THEN
+ RAISE EXCEPTION 'rewrites only allowed between 1am and 6am';
+ END IF;
+END;
+$$;
+
+CREATE EVENT TRIGGER no_rewrite_allowed
+ ON table_rewrite
+ EXECUTE FUNCTION no_rewrite();
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/event-triggers.html b/pgsql/doc/postgresql/html/event-triggers.html
new file mode 100644
index 0000000000000000000000000000000000000000..e37e21ac657ed2cedd23e93928b48d7d40c83370
--- /dev/null
+++ b/pgsql/doc/postgresql/html/event-triggers.html
@@ -0,0 +1,12 @@
+
+Chapter 40. Event Triggers
+ To supplement the trigger mechanism discussed in Chapter 39,
+ PostgreSQL also provides event triggers. Unlike regular
+ triggers, which are attached to a single table and capture only DML events,
+ event triggers are global to a particular database and are capable of
+ capturing DDL events.
+
+ Like regular triggers, event triggers can be written in any procedural
+ language that includes event trigger support, or in C, but not in plain
+ SQL.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/executor.html b/pgsql/doc/postgresql/html/executor.html
new file mode 100644
index 0000000000000000000000000000000000000000..1998a5b883df963a4c32170c2dcd620a6eccd972
--- /dev/null
+++ b/pgsql/doc/postgresql/html/executor.html
@@ -0,0 +1,78 @@
+
+52.6. Executor
+ The executor takes the plan created by the
+ planner/optimizer and recursively processes it to extract the required set
+ of rows. This is essentially a demand-pull pipeline mechanism.
+ Each time a plan node is called, it must deliver one more row, or
+ report that it is done delivering rows.
+
+ To provide a concrete example, assume that the top
+ node is a MergeJoin node.
+ Before any merge can be done two rows have to be fetched (one from
+ each subplan). So the executor recursively calls itself to
+ process the subplans (it starts with the subplan attached to
+ lefttree). The new top node (the top node of the left
+ subplan) is, let's say, a
+ Sort node and again recursion is needed to obtain
+ an input row. The child node of the Sort might
+ be a SeqScan node, representing actual reading of a table.
+ Execution of this node causes the executor to fetch a row from the
+ table and return it up to the calling node. The Sort
+ node will repeatedly call its child to obtain all the rows to be sorted.
+ When the input is exhausted (as indicated by the child node returning
+ a NULL instead of a row), the Sort code performs
+ the sort, and finally is able to return its first output row, namely
+ the first one in sorted order. It keeps the remaining rows stored so
+ that it can deliver them in sorted order in response to later demands.
+
+ The MergeJoin node similarly demands the first row
+ from its right subplan. Then it compares the two rows to see if they
+ can be joined; if so, it returns a join row to its caller. On the next
+ call, or immediately if it cannot join the current pair of inputs,
+ it advances to the next row of one table
+ or the other (depending on how the comparison came out), and again
+ checks for a match. Eventually, one subplan or the other is exhausted,
+ and the MergeJoin node returns NULL to indicate that
+ no more join rows can be formed.
+
+ Complex queries can involve many levels of plan nodes, but the general
+ approach is the same: each node computes and returns its next output
+ row each time it is called. Each node is also responsible for applying
+ any selection or projection expressions that were assigned to it by
+ the planner.
+
+ The executor mechanism is used to evaluate all five basic SQL query
+ types: SELECT, INSERT,
+ UPDATE, DELETE, and
+ MERGE.
+ For SELECT, the top-level executor code
+ only needs to send each row returned by the query plan tree
+ off to the client. INSERT ... SELECT,
+ UPDATE, DELETE, and
+ MERGE
+ are effectively SELECTs under a special
+ top-level plan node called ModifyTable.
+
+ INSERT ... SELECT feeds the rows up
+ to ModifyTable for insertion. For
+ UPDATE, the planner arranges that each
+ computed row includes all the updated column values, plus the
+ TID (tuple ID, or row ID) of the original
+ target row; this data is fed up to the ModifyTable
+ node, which uses the information to create a new updated row and
+ mark the old row deleted. For DELETE, the only
+ column that is actually returned by the plan is the TID, and the
+ ModifyTable node simply uses the TID to visit each
+ target row and mark it deleted. For MERGE, the
+ planner joins the source and target relations, and includes all
+ column values required by any of the WHEN clauses,
+ plus the TID of the target row; this data is fed up to the
+ ModifyTable node, which uses the information to
+ work out which WHEN clause to execute, and then
+ inserts, updates or deletes the target row, as required.
+
+ A simple INSERT ... VALUES command creates a
+ trivial plan tree consisting of a single Result
+ node, which computes just one result row, feeding that up
+ to ModifyTable to perform the insertion.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/explicit-joins.html b/pgsql/doc/postgresql/html/explicit-joins.html
new file mode 100644
index 0000000000000000000000000000000000000000..f86a9d6bf37518d30489788dfb425ff464c9d4ea
--- /dev/null
+++ b/pgsql/doc/postgresql/html/explicit-joins.html
@@ -0,0 +1,144 @@
+
+14.3. Controlling the Planner with Explicit JOIN Clauses
14.3. Controlling the Planner with Explicit JOIN Clauses
14.3. Controlling the Planner with Explicit JOIN Clauses #
+ It is possible
+ to control the query planner to some extent by using the explicit JOIN
+ syntax. To see why this matters, we first need some background.
+
+ In a simple join query, such as:
+
+SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
+
+ the planner is free to join the given tables in any order. For
+ example, it could generate a query plan that joins A to B, using
+ the WHERE condition a.id = b.id, and then
+ joins C to this joined table, using the other WHERE
+ condition. Or it could join B to C and then join A to that result.
+ Or it could join A to C and then join them with B — but that
+ would be inefficient, since the full Cartesian product of A and C
+ would have to be formed, there being no applicable condition in the
+ WHERE clause to allow optimization of the join. (All
+ joins in the PostgreSQL executor happen
+ between two input tables, so it's necessary to build up the result
+ in one or another of these fashions.) The important point is that
+ these different join possibilities give semantically equivalent
+ results but might have hugely different execution costs. Therefore,
+ the planner will explore all of them to try to find the most
+ efficient query plan.
+
+ When a query only involves two or three tables, there aren't many join
+ orders to worry about. But the number of possible join orders grows
+ exponentially as the number of tables expands. Beyond ten or so input
+ tables it's no longer practical to do an exhaustive search of all the
+ possibilities, and even for six or seven tables planning might take an
+ annoyingly long time. When there are too many input tables, the
+ PostgreSQL planner will switch from exhaustive
+ search to a genetic probabilistic search
+ through a limited number of possibilities. (The switch-over threshold is
+ set by the geqo_threshold run-time
+ parameter.)
+ The genetic search takes less time, but it won't
+ necessarily find the best possible plan.
+
+ When the query involves outer joins, the planner has less freedom
+ than it does for plain (inner) joins. For example, consider:
+
+SELECT * FROM a LEFT JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
+
+ Although this query's restrictions are superficially similar to the
+ previous example, the semantics are different because a row must be
+ emitted for each row of A that has no matching row in the join of B and C.
+ Therefore the planner has no choice of join order here: it must join
+ B to C and then join A to that result. Accordingly, this query takes
+ less time to plan than the previous query. In other cases, the planner
+ might be able to determine that more than one join order is safe.
+ For example, given:
+
+SELECT * FROM a LEFT JOIN b ON (a.bid = b.id) LEFT JOIN c ON (a.cid = c.id);
+
+ it is valid to join A to either B or C first. Currently, only
+ FULL JOIN completely constrains the join order. Most
+ practical cases involving LEFT JOIN or RIGHT JOIN
+ can be rearranged to some extent.
+
+ Explicit inner join syntax (INNER JOIN, CROSS
+ JOIN, or unadorned JOIN) is semantically the same as
+ listing the input relations in FROM, so it does not
+ constrain the join order.
+
+ Even though most kinds of JOIN don't completely constrain
+ the join order, it is possible to instruct the
+ PostgreSQL query planner to treat all
+ JOIN clauses as constraining the join order anyway.
+ For example, these three queries are logically equivalent:
+
+SELECT * FROM a, b, c WHERE a.id = b.id AND b.ref = c.id;
+SELECT * FROM a CROSS JOIN b CROSS JOIN c WHERE a.id = b.id AND b.ref = c.id;
+SELECT * FROM a JOIN (b JOIN c ON (b.ref = c.id)) ON (a.id = b.id);
+
+ But if we tell the planner to honor the JOIN order,
+ the second and third take less time to plan than the first. This effect
+ is not worth worrying about for only three tables, but it can be a
+ lifesaver with many tables.
+
+ To force the planner to follow the join order laid out by explicit
+ JOINs,
+ set the join_collapse_limit run-time parameter to 1.
+ (Other possible values are discussed below.)
+
+ You do not need to constrain the join order completely in order to
+ cut search time, because it's OK to use JOIN operators
+ within items of a plain FROM list. For example, consider:
+
+SELECT * FROM a CROSS JOIN b, c, d, e WHERE ...;
+
+ With join_collapse_limit = 1, this
+ forces the planner to join A to B before joining them to other tables,
+ but doesn't constrain its choices otherwise. In this example, the
+ number of possible join orders is reduced by a factor of 5.
+
+ Constraining the planner's search in this way is a useful technique
+ both for reducing planning time and for directing the planner to a
+ good query plan. If the planner chooses a bad join order by default,
+ you can force it to choose a better order via JOIN syntax
+ — assuming that you know of a better order, that is. Experimentation
+ is recommended.
+
+ A closely related issue that affects planning time is collapsing of
+ subqueries into their parent query. For example, consider:
+
+SELECT *
+FROM x, y,
+ (SELECT * FROM a, b, c WHERE something) AS ss
+WHERE somethingelse;
+
+ This situation might arise from use of a view that contains a join;
+ the view's SELECT rule will be inserted in place of the view
+ reference, yielding a query much like the above. Normally, the planner
+ will try to collapse the subquery into the parent, yielding:
+
+SELECT * FROM x, y, a, b, c WHERE something AND somethingelse;
+
+ This usually results in a better plan than planning the subquery
+ separately. (For example, the outer WHERE conditions might be such that
+ joining X to A first eliminates many rows of A, thus avoiding the need to
+ form the full logical output of the subquery.) But at the same time,
+ we have increased the planning time; here, we have a five-way join
+ problem replacing two separate three-way join problems. Because of the
+ exponential growth of the number of possibilities, this makes a big
+ difference. The planner tries to avoid getting stuck in huge join search
+ problems by not collapsing a subquery if more than from_collapse_limit
+ FROM items would result in the parent
+ query. You can trade off planning time against quality of plan by
+ adjusting this run-time parameter up or down.
+
+ from_collapse_limit and join_collapse_limit
+ are similarly named because they do almost the same thing: one controls
+ when the planner will “flatten out” subqueries, and the
+ other controls when it will flatten out explicit joins. Typically
+ you would either set join_collapse_limit equal to
+ from_collapse_limit (so that explicit joins and subqueries
+ act similarly) or set join_collapse_limit to 1 (if you want
+ to control join order with explicit joins). But you might set them
+ differently if you are trying to fine-tune the trade-off between planning
+ time and run time.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/explicit-locking.html b/pgsql/doc/postgresql/html/explicit-locking.html
new file mode 100644
index 0000000000000000000000000000000000000000..45aa07f0937a5ba196e68b49c2c8049d179ad626
--- /dev/null
+++ b/pgsql/doc/postgresql/html/explicit-locking.html
@@ -0,0 +1,396 @@
+
+13.3. Explicit Locking
+ PostgreSQL provides various lock modes
+ to control concurrent access to data in tables. These modes can
+ be used for application-controlled locking in situations where
+ MVCC does not give the desired behavior. Also,
+ most PostgreSQL commands automatically
+ acquire locks of appropriate modes to ensure that referenced
+ tables are not dropped or modified in incompatible ways while the
+ command executes. (For example, TRUNCATE cannot safely be
+ executed concurrently with other operations on the same table, so it
+ obtains an ACCESS EXCLUSIVE lock on the table to
+ enforce that.)
+
+ To examine a list of the currently outstanding locks in a database
+ server, use the
+ pg_locks
+ system view. For more information on monitoring the status of the lock
+ manager subsystem, refer to Chapter 28.
+
+ The list below shows the available lock modes and the contexts in
+ which they are used automatically by
+ PostgreSQL. You can also acquire any
+ of these locks explicitly with the command LOCK.
+ Remember that all of these lock modes are table-level locks,
+ even if the name contains the word
+ “row”; the names of the lock modes are historical.
+ To some extent the names reflect the typical usage of each lock
+ mode — but the semantics are all the same. The only real difference
+ between one lock mode and another is the set of lock modes with
+ which each conflicts (see Table 13.2).
+ Two transactions cannot hold locks of conflicting
+ modes on the same table at the same time. (However, a transaction
+ never conflicts with itself. For example, it might acquire
+ ACCESS EXCLUSIVE lock and later acquire
+ ACCESS SHARE lock on the same table.) Non-conflicting
+ lock modes can be held concurrently by many transactions. Notice in
+ particular that some lock modes are self-conflicting (for example,
+ an ACCESS EXCLUSIVE lock cannot be held by more than one
+ transaction at a time) while others are not self-conflicting (for example,
+ an ACCESS SHARE lock can be held by multiple transactions).
+
Table-Level Lock Modes
+ ACCESS SHARE (AccessShareLock)
+
+ Conflicts with the ACCESS EXCLUSIVE lock
+ mode only.
+
+ The SELECT command acquires a lock of this mode on
+ referenced tables. In general, any query that only reads a table
+ and does not modify it will acquire this lock mode.
+
+ ROW SHARE (RowShareLock)
+
+ Conflicts with the EXCLUSIVE and
+ ACCESS EXCLUSIVE lock modes.
+
+ The SELECT command acquires a lock of this mode
+ on all tables on which one of the FOR UPDATE,
+ FOR NO KEY UPDATE,
+ FOR SHARE, or
+ FOR KEY SHARE options is specified
+ (in addition to ACCESS SHARE locks on any other
+ tables that are referenced without any explicit
+ FOR ... locking option).
+
+ ROW EXCLUSIVE (RowExclusiveLock)
+
+ Conflicts with the SHARE, SHARE ROW
+ EXCLUSIVE, EXCLUSIVE, and
+ ACCESS EXCLUSIVE lock modes.
+
+ The commands UPDATE,
+ DELETE, INSERT, and
+ MERGE
+ acquire this lock mode on the target table (in addition to
+ ACCESS SHARE locks on any other referenced
+ tables). In general, this lock mode will be acquired by any
+ command that modifies data in a table.
+
+ Conflicts with the SHARE UPDATE EXCLUSIVE,
+ SHARE, SHARE ROW
+ EXCLUSIVE, EXCLUSIVE, and
+ ACCESS EXCLUSIVE lock modes.
+ This mode protects a table against
+ concurrent schema changes and VACUUM runs.
+
+ Acquired by VACUUM (without FULL),
+ ANALYZE, CREATE INDEX CONCURRENTLY,
+ CREATE STATISTICS, COMMENT ON,
+ REINDEX CONCURRENTLY,
+ and certain ALTER INDEX
+ and ALTER TABLE variants
+ (for full details see the documentation of these commands).
+
+ SHARE (ShareLock)
+
+ Conflicts with the ROW EXCLUSIVE,
+ SHARE UPDATE EXCLUSIVE, SHARE ROW
+ EXCLUSIVE, EXCLUSIVE, and
+ ACCESS EXCLUSIVE lock modes.
+ This mode protects a table against concurrent data changes.
+
+ Acquired by CREATE INDEX
+ (without CONCURRENTLY).
+
+ SHARE ROW EXCLUSIVE (ShareRowExclusiveLock)
+
+ Conflicts with the ROW EXCLUSIVE,
+ SHARE UPDATE EXCLUSIVE,
+ SHARE, SHARE ROW
+ EXCLUSIVE, EXCLUSIVE, and
+ ACCESS EXCLUSIVE lock modes.
+ This mode protects a table against concurrent data changes, and
+ is self-exclusive so that only one session can hold it at a time.
+
+ Acquired by CREATE TRIGGER and some forms of
+ ALTER TABLE.
+
+ EXCLUSIVE (ExclusiveLock)
+
+ Conflicts with the ROW SHARE, ROW
+ EXCLUSIVE, SHARE UPDATE
+ EXCLUSIVE, SHARE, SHARE
+ ROW EXCLUSIVE, EXCLUSIVE, and
+ ACCESS EXCLUSIVE lock modes.
+ This mode allows only concurrent ACCESS SHARE locks,
+ i.e., only reads from the table can proceed in parallel with a
+ transaction holding this lock mode.
+
+ Acquired by REFRESH MATERIALIZED VIEW CONCURRENTLY.
+
+ ACCESS EXCLUSIVE (AccessExclusiveLock)
+
+ Conflicts with locks of all modes (ACCESS
+ SHARE, ROW SHARE, ROW
+ EXCLUSIVE, SHARE UPDATE
+ EXCLUSIVE, SHARE, SHARE
+ ROW EXCLUSIVE, EXCLUSIVE, and
+ ACCESS EXCLUSIVE).
+ This mode guarantees that the
+ holder is the only transaction accessing the table in any way.
+
+ Acquired by the DROP TABLE,
+ TRUNCATE, REINDEX,
+ CLUSTER, VACUUM FULL,
+ and REFRESH MATERIALIZED VIEW (without
+ CONCURRENTLY)
+ commands. Many forms of ALTER INDEX and ALTER TABLE also acquire
+ a lock at this level. This is also the default lock mode for
+ LOCK TABLE statements that do not specify
+ a mode explicitly.
+
Tip
+ Only an ACCESS EXCLUSIVE lock blocks a
+ SELECT (without FOR UPDATE/SHARE)
+ statement.
+
+ Once acquired, a lock is normally held until the end of the transaction. But if a
+ lock is acquired after establishing a savepoint, the lock is released
+ immediately if the savepoint is rolled back to. This is consistent with
+ the principle that ROLLBACK cancels all effects of the
+ commands since the savepoint. The same holds for locks acquired within a
+ PL/pgSQL exception block: an error escape from the block
+ releases locks acquired within it.
+
+ In addition to table-level locks, there are row-level locks, which
+ are listed as below with the contexts in which they are used
+ automatically by PostgreSQL. See
+ Table 13.3 for a complete table of
+ row-level lock conflicts. Note that a transaction can hold
+ conflicting locks on the same row, even in different subtransactions;
+ but other than that, two transactions can never hold conflicting locks
+ on the same row. Row-level locks do not affect data querying; they
+ block only writers and lockers to the same
+ row. Row-level locks are released at transaction end or during
+ savepoint rollback, just like table-level locks.
+
+
Row-Level Lock Modes
+ FOR UPDATE
+
+ FOR UPDATE causes the rows retrieved by the
+ SELECT statement to be locked as though for
+ update. This prevents them from being locked, modified or deleted by
+ other transactions until the current transaction ends. That is,
+ other transactions that attempt UPDATE,
+ DELETE,
+ SELECT FOR UPDATE,
+ SELECT FOR NO KEY UPDATE,
+ SELECT FOR SHARE or
+ SELECT FOR KEY SHARE
+ of these rows will be blocked until the current transaction ends;
+ conversely, SELECT FOR UPDATE will wait for a
+ concurrent transaction that has run any of those commands on the
+ same row,
+ and will then lock and return the updated row (or no row, if the
+ row was deleted). Within a REPEATABLE READ or
+ SERIALIZABLE transaction,
+ however, an error will be thrown if a row to be locked has changed
+ since the transaction started. For further discussion see
+ Section 13.4.
+
+ The FOR UPDATE lock mode
+ is also acquired by any DELETE on a row, and also by an
+ UPDATE that modifies the values of certain columns. Currently,
+ the set of columns considered for the UPDATE case are those that
+ have a unique index on them that can be used in a foreign key (so partial
+ indexes and expressional indexes are not considered), but this may change
+ in the future.
+
+ FOR NO KEY UPDATE
+
+ Behaves similarly to FOR UPDATE, except that the lock
+ acquired is weaker: this lock will not block
+ SELECT FOR KEY SHARE commands that attempt to acquire
+ a lock on the same rows. This lock mode is also acquired by any
+ UPDATE that does not acquire a FOR UPDATE lock.
+
+ FOR SHARE
+
+ Behaves similarly to FOR NO KEY UPDATE, except that it
+ acquires a shared lock rather than exclusive lock on each retrieved
+ row. A shared lock blocks other transactions from performing
+ UPDATE, DELETE,
+ SELECT FOR UPDATE or
+ SELECT FOR NO KEY UPDATE on these rows, but it does not
+ prevent them from performing SELECT FOR SHARE or
+ SELECT FOR KEY SHARE.
+
+ FOR KEY SHARE
+
+ Behaves similarly to FOR SHARE, except that the
+ lock is weaker: SELECT FOR UPDATE is blocked, but not
+ SELECT FOR NO KEY UPDATE. A key-shared lock blocks
+ other transactions from performing DELETE or
+ any UPDATE that changes the key values, but not
+ other UPDATE, and neither does it prevent
+ SELECT FOR NO KEY UPDATE, SELECT FOR SHARE,
+ or SELECT FOR KEY SHARE.
+
+ PostgreSQL doesn't remember any
+ information about modified rows in memory, so there is no limit on
+ the number of rows locked at one time. However, locking a row
+ might cause a disk write, e.g., SELECT FOR
+ UPDATE modifies selected rows to mark them locked, and so
+ will result in disk writes.
+
+ In addition to table and row locks, page-level share/exclusive locks are
+ used to control read/write access to table pages in the shared buffer
+ pool. These locks are released immediately after a row is fetched or
+ updated. Application developers normally need not be concerned with
+ page-level locks, but they are mentioned here for completeness.
+
+ The use of explicit locking can increase the likelihood of
+ deadlocks, wherein two (or more) transactions each
+ hold locks that the other wants. For example, if transaction 1
+ acquires an exclusive lock on table A and then tries to acquire
+ an exclusive lock on table B, while transaction 2 has already
+ exclusive-locked table B and now wants an exclusive lock on table
+ A, then neither one can proceed.
+ PostgreSQL automatically detects
+ deadlock situations and resolves them by aborting one of the
+ transactions involved, allowing the other(s) to complete.
+ (Exactly which transaction will be aborted is difficult to
+ predict and should not be relied upon.)
+
+ Note that deadlocks can also occur as the result of row-level
+ locks (and thus, they can occur even if explicit locking is not
+ used). Consider the case in which two concurrent
+ transactions modify a table. The first transaction executes:
+
+
+UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 11111;
+
+
+ This acquires a row-level lock on the row with the specified
+ account number. Then, the second transaction executes:
+
+
+UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 22222;
+UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 11111;
+
+
+ The first UPDATE statement successfully
+ acquires a row-level lock on the specified row, so it succeeds in
+ updating that row. However, the second UPDATE
+ statement finds that the row it is attempting to update has
+ already been locked, so it waits for the transaction that
+ acquired the lock to complete. Transaction two is now waiting on
+ transaction one to complete before it continues execution. Now,
+ transaction one executes:
+
+
+UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 22222;
+
+
+ Transaction one attempts to acquire a row-level lock on the
+ specified row, but it cannot: transaction two already holds such
+ a lock. So it waits for transaction two to complete. Thus,
+ transaction one is blocked on transaction two, and transaction
+ two is blocked on transaction one: a deadlock
+ condition. PostgreSQL will detect this
+ situation and abort one of the transactions.
+
+ The best defense against deadlocks is generally to avoid them by
+ being certain that all applications using a database acquire
+ locks on multiple objects in a consistent order. In the example
+ above, if both transactions
+ had updated the rows in the same order, no deadlock would have
+ occurred. One should also ensure that the first lock acquired on
+ an object in a transaction is the most restrictive mode that will be
+ needed for that object. If it is not feasible to verify this in
+ advance, then deadlocks can be handled on-the-fly by retrying
+ transactions that abort due to deadlocks.
+
+ So long as no deadlock situation is detected, a transaction seeking
+ either a table-level or row-level lock will wait indefinitely for
+ conflicting locks to be released. This means it is a bad idea for
+ applications to hold transactions open for long periods of time
+ (e.g., while waiting for user input).
+
+ PostgreSQL provides a means for
+ creating locks that have application-defined meanings. These are
+ called advisory locks, because the system does not
+ enforce their use — it is up to the application to use them
+ correctly. Advisory locks can be useful for locking strategies
+ that are an awkward fit for the MVCC model.
+ For example, a common use of advisory locks is to emulate pessimistic
+ locking strategies typical of so-called “flat file” data
+ management systems.
+ While a flag stored in a table could be used for the same purpose,
+ advisory locks are faster, avoid table bloat, and are automatically
+ cleaned up by the server at the end of the session.
+
+ There are two ways to acquire an advisory lock in
+ PostgreSQL: at session level or at
+ transaction level.
+ Once acquired at session level, an advisory lock is held until
+ explicitly released or the session ends. Unlike standard lock requests,
+ session-level advisory lock requests do not honor transaction semantics:
+ a lock acquired during a transaction that is later rolled back will still
+ be held following the rollback, and likewise an unlock is effective even
+ if the calling transaction fails later. A lock can be acquired multiple
+ times by its owning process; for each completed lock request there must
+ be a corresponding unlock request before the lock is actually released.
+ Transaction-level lock requests, on the other hand, behave more like
+ regular lock requests: they are automatically released at the end of the
+ transaction, and there is no explicit unlock operation. This behavior
+ is often more convenient than the session-level behavior for short-term
+ usage of an advisory lock.
+ Session-level and transaction-level lock requests for the same advisory
+ lock identifier will block each other in the expected way.
+ If a session already holds a given advisory lock, additional requests by
+ it will always succeed, even if other sessions are awaiting the lock; this
+ statement is true regardless of whether the existing lock hold and new
+ request are at session level or transaction level.
+
+ Like all locks in
+ PostgreSQL, a complete list of advisory locks
+ currently held by any session can be found in the pg_locks system
+ view.
+
+ Both advisory locks and regular locks are stored in a shared memory
+ pool whose size is defined by the configuration variables
+ max_locks_per_transaction and
+ max_connections.
+ Care must be taken not to exhaust this
+ memory or the server will be unable to grant any locks at all.
+ This imposes an upper limit on the number of advisory locks
+ grantable by the server, typically in the tens to hundreds of thousands
+ depending on how the server is configured.
+
+ In certain cases using advisory locking methods, especially in queries
+ involving explicit ordering and LIMIT clauses, care must be
+ taken to control the locks acquired because of the order in which SQL
+ expressions are evaluated. For example:
+
+SELECT pg_advisory_lock(id) FROM foo WHERE id = 12345; -- ok
+SELECT pg_advisory_lock(id) FROM foo WHERE id > 12345 LIMIT 100; -- danger!
+SELECT pg_advisory_lock(q.id) FROM
+(
+ SELECT id FROM foo WHERE id > 12345 LIMIT 100
+) q; -- ok
+
+ In the above queries, the second form is dangerous because the
+ LIMIT is not guaranteed to be applied before the locking
+ function is executed. This might cause some locks to be acquired
+ that the application was not expecting, and hence would fail to release
+ (until it ends the session).
+ From the point of view of the application, such locks
+ would be dangling, although still viewable in
+ pg_locks.
+
+ The functions provided to manipulate advisory locks are described in
+ Section 9.27.10.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/extend-extensions.html b/pgsql/doc/postgresql/html/extend-extensions.html
new file mode 100644
index 0000000000000000000000000000000000000000..71ab449314954a87aa8b95bddf28803490cd3dd3
--- /dev/null
+++ b/pgsql/doc/postgresql/html/extend-extensions.html
@@ -0,0 +1,656 @@
+
+38.17. Packaging Related Objects into an Extension
38.17. Packaging Related Objects into an Extension
+ A useful extension to PostgreSQL typically includes
+ multiple SQL objects; for example, a new data type will require new
+ functions, new operators, and probably new index operator classes.
+ It is helpful to collect all these objects into a single package
+ to simplify database management. PostgreSQL calls
+ such a package an extension. To define an extension,
+ you need at least a script file that contains the
+ SQL commands to create the extension's objects, and a
+ control file that specifies a few basic properties
+ of the extension itself. If the extension includes C code, there
+ will typically also be a shared library file into which the C code
+ has been built. Once you have these files, a simple
+ CREATE EXTENSION command loads the objects into
+ your database.
+
+ The main advantage of using an extension, rather than just running the
+ SQL script to load a bunch of “loose” objects
+ into your database, is that PostgreSQL will then
+ understand that the objects of the extension go together. You can
+ drop all the objects with a single DROP EXTENSION
+ command (no need to maintain a separate “uninstall” script).
+ Even more useful, pg_dump knows that it should not
+ dump the individual member objects of the extension — it will
+ just include a CREATE EXTENSION command in dumps, instead.
+ This vastly simplifies migration to a new version of the extension
+ that might contain more or different objects than the old version.
+ Note however that you must have the extension's control, script, and
+ other files available when loading such a dump into a new database.
+
+ PostgreSQL will not let you drop an individual object
+ contained in an extension, except by dropping the whole extension.
+ Also, while you can change the definition of an extension member object
+ (for example, via CREATE OR REPLACE FUNCTION for a
+ function), bear in mind that the modified definition will not be dumped
+ by pg_dump. Such a change is usually only sensible if
+ you concurrently make the same change in the extension's script file.
+ (But there are special provisions for tables containing configuration
+ data; see Section 38.17.3.)
+ In production situations, it's generally better to create an extension
+ update script to perform changes to extension member objects.
+
+ The extension script may set privileges on objects that are part of the
+ extension, using GRANT and REVOKE
+ statements. The final set of privileges for each object (if any are set)
+ will be stored in the
+ pg_init_privs
+ system catalog. When pg_dump is used, the
+ CREATE EXTENSION command will be included in the dump, followed
+ by the set of GRANT and REVOKE
+ statements necessary to set the privileges on the objects to what they were
+ at the time the dump was taken.
+
+ PostgreSQL does not currently support extension scripts
+ issuing CREATE POLICY or SECURITY LABEL
+ statements. These are expected to be set after the extension has been
+ created. All RLS policies and security labels on extension objects will be
+ included in dumps created by pg_dump.
+
+ The extension mechanism also has provisions for packaging modification
+ scripts that adjust the definitions of the SQL objects contained in an
+ extension. For example, if version 1.1 of an extension adds one function
+ and changes the body of another function compared to 1.0, the extension
+ author can provide an update script that makes just those
+ two changes. The ALTER EXTENSION UPDATE command can then
+ be used to apply these changes and track which version of the extension
+ is actually installed in a given database.
+
+ The kinds of SQL objects that can be members of an extension are shown in
+ the description of ALTER EXTENSION. Notably, objects
+ that are database-cluster-wide, such as databases, roles, and tablespaces,
+ cannot be extension members since an extension is only known within one
+ database. (Although an extension script is not prohibited from creating
+ such objects, if it does so they will not be tracked as part of the
+ extension.) Also notice that while a table can be a member of an
+ extension, its subsidiary objects such as indexes are not directly
+ considered members of the extension.
+ Another important point is that schemas can belong to extensions, but not
+ vice versa: an extension as such has an unqualified name and does not
+ exist “within” any schema. The extension's member objects,
+ however, will belong to schemas whenever appropriate for their object
+ types. It may or may not be appropriate for an extension to own the
+ schema(s) its member objects are within.
+
+ If an extension's script creates any temporary objects (such as temp
+ tables), those objects are treated as extension members for the
+ remainder of the current session, but are automatically dropped at
+ session end, as any temporary object would be. This is an exception
+ to the rule that extension member objects cannot be dropped without
+ dropping the whole extension.
+
+ The CREATE EXTENSION command relies on a control
+ file for each extension, which must be named the same as the extension
+ with a suffix of .control, and must be placed in the
+ installation's SHAREDIR/extension directory. There
+ must also be at least one SQL script file, which follows the
+ naming pattern
+ extension--version.sql
+ (for example, foo--1.0.sql for version 1.0 of
+ extension foo). By default, the script file(s) are also
+ placed in the SHAREDIR/extension directory; but the
+ control file can specify a different directory for the script file(s).
+
+ The file format for an extension control file is the same as for the
+ postgresql.conf file, namely a list of
+ parameter_name=value
+ assignments, one per line. Blank lines and comments introduced by
+ # are allowed. Be sure to quote any value that is not
+ a single word or number.
+
+ A control file can set the following parameters:
+
+ The directory containing the extension's SQL script
+ file(s). Unless an absolute path is given, the name is relative to
+ the installation's SHAREDIR directory. The
+ default behavior is equivalent to specifying
+ directory = 'extension'.
+
+ The default version of the extension (the one that will be installed
+ if no version is specified in CREATE EXTENSION). Although
+ this can be omitted, that will result in CREATE EXTENSION
+ failing if no VERSION option appears, so you generally
+ don't want to do that.
+
+ A comment (any string) about the extension. The comment is applied
+ when initially creating an extension, but not during extension updates
+ (since that might override user-added comments). Alternatively,
+ the extension's comment can be set by writing
+ a COMMENT command in the script file.
+
+ The character set encoding used by the script file(s). This should
+ be specified if the script files contain any non-ASCII characters.
+ Otherwise the files will be assumed to be in the database encoding.
+
+ The value of this parameter will be substituted for each occurrence
+ of MODULE_PATHNAME in the script file(s). If it is not
+ set, no substitution is made. Typically, this is set to
+ $libdir/shared_library_name and
+ then MODULE_PATHNAME is used in CREATE
+ FUNCTION commands for C-language functions, so that the script
+ files do not need to hard-wire the name of the shared library.
+
+ A list of names of extensions that this extension depends on,
+ for example requires = 'foo, bar'. Those
+ extensions must be installed before this one can be installed.
+
+ A list of names of extensions that this extension depends on that
+ should be barred from changing their schemas via ALTER
+ EXTENSION ... SET SCHEMA.
+ This is needed if this extension's script references the name
+ of a required extension's schema (using
+ the @extschema:name@
+ syntax) in a way that cannot track renames.
+
+ If this parameter is true (which is the default),
+ only superusers can create the extension or update it to a new
+ version (but see also trusted, below).
+ If it is set to false, just the privileges
+ required to execute the commands in the installation or update script
+ are required.
+ This should normally be set to true if any of the
+ script commands require superuser privileges. (Such commands would
+ fail anyway, but it's more user-friendly to give the error up front.)
+
+ This parameter, if set to true (which is not the
+ default), allows some non-superusers to install an extension that
+ has superuser set to true.
+ Specifically, installation will be permitted for anyone who has
+ CREATE privilege on the current database.
+ When the user executing CREATE EXTENSION is not
+ a superuser but is allowed to install by virtue of this parameter,
+ then the installation or update script is run as the bootstrap
+ superuser, not as the calling user.
+ This parameter is irrelevant if superuser is
+ false.
+ Generally, this should not be set true for extensions that could
+ allow access to otherwise-superuser-only abilities, such as
+ file system access.
+ Also, marking an extension trusted requires significant extra effort
+ to write the extension's installation and update script(s) securely;
+ see Section 38.17.6.
+
+ An extension is relocatable if it is possible to move
+ its contained objects into a different schema after initial creation
+ of the extension. The default is false, i.e., the
+ extension is not relocatable.
+ See Section 38.17.2 for more information.
+
+ This parameter can only be set for non-relocatable extensions.
+ It forces the extension to be loaded into exactly the named schema
+ and not any other.
+ The schema parameter is consulted only when
+ initially creating an extension, not during extension updates.
+ See Section 38.17.2 for more information.
+
+ In addition to the primary control file
+ extension.control,
+ an extension can have secondary control files named in the style
+ extension--version.control.
+ If supplied, these must be located in the script file directory.
+ Secondary control files follow the same format as the primary control
+ file. Any parameters set in a secondary control file override the
+ primary control file when installing or updating to that version of
+ the extension. However, the parameters directory and
+ default_version cannot be set in a secondary control file.
+
+ An extension's SQL script files can contain any SQL commands,
+ except for transaction control commands (BEGIN,
+ COMMIT, etc.) and commands that cannot be executed inside a
+ transaction block (such as VACUUM). This is because the
+ script files are implicitly executed within a transaction block.
+
+ An extension's SQL script files can also contain lines
+ beginning with \echo, which will be ignored (treated as
+ comments) by the extension mechanism. This provision is commonly used
+ to throw an error if the script file is fed to psql
+ rather than being loaded via CREATE EXTENSION (see example
+ script in Section 38.17.7).
+ Without that, users might accidentally load the
+ extension's contents as “loose” objects rather than as an
+ extension, a state of affairs that's a bit tedious to recover from.
+
+ If the extension script contains the
+ string @extowner@, that string is replaced with the
+ (suitably quoted) name of the user calling CREATE
+ EXTENSION or ALTER EXTENSION. Typically
+ this feature is used by extensions that are marked trusted to assign
+ ownership of selected objects to the calling user rather than the
+ bootstrap superuser. (One should be careful about doing so, however.
+ For example, assigning ownership of a C-language function to a
+ non-superuser would create a privilege escalation path for that user.)
+
+ While the script files can contain any characters allowed by the specified
+ encoding, control files should contain only plain ASCII, because there
+ is no way for PostgreSQL to know what encoding a
+ control file is in. In practice this is only an issue if you want to
+ use non-ASCII characters in the extension's comment. Recommended
+ practice in that case is to not use the control file comment
+ parameter, but instead use COMMENT ON EXTENSION
+ within a script file to set the comment.
+
+ Users often wish to load the objects contained in an extension into a
+ different schema than the extension's author had in mind. There are
+ three supported levels of relocatability:
+
+ A fully relocatable extension can be moved into another schema
+ at any time, even after it's been loaded into a database.
+ This is done with the ALTER EXTENSION SET SCHEMA
+ command, which automatically renames all the member objects into
+ the new schema. Normally, this is only possible if the extension
+ contains no internal assumptions about what schema any of its
+ objects are in. Also, the extension's objects must all be in one
+ schema to begin with (ignoring objects that do not belong to any
+ schema, such as procedural languages). Mark a fully relocatable
+ extension by setting relocatable = true in its control
+ file.
+
+ An extension might be relocatable during installation but not
+ afterwards. This is typically the case if the extension's script
+ file needs to reference the target schema explicitly, for example
+ in setting search_path properties for SQL functions.
+ For such an extension, set relocatable = false in its
+ control file, and use @extschema@ to refer to the target
+ schema in the script file. All occurrences of this string will be
+ replaced by the actual target schema's name (double-quoted if
+ necessary) before the script is executed. The user can set the
+ target schema using the
+ SCHEMA option of CREATE EXTENSION.
+
+ If the extension does not support relocation at all, set
+ relocatable = false in its control file, and also set
+ schema to the name of the intended target schema. This
+ will prevent use of the SCHEMA option of CREATE
+ EXTENSION, unless it specifies the same schema named in the control
+ file. This choice is typically necessary if the extension contains
+ internal assumptions about its schema name that can't be replaced by
+ uses of @extschema@. The @extschema@
+ substitution mechanism is available in this case too, although it is
+ of limited use since the schema name is determined by the control file.
+
+ In all cases, the script file will be executed with
+ search_path initially set to point to the target
+ schema; that is, CREATE EXTENSION does the equivalent of
+ this:
+
+SET LOCAL search_path TO @extschema@, pg_temp;
+
+ This allows the objects created by the script file to go into the target
+ schema. The script file can change search_path if it wishes,
+ but that is generally undesirable. search_path is restored
+ to its previous setting upon completion of CREATE EXTENSION.
+
+ The target schema is determined by the schema parameter in
+ the control file if that is given, otherwise by the SCHEMA
+ option of CREATE EXTENSION if that is given, otherwise the
+ current default object creation schema (the first one in the caller's
+ search_path). When the control file schema
+ parameter is used, the target schema will be created if it doesn't
+ already exist, but in the other two cases it must already exist.
+
+ If any prerequisite extensions are listed in requires
+ in the control file, their target schemas are added to the initial
+ setting of search_path, following the new
+ extension's target schema. This allows their objects to be visible to
+ the new extension's script file.
+
+ For security, pg_temp is automatically appended to
+ the end of search_path in all cases.
+
+ Although a non-relocatable extension can contain objects spread across
+ multiple schemas, it is usually desirable to place all the objects meant
+ for external use into a single schema, which is considered the extension's
+ target schema. Such an arrangement works conveniently with the default
+ setting of search_path during creation of dependent
+ extensions.
+
+ If an extension references objects belonging to another extension,
+ it is recommended to schema-qualify those references. To do that,
+ write @extschema:name@
+ in the extension's script file, where name
+ is the name of the other extension (which must be listed in this
+ extension's requires list). This string will be
+ replaced by the name (double-quoted if necessary) of that extension's
+ target schema.
+ Although this notation avoids the need to make hard-wired assumptions
+ about schema names in the extension's script file, its use may embed
+ the other extension's schema name into the installed objects of this
+ extension. (Typically, that happens
+ when @extschema:name@ is
+ used inside a string literal, such as a function body or
+ a search_path setting. In other cases, the object
+ reference is reduced to an OID during parsing and does not require
+ subsequent lookups.) If the other extension's schema name is so
+ embedded, you should prevent the other extension from being relocated
+ after yours is installed, by adding the name of the other extension to
+ this one's no_relocate list.
+
+ Some extensions include configuration tables, which contain data that
+ might be added or changed by the user after installation of the
+ extension. Ordinarily, if a table is part of an extension, neither
+ the table's definition nor its content will be dumped by
+ pg_dump. But that behavior is undesirable for a
+ configuration table; any data changes made by the user need to be
+ included in dumps, or the extension will behave differently after a dump
+ and restore.
+
+ To solve this problem, an extension's script file can mark a table
+ or a sequence it has created as a configuration relation, which will
+ cause pg_dump to include the table's or the sequence's
+ contents (not its definition) in dumps. To do that, call the function
+ pg_extension_config_dump(regclass, text) after creating the
+ table or the sequence, for example
+
+ Any number of tables or sequences can be marked this way. Sequences
+ associated with serial or bigserial columns can
+ be marked as well.
+
+ When the second argument of pg_extension_config_dump is
+ an empty string, the entire contents of the table are dumped by
+ pg_dump. This is usually only correct if the table
+ is initially empty as created by the extension script. If there is
+ a mixture of initial data and user-provided data in the table,
+ the second argument of pg_extension_config_dump provides
+ a WHERE condition that selects the data to be dumped.
+ For example, you might do
+
+CREATE TABLE my_config (key text, value text, standard_entry boolean);
+
+SELECT pg_catalog.pg_extension_config_dump('my_config', 'WHERE NOT standard_entry');
+
+ and then make sure that standard_entry is true only
+ in the rows created by the extension's script.
+
+ For sequences, the second argument of pg_extension_config_dump
+ has no effect.
+
+ More complicated situations, such as initially-provided rows that might
+ be modified by users, can be handled by creating triggers on the
+ configuration table to ensure that modified rows are marked correctly.
+
+ You can alter the filter condition associated with a configuration table
+ by calling pg_extension_config_dump again. (This would
+ typically be useful in an extension update script.) The only way to mark
+ a table as no longer a configuration table is to dissociate it from the
+ extension with ALTER EXTENSION ... DROP TABLE.
+
+ Note that foreign key relationships between these tables will dictate the
+ order in which the tables are dumped out by pg_dump. Specifically, pg_dump
+ will attempt to dump the referenced-by table before the referencing table.
+ As the foreign key relationships are set up at CREATE EXTENSION time (prior
+ to data being loaded into the tables) circular dependencies are not
+ supported. When circular dependencies exist, the data will still be dumped
+ out but the dump will not be able to be restored directly and user
+ intervention will be required.
+
+ Sequences associated with serial or bigserial columns
+ need to be directly marked to dump their state. Marking their parent
+ relation is not enough for this purpose.
+
+ One advantage of the extension mechanism is that it provides convenient
+ ways to manage updates to the SQL commands that define an extension's
+ objects. This is done by associating a version name or number with
+ each released version of the extension's installation script.
+ In addition, if you want users to be able to update their databases
+ dynamically from one version to the next, you should provide
+ update scripts that make the necessary changes to go from
+ one version to the next. Update scripts have names following the pattern
+ extension--old_version--target_version.sql
+ (for example, foo--1.0--1.1.sql contains the commands to modify
+ version 1.0 of extension foo into version
+ 1.1).
+
+ Given that a suitable update script is available, the command
+ ALTER EXTENSION UPDATE will update an installed extension
+ to the specified new version. The update script is run in the same
+ environment that CREATE EXTENSION provides for installation
+ scripts: in particular, search_path is set up in the same
+ way, and any new objects created by the script are automatically added
+ to the extension. Also, if the script chooses to drop extension member
+ objects, they are automatically dissociated from the extension.
+
+ If an extension has secondary control files, the control parameters
+ that are used for an update script are those associated with the script's
+ target (new) version.
+
+ ALTER EXTENSION is able to execute sequences of update
+ script files to achieve a requested update. For example, if only
+ foo--1.0--1.1.sql and foo--1.1--2.0.sql are
+ available, ALTER EXTENSION will apply them in sequence if an
+ update to version 2.0 is requested when 1.0 is
+ currently installed.
+
+ PostgreSQL doesn't assume anything about the properties
+ of version names: for example, it does not know whether 1.1
+ follows 1.0. It just matches up the available version names
+ and follows the path that requires applying the fewest update scripts.
+ (A version name can actually be any string that doesn't contain
+ -- or leading or trailing -.)
+
+ Sometimes it is useful to provide “downgrade” scripts, for
+ example foo--1.1--1.0.sql to allow reverting the changes
+ associated with version 1.1. If you do that, be careful
+ of the possibility that a downgrade script might unexpectedly
+ get applied because it yields a shorter path. The risky case is where
+ there is a “fast path” update script that jumps ahead several
+ versions as well as a downgrade script to the fast path's start point.
+ It might take fewer steps to apply the downgrade and then the fast
+ path than to move ahead one version at a time. If the downgrade script
+ drops any irreplaceable objects, this will yield undesirable results.
+
+ To check for unexpected update paths, use this command:
+
+SELECT * FROM pg_extension_update_paths('extension_name');
+
+ This shows each pair of distinct known version names for the specified
+ extension, together with the update path sequence that would be taken to
+ get from the source version to the target version, or NULL if
+ there is no available update path. The path is shown in textual form
+ with -- separators. You can use
+ regexp_split_to_array(path,'--') if you prefer an array
+ format.
+
38.17.5. Installing Extensions Using Update Scripts #
+ An extension that has been around for awhile will probably exist in
+ several versions, for which the author will need to write update scripts.
+ For example, if you have released a foo extension in
+ versions 1.0, 1.1, and 1.2, there
+ should be update scripts foo--1.0--1.1.sql
+ and foo--1.1--1.2.sql.
+ Before PostgreSQL 10, it was necessary to also create
+ new script files foo--1.1.sql and foo--1.2.sql
+ that directly build the newer extension versions, or else the newer
+ versions could not be installed directly, only by
+ installing 1.0 and then updating. That was tedious and
+ duplicative, but now it's unnecessary, because CREATE
+ EXTENSION can follow update chains automatically.
+ For example, if only the script
+ files foo--1.0.sql, foo--1.0--1.1.sql,
+ and foo--1.1--1.2.sql are available then a request to
+ install version 1.2 is honored by running those three
+ scripts in sequence. The processing is the same as if you'd first
+ installed 1.0 and then updated to 1.2.
+ (As with ALTER EXTENSION UPDATE, if multiple pathways are
+ available then the shortest is preferred.) Arranging an extension's
+ script files in this style can reduce the amount of maintenance effort
+ needed to produce small updates.
+
+ If you use secondary (version-specific) control files with an extension
+ maintained in this style, keep in mind that each version needs a control
+ file even if it has no stand-alone installation script, as that control
+ file will determine how the implicit update to that version is performed.
+ For example, if foo--1.0.control specifies requires
+ = 'bar' but foo's other control files do not, the
+ extension's dependency on bar will be dropped when updating
+ from 1.0 to another version.
+
+ Widely-distributed extensions should assume little about the database
+ they occupy. Therefore, it's appropriate to write functions provided
+ by an extension in a secure style that cannot be compromised by
+ search-path-based attacks.
+
+ An extension that has the superuser property set to
+ true must also consider security hazards for the actions taken within
+ its installation and update scripts. It is not terribly difficult for
+ a malicious user to create trojan-horse objects that will compromise
+ later execution of a carelessly-written extension script, allowing that
+ user to acquire superuser privileges.
+
+ If an extension is marked trusted, then its
+ installation schema can be selected by the installing user, who might
+ intentionally use an insecure schema in hopes of gaining superuser
+ privileges. Therefore, a trusted extension is extremely exposed from a
+ security standpoint, and all its script commands must be carefully
+ examined to ensure that no compromise is possible.
+
+ Advice about writing functions securely is provided in
+ Section 38.17.6.1 below, and advice
+ about writing installation scripts securely is provided in
+ Section 38.17.6.2.
+
38.17.6.1. Security Considerations for Extension Functions #
+ SQL-language and PL-language functions provided by extensions are at
+ risk of search-path-based attacks when they are executed, since
+ parsing of these functions occurs at execution time not creation time.
+
+ The CREATE
+ FUNCTION reference page contains advice about
+ writing SECURITY DEFINER functions safely. It's
+ good practice to apply those techniques for any function provided by
+ an extension, since the function might be called by a high-privilege
+ user.
+
+ If you cannot set the search_path to contain only
+ secure schemas, assume that each unqualified name could resolve to an
+ object that a malicious user has defined. Beware of constructs that
+ depend on search_path implicitly; for
+ example, IN
+ and CASE expression WHEN
+ always select an operator using the search path. In their place, use
+ OPERATOR(schema.=) ANY
+ and CASE WHEN expression.
+
+ A general-purpose extension usually should not assume that it's been
+ installed into a secure schema, which means that even schema-qualified
+ references to its own objects are not entirely risk-free. For
+ example, if the extension has defined a
+ function myschema.myfunc(bigint) then a call such
+ as myschema.myfunc(42) could be captured by a
+ hostile function myschema.myfunc(integer). Be
+ careful that the data types of function and operator parameters exactly
+ match the declared argument types, using explicit casts where necessary.
+
38.17.6.2. Security Considerations for Extension Scripts #
+ An extension installation or update script should be written to guard
+ against search-path-based attacks occurring when the script executes.
+ If an object reference in the script can be made to resolve to some
+ other object than the script author intended, then a compromise might
+ occur immediately, or later when the mis-defined extension object is
+ used.
+
+ DDL commands such as CREATE FUNCTION
+ and CREATE OPERATOR CLASS are generally secure,
+ but beware of any command having a general-purpose expression as a
+ component. For example, CREATE VIEW needs to be
+ vetted, as does a DEFAULT expression
+ in CREATE FUNCTION.
+
+ Sometimes an extension script might need to execute general-purpose
+ SQL, for example to make catalog adjustments that aren't possible via
+ DDL. Be careful to execute such commands with a
+ secure search_path; do not
+ trust the path provided by CREATE/ALTER EXTENSION
+ to be secure. Best practice is to temporarily
+ set search_path to 'pg_catalog,
+ pg_temp' and insert references to the extension's
+ installation schema explicitly where needed. (This practice might
+ also be helpful for creating views.) Examples can be found in
+ the contrib modules in
+ the PostgreSQL source code distribution.
+
+ Cross-extension references are extremely difficult to make fully
+ secure, partially because of uncertainty about which schema the other
+ extension is in. The hazards are reduced if both extensions are
+ installed in the same schema, because then a hostile object cannot be
+ placed ahead of the referenced extension in the installation-time
+ search_path. However, no mechanism currently exists
+ to require that. For now, best practice is to not mark an extension
+ trusted if it depends on another one, unless that other one is always
+ installed in pg_catalog.
+
+ Here is a complete example of an SQL-only
+ extension, a two-element composite type that can store any type of value
+ in its slots, which are named “k” and “v”. Non-text
+ values are automatically coerced to text for storage.
+
+ The script file pair--1.0.sql looks like this:
+
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "CREATE EXTENSION pair" to load this file. \quit
+
+CREATE TYPE pair AS ( k text, v text );
+
+CREATE FUNCTION pair(text, text)
+RETURNS pair LANGUAGE SQL AS 'SELECT ROW($1, $2)::@extschema@.pair;';
+
+CREATE OPERATOR ~> (LEFTARG = text, RIGHTARG = text, FUNCTION = pair);
+
+-- "SET search_path" is easy to get right, but qualified names perform better.
+CREATE FUNCTION lower(pair)
+RETURNS pair LANGUAGE SQL
+AS 'SELECT ROW(lower($1.k), lower($1.v))::@extschema@.pair;'
+SET search_path = pg_temp;
+
+CREATE FUNCTION pair_concat(pair, pair)
+RETURNS pair LANGUAGE SQL
+AS 'SELECT ROW($1.k OPERATOR(pg_catalog.||) $2.k,
+ $1.v OPERATOR(pg_catalog.||) $2.v)::@extschema@.pair;';
+
+
+
+ The control file pair.control looks like this:
+
+
+# pair extension
+comment = 'A key/value pair data type'
+default_version = '1.0'
+# cannot be relocatable because of use of @extschema@
+relocatable = false
+
+
+ While you hardly need a makefile to install these two files into the
+ correct directory, you could use a Makefile containing this:
+
+
+
+ This makefile relies on PGXS, which is described
+ in Section 38.18. The command make install
+ will install the control and script files into the correct
+ directory as reported by pg_config.
+
+ Once the files are installed, use the
+ CREATE EXTENSION command to load the objects into
+ any particular database.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/extend-how.html b/pgsql/doc/postgresql/html/extend-how.html
new file mode 100644
index 0000000000000000000000000000000000000000..329b3a149776eb91cb0283500bf96615a0e8ac90
--- /dev/null
+++ b/pgsql/doc/postgresql/html/extend-how.html
@@ -0,0 +1,33 @@
+
+38.1. How Extensibility Works
+ PostgreSQL is extensible because its operation is
+ catalog-driven. If you are familiar with standard
+ relational database systems, you know that they store information
+ about databases, tables, columns, etc., in what are
+ commonly known as system catalogs. (Some systems call
+ this the data dictionary.) The catalogs appear to the
+ user as tables like any other, but the DBMS stores
+ its internal bookkeeping in them. One key difference
+ between PostgreSQL and standard relational database systems is
+ that PostgreSQL stores much more information in its
+ catalogs: not only information about tables and columns,
+ but also information about data types, functions, access
+ methods, and so on. These tables can be modified by
+ the user, and since PostgreSQL bases its operation
+ on these tables, this means that PostgreSQL can be
+ extended by users. By comparison, conventional
+ database systems can only be extended by changing hardcoded
+ procedures in the source code or by loading modules
+ specially written by the DBMS vendor.
+
+ The PostgreSQL server can moreover
+ incorporate user-written code into itself through dynamic loading.
+ That is, the user can specify an object code file (e.g., a shared
+ library) that implements a new type or function, and
+ PostgreSQL will load it as required.
+ Code written in SQL is even more trivial to add
+ to the server. This ability to modify its operation “on the
+ fly” makes PostgreSQL uniquely
+ suited for rapid prototyping of new applications and storage
+ structures.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/extend-pgxs.html b/pgsql/doc/postgresql/html/extend-pgxs.html
new file mode 100644
index 0000000000000000000000000000000000000000..0e52a0a3a679d1c6aee45050649a47a9c10bdc40
--- /dev/null
+++ b/pgsql/doc/postgresql/html/extend-pgxs.html
@@ -0,0 +1,230 @@
+
+38.18. Extension Building Infrastructure
+ If you are thinking about distributing your
+ PostgreSQL extension modules, setting up a
+ portable build system for them can be fairly difficult. Therefore
+ the PostgreSQL installation provides a build
+ infrastructure for extensions, called PGXS, so
+ that simple extension modules can be built simply against an
+ already installed server. PGXS is mainly intended
+ for extensions that include C code, although it can be used for
+ pure-SQL extensions too. Note that PGXS is not
+ intended to be a universal build system framework that can be used
+ to build any software interfacing to PostgreSQL;
+ it simply automates common build rules for simple server extension
+ modules. For more complicated packages, you might need to write your
+ own build system.
+
+ To use the PGXS infrastructure for your extension,
+ you must write a simple makefile.
+ In the makefile, you need to set some variables
+ and include the global PGXS makefile.
+ Here is an example that builds an extension module named
+ isbn_issn, consisting of a shared library containing
+ some C code, an extension control file, an SQL script, an include file
+ (only needed if other modules might need to access the extension functions
+ without going via SQL), and a documentation text file:
+
+ subdirectory of prefix/share
+ into which DATA and DOCS files should be installed
+ (if not set, default is extension if
+ EXTENSION is set,
+ or contrib if not)
+
+ Files to (optionally build and) install under
+ prefix/include/server/$MODULEDIR/$MODULE_big.
+
+ Unlike DATA_built, files in HEADERS_built
+ are not removed by the clean target; if you want them removed,
+ also add them to EXTRA_CLEAN or add your own rules to do it.
+
+ Files to install (after building if specified) under
+ prefix/include/server/$MODULEDIR/$MODULE,
+ where $MODULE must be a module name used
+ in MODULES or MODULE_big.
+
+ Unlike DATA_built, files in HEADERS_built_$MODULE
+ are not removed by the clean target; if you want them removed,
+ also add them to EXTRA_CLEAN or add your own rules to do it.
+
+ It is legal to use both variables for the same module, or any
+ combination, unless you have two module names in the
+ MODULES list that differ only by the presence of a
+ prefix built_, which would cause ambiguity. In
+ that (hopefully unlikely) case, you should use only the
+ HEADERS_built_$MODULE variables.
+
+ path to pg_config program for the
+ PostgreSQL installation to build against
+ (typically just pg_config to use the first one in your
+ PATH)
+
+
+ Put this makefile as Makefile in the directory
+ which holds your extension. Then you can do
+ make to compile, and then make
+ install to install your module. By default, the extension is
+ compiled and installed for the
+ PostgreSQL installation that
+ corresponds to the first pg_config program
+ found in your PATH. You can use a different installation by
+ setting PG_CONFIG to point to its
+ pg_config program, either within the makefile
+ or on the make command line.
+
+ You can also run make in a directory outside the source
+ tree of your extension, if you want to keep the build directory separate.
+ This procedure is also called a
+ VPATH
+ build. Here's how:
+
+ Alternatively, you can set up a directory for a VPATH build in a similar
+ way to how it is done for the core code. One way to do this is using the
+ core script config/prep_buildtree. Once this has been done
+ you can build by setting the make variable
+ VPATH like this:
+
+ This procedure can work with a greater variety of directory layouts.
+
+ The scripts listed in the REGRESS variable are used for
+ regression testing of your module, which can be invoked by make
+ installcheck after doing make install. For this to
+ work you must have a running PostgreSQL server.
+ The script files listed in REGRESS must appear in a
+ subdirectory named sql/ in your extension's directory.
+ These files must have extension .sql, which must not be
+ included in the REGRESS list in the makefile. For each
+ test there should also be a file containing the expected output in a
+ subdirectory named expected/, with the same stem and
+ extension .out. make installcheck
+ executes each test script with psql, and compares the
+ resulting output to the matching expected file. Any differences will be
+ written to the file regression.diffs in diff
+ -c format. Note that trying to run a test that is missing its
+ expected file will be reported as “trouble”, so make sure you
+ have all expected files.
+
+ The scripts listed in the ISOLATION variable are used
+ for tests stressing behavior of concurrent session with your module, which
+ can be invoked by make installcheck after doing
+ make install. For this to work you must have a
+ running PostgreSQL server. The script files
+ listed in ISOLATION must appear in a subdirectory
+ named specs/ in your extension's directory. These files
+ must have extension .spec, which must not be included
+ in the ISOLATION list in the makefile. For each test
+ there should also be a file containing the expected output in a
+ subdirectory named expected/, with the same stem and
+ extension .out. make installcheck
+ executes each test script, and compares the resulting output to the
+ matching expected file. Any differences will be written to the file
+ output_iso/regression.diffs in
+ diff -c format. Note that trying to run a test that is
+ missing its expected file will be reported as “trouble”, so
+ make sure you have all expected files.
+
+ TAP_TESTS enables the use of TAP tests. Data from each
+ run is present in a subdirectory named tmp_check/.
+ See also Section 33.4 for more details.
+
Tip
+ The easiest way to create the expected files is to create empty files,
+ then do a test run (which will of course report differences). Inspect
+ the actual result files found in the results/
+ directory (for tests in REGRESS), or
+ output_iso/results/ directory (for tests in
+ ISOLATION), then copy them to
+ expected/ if they match what you expect from the test.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/extend-type-system.html b/pgsql/doc/postgresql/html/extend-type-system.html
new file mode 100644
index 0000000000000000000000000000000000000000..402787f5c8ad05daa99583bf58e402d8674c1921
--- /dev/null
+++ b/pgsql/doc/postgresql/html/extend-type-system.html
@@ -0,0 +1,222 @@
+
+38.2. The PostgreSQL Type System
+ Base types are those, like integer, that are
+ implemented below the level of the SQL language
+ (typically in a low-level language such as C). They generally
+ correspond to what are often known as abstract data types.
+ PostgreSQL can only operate on such
+ types through functions provided by the user and only understands
+ the behavior of such types to the extent that the user describes
+ them.
+ The built-in base types are described in Chapter 8.
+
+ Enumerated (enum) types can be considered as a subcategory of base
+ types. The main difference is that they can be created using
+ just SQL commands, without any low-level programming.
+ Refer to Section 8.7 for more information.
+
+ PostgreSQL has three kinds
+ of “container” types, which are types that contain multiple
+ values of other types. These are arrays, composites, and ranges.
+
+ Arrays can hold multiple values that are all of the same type. An array
+ type is automatically created for each base type, composite type, range
+ type, and domain type. But there are no arrays of arrays. So far as
+ the type system is concerned, multi-dimensional arrays are the same as
+ one-dimensional arrays. Refer to Section 8.15 for more
+ information.
+
+ Composite types, or row types, are created whenever the user
+ creates a table. It is also possible to use CREATE TYPE to
+ define a “stand-alone” composite type with no associated
+ table. A composite type is simply a list of types with
+ associated field names. A value of a composite type is a row or
+ record of field values. Refer to Section 8.16
+ for more information.
+
+ A range type can hold two values of the same type, which are the lower
+ and upper bounds of the range. Range types are user-created, although
+ a few built-in ones exist. Refer to Section 8.17
+ for more information.
+
+ A domain is based on a particular underlying type and for many purposes
+ is interchangeable with its underlying type. However, a domain can have
+ constraints that restrict its valid values to a subset of what the
+ underlying type would allow. Domains are created using
+ the SQL command CREATE DOMAIN.
+ Refer to Section 8.18 for more information.
+
+ There are a few “pseudo-types” for special purposes.
+ Pseudo-types cannot appear as columns of tables or components of
+ container types, but they can be used to declare the argument and
+ result types of functions. This provides a mechanism within the
+ type system to identify special classes of functions. Table 8.27 lists the existing
+ pseudo-types.
+
+ Some pseudo-types of special interest are the polymorphic
+ types, which are used to declare polymorphic
+ functions. This powerful feature allows a single function
+ definition to operate on many different data types, with the specific
+ data type(s) being determined by the data types actually passed to it
+ in a particular call. The polymorphic types are shown in
+ Table 38.1. Some examples of
+ their use appear in Section 38.5.11.
+
Table 38.1. Polymorphic Types
Name
Family
Description
anyelement
Simple
Indicates that a function accepts any data type
anyarray
Simple
Indicates that a function accepts any array data type
anynonarray
Simple
Indicates that a function accepts any non-array data type
anyenum
Simple
Indicates that a function accepts any enum data type
+ (see Section 8.7)
+
anyrange
Simple
Indicates that a function accepts any range data type
+ (see Section 8.17)
+
anymultirange
Simple
Indicates that a function accepts any multirange data type
+ (see Section 8.17)
+
anycompatible
Common
Indicates that a function accepts any data type,
+ with automatic promotion of multiple arguments to a common data type
+
anycompatiblearray
Common
Indicates that a function accepts any array data type,
+ with automatic promotion of multiple arguments to a common data type
+
anycompatiblenonarray
Common
Indicates that a function accepts any non-array data type,
+ with automatic promotion of multiple arguments to a common data type
+
anycompatiblerange
Common
Indicates that a function accepts any range data type,
+ with automatic promotion of multiple arguments to a common data type
+
anycompatiblemultirange
Common
Indicates that a function accepts any multirange data type,
+ with automatic promotion of multiple arguments to a common data type
+
+ Polymorphic arguments and results are tied to each other and are resolved
+ to specific data types when a query calling a polymorphic function is
+ parsed. When there is more than one polymorphic argument, the actual
+ data types of the input values must match up as described below. If the
+ function's result type is polymorphic, or it has output parameters of
+ polymorphic types, the types of those results are deduced from the
+ actual types of the polymorphic inputs as described below.
+
+ For the “simple” family of polymorphic types, the
+ matching and deduction rules work like this:
+
+ Each position (either argument or return value) declared as
+ anyelement is allowed to have any specific actual
+ data type, but in any given call they must all be the
+ same actual type. Each
+ position declared as anyarray can have any array data type,
+ but similarly they must all be the same type. And similarly,
+ positions declared as anyrange must all be the same range
+ type. Likewise for anymultirange.
+
+ Furthermore, if there are
+ positions declared anyarray and others declared
+ anyelement, the actual array type in the
+ anyarray positions must be an array whose elements are
+ the same type appearing in the anyelement positions.
+ anynonarray is treated exactly the same as anyelement,
+ but adds the additional constraint that the actual type must not be
+ an array type.
+ anyenum is treated exactly the same as anyelement,
+ but adds the additional constraint that the actual type must
+ be an enum type.
+
+ Similarly, if there are positions declared anyrange
+ and others declared anyelement or anyarray,
+ the actual range type in the anyrange positions must be a
+ range whose subtype is the same type appearing in
+ the anyelement positions and the same as the element type
+ of the anyarray positions.
+ If there are positions declared anymultirange,
+ their actual multirange type must contain ranges matching parameters declared
+ anyrange and base elements matching parameters declared
+ anyelement and anyarray.
+
+ Thus, when more than one argument position is declared with a polymorphic
+ type, the net effect is that only certain combinations of actual argument
+ types are allowed. For example, a function declared as
+ equal(anyelement, anyelement) will take any two input values,
+ so long as they are of the same data type.
+
+ When the return value of a function is declared as a polymorphic type,
+ there must be at least one argument position that is also polymorphic,
+ and the actual data type(s) supplied for the polymorphic arguments
+ determine the actual
+ result type for that call. For example, if there were not already
+ an array subscripting mechanism, one could define a function that
+ implements subscripting as subscript(anyarray, integer)
+ returns anyelement. This declaration constrains the actual first
+ argument to be an array type, and allows the parser to infer the correct
+ result type from the actual first argument's type. Another example
+ is that a function declared as f(anyarray) returns anyenum
+ will only accept arrays of enum types.
+
+ In most cases, the parser can infer the actual data type for a
+ polymorphic result type from arguments that are of a different
+ polymorphic type in the same family; for example anyarray
+ can be deduced from anyelement or vice versa.
+ An exception is that a
+ polymorphic result of type anyrange requires an argument
+ of type anyrange; it cannot be deduced
+ from anyarray or anyelement arguments. This
+ is because there could be multiple range types with the same subtype.
+
+ Note that anynonarray and anyenum do not represent
+ separate type variables; they are the same type as
+ anyelement, just with an additional constraint. For
+ example, declaring a function as f(anyelement, anyenum)
+ is equivalent to declaring it as f(anyenum, anyenum):
+ both actual arguments have to be the same enum type.
+
+ For the “common” family of polymorphic types, the
+ matching and deduction rules work approximately the same as for
+ the “simple” family, with one major difference: the
+ actual types of the arguments need not be identical, so long as they
+ can be implicitly cast to a single common type. The common type is
+ selected following the same rules as for UNION and
+ related constructs (see Section 10.5).
+ Selection of the common type considers the actual types
+ of anycompatible and anycompatiblenonarray
+ inputs, the array element types of anycompatiblearray
+ inputs, the range subtypes of anycompatiblerange inputs,
+ and the multirange subtypes of anycompatiblemultirange
+ inputs. If anycompatiblenonarray is present then the
+ common type is required to be a non-array type. Once a common type is
+ identified, arguments in anycompatible
+ and anycompatiblenonarray positions are automatically
+ cast to that type, and arguments in anycompatiblearray
+ positions are automatically cast to the array type for that type.
+
+ Since there is no way to select a range type knowing only its subtype,
+ use of anycompatiblerange and/or
+ anycompatiblemultirange requires that all arguments declared
+ with that type have the same actual range and/or multirange type, and that
+ that type's subtype agree with the selected common type, so that no casting
+ of the range values is required. As with anyrange and
+ anymultirange, use of anycompatiblerange and
+ anymultirange as a function result type requires that there be
+ an anycompatiblerange or anycompatiblemultirange
+ argument.
+
+ Notice that there is no anycompatibleenum type. Such a
+ type would not be very useful, since there normally are not any
+ implicit casts to enum types, meaning that there would be no way to
+ resolve a common type for dissimilar enum inputs.
+
+ The “simple” and “common” polymorphic
+ families represent two independent sets of type variables. Consider
+ for example
+
+CREATE FUNCTION myfunc(a anyelement, b anyelement,
+ c anycompatible, d anycompatible)
+RETURNS anycompatible AS ...
+
+ In an actual call of this function, the first two inputs must have
+ exactly the same type. The last two inputs must be promotable to a
+ common type, but this type need not have anything to do with the type
+ of the first two inputs. The result will have the common type of the
+ last two inputs.
+
+ A variadic function (one taking a variable number of arguments, as in
+ Section 38.5.6) can be
+ polymorphic: this is accomplished by declaring its last parameter as
+ VARIADICanyarray or
+ VARIADICanycompatiblearray.
+ For purposes of argument
+ matching and determining the actual result type, such a function behaves
+ the same as if you had written the appropriate number of
+ anynonarray or anycompatiblenonarray
+ parameters.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/extend.html b/pgsql/doc/postgresql/html/extend.html
new file mode 100644
index 0000000000000000000000000000000000000000..124d0380fdcfa5a0ec2c0c9befb18f17f00b6178
--- /dev/null
+++ b/pgsql/doc/postgresql/html/extend.html
@@ -0,0 +1,20 @@
+
+Chapter 38. Extending SQL
+ operator classes for indexes (starting in Section 38.16)
+
+ packages of related objects (starting in Section 38.17)
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/external-admin-tools.html b/pgsql/doc/postgresql/html/external-admin-tools.html
new file mode 100644
index 0000000000000000000000000000000000000000..6e1f804f9563982e630cb202ff30403711bc69da
--- /dev/null
+++ b/pgsql/doc/postgresql/html/external-admin-tools.html
@@ -0,0 +1,7 @@
+
+H.2. Administration Tools
+ There are several administration tools available for
+ PostgreSQL. The most popular is
+ pgAdmin,
+ and there are several commercially available ones as well.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/external-extensions.html b/pgsql/doc/postgresql/html/external-extensions.html
new file mode 100644
index 0000000000000000000000000000000000000000..6991cdf0c7175b1d8db5bf8b8da83cd2bc65f427
--- /dev/null
+++ b/pgsql/doc/postgresql/html/external-extensions.html
@@ -0,0 +1,14 @@
+
+H.4. Extensions
+ PostgreSQL is designed to be easily extensible. For
+ this reason, extensions loaded into the database can function
+ just like features that are built in. The
+ contrib/ directory shipped with the source code
+ contains several extensions, which are described in
+ Appendix F. Other extensions are developed
+ independently, like PostGIS. Even
+ PostgreSQL replication solutions can be developed
+ externally. For example, Slony-I is a popular
+ primary/standby replication solution that is developed independently
+ from the core project.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/external-interfaces.html b/pgsql/doc/postgresql/html/external-interfaces.html
new file mode 100644
index 0000000000000000000000000000000000000000..2c8f67d04ccbcbbd4a405f44dfc26a3459623544
--- /dev/null
+++ b/pgsql/doc/postgresql/html/external-interfaces.html
@@ -0,0 +1,24 @@
+
+H.1. Client Interfaces
+ There are only two client interfaces included in the base
+ PostgreSQL distribution:
+
+ libpq is included because it is the
+ primary C language interface, and because many other client interfaces
+ are built on top of it.
+
+ ECPG is included because it depends on the
+ server-side SQL grammar, and is therefore sensitive to changes in
+ PostgreSQL itself.
+
+
+ All other language interfaces are external projects and are distributed
+ separately. A
+ list of language interfaces
+ is maintained on the PostgreSQL wiki. Note that some of these packages are
+ not released under the same license as PostgreSQL.
+ For more information on each language interface, including licensing terms,
+ refer to its website and documentation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/external-pl.html b/pgsql/doc/postgresql/html/external-pl.html
new file mode 100644
index 0000000000000000000000000000000000000000..d4920ad7daf293e9fe035dbe61f0e9cf6521bfad
--- /dev/null
+++ b/pgsql/doc/postgresql/html/external-pl.html
@@ -0,0 +1,18 @@
+
+H.3. Procedural Languages
+ PostgreSQL includes several procedural
+ languages with the base distribution: PL/pgSQL, PL/Tcl,
+ PL/Perl, and PL/Python.
+
+ In addition, there are a number of procedural languages that are developed
+ and maintained outside the core PostgreSQL
+ distribution. A list of
+ procedural languages
+ is maintained on the PostgreSQL wiki. Note that some of these projects are
+ not released under the same license as PostgreSQL.
+ For more information on each procedural language, including licensing
+ information, refer to its website
+ and documentation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/external-projects.html b/pgsql/doc/postgresql/html/external-projects.html
new file mode 100644
index 0000000000000000000000000000000000000000..7d63367682aa262dcf20b01058b97bd541154016
--- /dev/null
+++ b/pgsql/doc/postgresql/html/external-projects.html
@@ -0,0 +1,7 @@
+
+Appendix H. External Projects
+ PostgreSQL is a complex software project,
+ and managing the project is difficult. We have found that many
+ enhancements to PostgreSQL can be more
+ efficiently developed separately from the core project.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fdw-callbacks.html b/pgsql/doc/postgresql/html/fdw-callbacks.html
new file mode 100644
index 0000000000000000000000000000000000000000..45feeb988dcbf3bbe734ec49ed363457e097e788
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fdw-callbacks.html
@@ -0,0 +1,1266 @@
+
+59.2. Foreign Data Wrapper Callback Routines
+ The FDW handler function returns a palloc'd FdwRoutine
+ struct containing pointers to the callback functions described below.
+ The scan-related functions are required, the rest are optional.
+
+ The FdwRoutine struct type is declared in
+ src/include/foreign/fdwapi.h, which see for additional
+ details.
+
59.2.1. FDW Routines for Scanning Foreign Tables #
+
+void
+GetForeignRelSize(PlannerInfo *root,
+ RelOptInfo *baserel,
+ Oid foreigntableid);
+
+
+ Obtain relation size estimates for a foreign table. This is called
+ at the beginning of planning for a query that scans a foreign table.
+ root is the planner's global information about the query;
+ baserel is the planner's information about this table; and
+ foreigntableid is the pg_class OID of the
+ foreign table. (foreigntableid could be obtained from the
+ planner data structures, but it's passed explicitly to save effort.)
+
+ This function should update baserel->rows to be the
+ expected number of rows returned by the table scan, after accounting for
+ the filtering done by the restriction quals. The initial value of
+ baserel->rows is just a constant default estimate, which
+ should be replaced if at all possible. The function may also choose to
+ update baserel->width if it can compute a better estimate
+ of the average result row width.
+ (The initial value is based on column data types and on column
+ average-width values measured by the last ANALYZE.)
+ Also, this function may update baserel->tuples if
+ it can compute a better estimate of the foreign table's total row count.
+ (The initial value is
+ from pg_class.reltuples
+ which represents the total row count seen by the
+ last ANALYZE; it will be -1 if
+ no ANALYZE has been done on this foreign table.)
+
+void
+GetForeignPaths(PlannerInfo *root,
+ RelOptInfo *baserel,
+ Oid foreigntableid);
+
+
+ Create possible access paths for a scan on a foreign table.
+ This is called during query planning.
+ The parameters are the same as for GetForeignRelSize,
+ which has already been called.
+
+ This function must generate at least one access path
+ (ForeignPath node) for a scan on the foreign table and
+ must call add_path to add each such path to
+ baserel->pathlist. It's recommended to use
+ create_foreignscan_path to build the
+ ForeignPath nodes. The function can generate multiple
+ access paths, e.g., a path which has valid pathkeys to
+ represent a pre-sorted result. Each access path must contain cost
+ estimates, and can contain any FDW-private information that is needed to
+ identify the specific scan method intended.
+
+ForeignScan *
+GetForeignPlan(PlannerInfo *root,
+ RelOptInfo *baserel,
+ Oid foreigntableid,
+ ForeignPath *best_path,
+ List *tlist,
+ List *scan_clauses,
+ Plan *outer_plan);
+
+
+ Create a ForeignScan plan node from the selected foreign
+ access path. This is called at the end of query planning.
+ The parameters are as for GetForeignRelSize, plus
+ the selected ForeignPath (previously produced by
+ GetForeignPaths, GetForeignJoinPaths,
+ or GetForeignUpperPaths),
+ the target list to be emitted by the plan node,
+ the restriction clauses to be enforced by the plan node,
+ and the outer subplan of the ForeignScan,
+ which is used for rechecks performed by RecheckForeignScan.
+ (If the path is for a join rather than a base
+ relation, foreigntableid is InvalidOid.)
+
+ This function must create and return a ForeignScan plan
+ node; it's recommended to use make_foreignscan to build the
+ ForeignScan node.
+
+void
+BeginForeignScan(ForeignScanState *node,
+ int eflags);
+
+
+ Begin executing a foreign scan. This is called during executor startup.
+ It should perform any initialization needed before the scan can start,
+ but not start executing the actual scan (that should be done upon the
+ first call to IterateForeignScan).
+ The ForeignScanState node has already been created, but
+ its fdw_state field is still NULL. Information about
+ the table to scan is accessible through the
+ ForeignScanState node (in particular, from the underlying
+ ForeignScan plan node, which contains any FDW-private
+ information provided by GetForeignPlan).
+ eflags contains flag bits describing the executor's
+ operating mode for this plan node.
+
+ Note that when (eflags & EXEC_FLAG_EXPLAIN_ONLY) is
+ true, this function should not perform any externally-visible actions;
+ it should only do the minimum required to make the node state valid
+ for ExplainForeignScan and EndForeignScan.
+
+
+ Fetch one row from the foreign source, returning it in a tuple table slot
+ (the node's ScanTupleSlot should be used for this
+ purpose). Return NULL if no more rows are available. The tuple table
+ slot infrastructure allows either a physical or virtual tuple to be
+ returned; in most cases the latter choice is preferable from a
+ performance standpoint. Note that this is called in a short-lived memory
+ context that will be reset between invocations. Create a memory context
+ in BeginForeignScan if you need longer-lived storage, or use
+ the es_query_cxt of the node's EState.
+
+ The rows returned must match the fdw_scan_tlist target
+ list if one was supplied, otherwise they must match the row type of the
+ foreign table being scanned. If you choose to optimize away fetching
+ columns that are not needed, you should insert nulls in those column
+ positions, or else generate a fdw_scan_tlist list with
+ those columns omitted.
+
+ Note that PostgreSQL's executor doesn't care
+ whether the rows returned violate any constraints that were defined on
+ the foreign table — but the planner does care, and may optimize
+ queries incorrectly if there are rows visible in the foreign table that
+ do not satisfy a declared constraint. If a constraint is violated when
+ the user has declared that the constraint should hold true, it may be
+ appropriate to raise an error (just as you would need to do in the case
+ of a data type mismatch).
+
+
+ Restart the scan from the beginning. Note that any parameters the
+ scan depends on may have changed value, so the new scan does not
+ necessarily return exactly the same rows.
+
+
+void
+EndForeignScan(ForeignScanState *node);
+
+
+ End the scan and release resources. It is normally not important
+ to release palloc'd memory, but for example open files and connections
+ to remote servers should be cleaned up.
+
+ If an FDW supports performing foreign joins remotely (rather than
+ by fetching both tables' data and doing the join locally), it should
+ provide this callback function:
+
+ Create possible access paths for a join of two (or more) foreign tables
+ that all belong to the same foreign server. This optional
+ function is called during query planning. As
+ with GetForeignPaths, this function should
+ generate ForeignPath path(s) for the
+ supplied joinrel
+ (use create_foreign_join_path to build them),
+ and call add_path to add these
+ paths to the set of paths considered for the join. But unlike
+ GetForeignPaths, it is not necessary that this function
+ succeed in creating at least one path, since paths involving local
+ joining are always possible.
+
+ Note that this function will be invoked repeatedly for the same join
+ relation, with different combinations of inner and outer relations; it is
+ the responsibility of the FDW to minimize duplicated work.
+
+ If a ForeignPath path is chosen for the join, it will
+ represent the entire join process; paths generated for the component
+ tables and subsidiary joins will not be used. Subsequent processing of
+ the join path proceeds much as it does for a path scanning a single
+ foreign table. One difference is that the scanrelid of
+ the resulting ForeignScan plan node should be set to zero,
+ since there is no single relation that it represents; instead,
+ the fs_relids field of the ForeignScan
+ node represents the set of relations that were joined. (The latter field
+ is set up automatically by the core planner code, and need not be filled
+ by the FDW.) Another difference is that, because the column list for a
+ remote join cannot be found from the system catalogs, the FDW must
+ fill fdw_scan_tlist with an appropriate list
+ of TargetEntry nodes, representing the set of columns
+ it will supply at run time in the tuples it returns.
+
Note
+ Beginning with PostgreSQL 16,
+ fs_relids includes the rangetable indexes
+ of outer joins, if any were involved in this join. The new field
+ fs_base_relids includes only base
+ relation indexes, and thus
+ mimics fs_relids's old semantics.
+
+ Create possible access paths for upper relation processing,
+ which is the planner's term for all post-scan/join query processing, such
+ as aggregation, window functions, sorting, and table updates. This
+ optional function is called during query planning. Currently, it is
+ called only if all base relation(s) involved in the query belong to the
+ same FDW. This function should generate ForeignPath
+ path(s) for any post-scan/join processing that the FDW knows how to
+ perform remotely
+ (use create_foreign_upper_path to build them),
+ and call add_path to add these paths to
+ the indicated upper relation. As with GetForeignJoinPaths,
+ it is not necessary that this function succeed in creating any paths,
+ since paths involving local processing are always possible.
+
+ The stage parameter identifies which post-scan/join step is
+ currently being considered. output_rel is the upper relation
+ that should receive paths representing computation of this step,
+ and input_rel is the relation representing the input to this
+ step. The extra parameter provides additional details,
+ currently, it is set only for UPPERREL_PARTIAL_GROUP_AGG
+ or UPPERREL_GROUP_AGG, in which case it points to a
+ GroupPathExtraData structure;
+ or for UPPERREL_FINAL, in which case it points to a
+ FinalPathExtraData structure.
+ (Note that ForeignPath paths added
+ to output_rel would typically not have any direct dependency
+ on paths of the input_rel, since their processing is expected
+ to be done externally. However, examining paths previously generated for
+ the previous processing step can be useful to avoid redundant planning
+ work.)
+
59.2.4. FDW Routines for Updating Foreign Tables #
+ If an FDW supports writable foreign tables, it should provide
+ some or all of the following callback functions depending on
+ the needs and capabilities of the FDW:
+
+
+ UPDATE and DELETE operations are performed
+ against rows previously fetched by the table-scanning functions. The
+ FDW may need extra information, such as a row ID or the values of
+ primary-key columns, to ensure that it can identify the exact row to
+ update or delete. To support that, this function can add extra hidden,
+ or “junk”, target columns to the list of columns that are to be
+ retrieved from the foreign table during an UPDATE or
+ DELETE.
+
+ To do that, construct a Var representing
+ an extra value you need, and pass it
+ to add_row_identity_var, along with a name for
+ the junk column. (You can do this more than once if several columns
+ are needed.) You must choose a distinct junk column name for each
+ different Var you need, except
+ that Vars that are identical except for
+ the varno field can and should share a
+ column name.
+ The core system uses the junk column names
+ tableoid for a
+ table's tableoid column,
+ ctid
+ or ctidN
+ for ctid,
+ wholerow
+ for a whole-row Var marked with
+ vartype = RECORD,
+ and wholerowN
+ for a whole-row Var with
+ vartype equal to the table's declared row type.
+ Re-use these names when you can (the planner will combine duplicate
+ requests for identical junk columns). If you need another kind of
+ junk column besides these, it might be wise to choose a name prefixed
+ with your extension name, to avoid conflicts against other FDWs.
+
+ If the AddForeignUpdateTargets pointer is set to
+ NULL, no extra target expressions are added.
+ (This will make it impossible to implement DELETE
+ operations, though UPDATE may still be feasible if the FDW
+ relies on an unchanging primary key to identify rows.)
+
+
+List *
+PlanForeignModify(PlannerInfo *root,
+ ModifyTable *plan,
+ Index resultRelation,
+ int subplan_index);
+
+
+ Perform any additional planning actions needed for an insert, update, or
+ delete on a foreign table. This function generates the FDW-private
+ information that will be attached to the ModifyTable plan
+ node that performs the update action. This private information must
+ have the form of a List, and will be delivered to
+ BeginForeignModify during the execution stage.
+
+ root is the planner's global information about the query.
+ plan is the ModifyTable plan node, which is
+ complete except for the fdwPrivLists field.
+ resultRelation identifies the target foreign table by its
+ range table index. subplan_index identifies which target of
+ the ModifyTable plan node this is, counting from zero;
+ use this if you want to index into per-target-relation substructures of the
+ plan node.
+
+ If the PlanForeignModify pointer is set to
+ NULL, no additional plan-time actions are taken, and the
+ fdw_private list delivered to
+ BeginForeignModify will be NIL.
+
+
+void
+BeginForeignModify(ModifyTableState *mtstate,
+ ResultRelInfo *rinfo,
+ List *fdw_private,
+ int subplan_index,
+ int eflags);
+
+
+ Begin executing a foreign table modification operation. This routine is
+ called during executor startup. It should perform any initialization
+ needed prior to the actual table modifications. Subsequently,
+ ExecForeignInsert/ExecForeignBatchInsert,
+ ExecForeignUpdate or
+ ExecForeignDelete will be called for tuple(s) to be
+ inserted, updated, or deleted.
+
+ mtstate is the overall state of the
+ ModifyTable plan node being executed; global data about
+ the plan and execution state is available via this structure.
+ rinfo is the ResultRelInfo struct describing
+ the target foreign table. (The ri_FdwState field of
+ ResultRelInfo is available for the FDW to store any
+ private state it needs for this operation.)
+ fdw_private contains the private data generated by
+ PlanForeignModify, if any.
+ subplan_index identifies which target of
+ the ModifyTable plan node this is.
+ eflags contains flag bits describing the executor's
+ operating mode for this plan node.
+
+ Note that when (eflags & EXEC_FLAG_EXPLAIN_ONLY) is
+ true, this function should not perform any externally-visible actions;
+ it should only do the minimum required to make the node state valid
+ for ExplainForeignModify and EndForeignModify.
+
+ If the BeginForeignModify pointer is set to
+ NULL, no action is taken during executor startup.
+
+
+ Insert one tuple into the foreign table.
+ estate is global execution state for the query.
+ rinfo is the ResultRelInfo struct describing
+ the target foreign table.
+ slot contains the tuple to be inserted; it will match the
+ row-type definition of the foreign table.
+ planSlot contains the tuple that was generated by the
+ ModifyTable plan node's subplan; it differs from
+ slot in possibly containing additional “junk”
+ columns. (The planSlot is typically of little interest
+ for INSERT cases, but is provided for completeness.)
+
+ The return value is either a slot containing the data that was actually
+ inserted (this might differ from the data supplied, for example as a
+ result of trigger actions), or NULL if no row was actually inserted
+ (again, typically as a result of triggers). The passed-in
+ slot can be re-used for this purpose.
+
+ The data in the returned slot is used only if the INSERT
+ statement has a RETURNING clause or involves a view
+ WITH CHECK OPTION; or if the foreign table has
+ an AFTER ROW trigger. Triggers require all columns,
+ but the FDW could choose to optimize away returning some or all columns
+ depending on the contents of the RETURNING clause or
+ WITH CHECK OPTION constraints. Regardless, some slot
+ must be returned to indicate success, or the query's reported row count
+ will be wrong.
+
+ If the ExecForeignInsert pointer is set to
+ NULL, attempts to insert into the foreign table will fail
+ with an error message.
+
+ Note that this function is also called when inserting routed tuples into
+ a foreign-table partition or executing COPY FROM on
+ a foreign table, in which case it is called in a different way than it
+ is in the INSERT case. See the callback functions
+ described below that allow the FDW to support that.
+
+
+ Insert multiple tuples in bulk into the foreign table.
+ The parameters are the same for ExecForeignInsert
+ except slots and planSlots contain
+ multiple tuples and *numSlots specifies the number of
+ tuples in those arrays.
+
+ The return value is an array of slots containing the data that was
+ actually inserted (this might differ from the data supplied, for
+ example as a result of trigger actions.)
+ The passed-in slots can be re-used for this purpose.
+ The number of successfully inserted tuples is returned in
+ *numSlots.
+
+ The data in the returned slot is used only if the INSERT
+ statement involves a view
+ WITH CHECK OPTION; or if the foreign table has
+ an AFTER ROW trigger. Triggers require all columns,
+ but the FDW could choose to optimize away returning some or all columns
+ depending on the contents of the
+ WITH CHECK OPTION constraints.
+
+ If the ExecForeignBatchInsert or
+ GetForeignModifyBatchSize pointer is set to
+ NULL, attempts to insert into the foreign table will
+ use ExecForeignInsert.
+ This function is not used if the INSERT has the
+ RETURNING clause.
+
+ Note that this function is also called when inserting routed tuples into
+ a foreign-table partition or executing COPY FROM on
+ a foreign table, in which case it is called in a different way than it
+ is in the INSERT case. See the callback functions
+ described below that allow the FDW to support that.
+
+
+ Report the maximum number of tuples that a single
+ ExecForeignBatchInsert call can handle for
+ the specified foreign table. The executor passes at most
+ the given number of tuples to ExecForeignBatchInsert.
+ rinfo is the ResultRelInfo struct describing
+ the target foreign table.
+ The FDW is expected to provide a foreign server and/or foreign
+ table option for the user to set this value, or some hard-coded value.
+
+ If the ExecForeignBatchInsert or
+ GetForeignModifyBatchSize pointer is set to
+ NULL, attempts to insert into the foreign table will
+ use ExecForeignInsert.
+
+
+ Update one tuple in the foreign table.
+ estate is global execution state for the query.
+ rinfo is the ResultRelInfo struct describing
+ the target foreign table.
+ slot contains the new data for the tuple; it will match the
+ row-type definition of the foreign table.
+ planSlot contains the tuple that was generated by the
+ ModifyTable plan node's subplan. Unlike
+ slot, this tuple contains only the new values for
+ columns changed by the query, so do not rely on attribute numbers of the
+ foreign table to index into planSlot.
+ Also, planSlot typically contains
+ additional “junk” columns. In particular, any junk columns
+ that were requested by AddForeignUpdateTargets will
+ be available from this slot.
+
+ The return value is either a slot containing the row as it was actually
+ updated (this might differ from the data supplied, for example as a
+ result of trigger actions), or NULL if no row was actually updated
+ (again, typically as a result of triggers). The passed-in
+ slot can be re-used for this purpose.
+
+ The data in the returned slot is used only if the UPDATE
+ statement has a RETURNING clause or involves a view
+ WITH CHECK OPTION; or if the foreign table has
+ an AFTER ROW trigger. Triggers require all columns,
+ but the FDW could choose to optimize away returning some or all columns
+ depending on the contents of the RETURNING clause or
+ WITH CHECK OPTION constraints. Regardless, some slot
+ must be returned to indicate success, or the query's reported row count
+ will be wrong.
+
+ If the ExecForeignUpdate pointer is set to
+ NULL, attempts to update the foreign table will fail
+ with an error message.
+
+
+ Delete one tuple from the foreign table.
+ estate is global execution state for the query.
+ rinfo is the ResultRelInfo struct describing
+ the target foreign table.
+ slot contains nothing useful upon call, but can be used to
+ hold the returned tuple.
+ planSlot contains the tuple that was generated by the
+ ModifyTable plan node's subplan; in particular, it will
+ carry any junk columns that were requested by
+ AddForeignUpdateTargets. The junk column(s) must be used
+ to identify the tuple to be deleted.
+
+ The return value is either a slot containing the row that was deleted,
+ or NULL if no row was deleted (typically as a result of triggers). The
+ passed-in slot can be used to hold the tuple to be returned.
+
+ The data in the returned slot is used only if the DELETE
+ query has a RETURNING clause or the foreign table has
+ an AFTER ROW trigger. Triggers require all columns, but the
+ FDW could choose to optimize away returning some or all columns depending
+ on the contents of the RETURNING clause. Regardless, some
+ slot must be returned to indicate success, or the query's reported row
+ count will be wrong.
+
+ If the ExecForeignDelete pointer is set to
+ NULL, attempts to delete from the foreign table will fail
+ with an error message.
+
+
+ End the table update and release resources. It is normally not important
+ to release palloc'd memory, but for example open files and connections
+ to remote servers should be cleaned up.
+
+ If the EndForeignModify pointer is set to
+ NULL, no action is taken during executor shutdown.
+
+ Tuples inserted into a partitioned table by INSERT or
+ COPY FROM are routed to partitions. If an FDW
+ supports routable foreign-table partitions, it should also provide the
+ following callback functions. These functions are also called when
+ COPY FROM is executed on a foreign table.
+
+
+ Begin executing an insert operation on a foreign table. This routine is
+ called right before the first tuple is inserted into the foreign table
+ in both cases when it is the partition chosen for tuple routing and the
+ target specified in a COPY FROM command. It should
+ perform any initialization needed prior to the actual insertion.
+ Subsequently, ExecForeignInsert or
+ ExecForeignBatchInsert will be called for
+ tuple(s) to be inserted into the foreign table.
+
+ mtstate is the overall state of the
+ ModifyTable plan node being executed; global data about
+ the plan and execution state is available via this structure.
+ rinfo is the ResultRelInfo struct describing
+ the target foreign table. (The ri_FdwState field of
+ ResultRelInfo is available for the FDW to store any
+ private state it needs for this operation.)
+
+ When this is called by a COPY FROM command, the
+ plan-related global data in mtstate is not provided
+ and the planSlot parameter of
+ ExecForeignInsert subsequently called for each
+ inserted tuple is NULL, whether the foreign table is
+ the partition chosen for tuple routing or the target specified in the
+ command.
+
+ If the BeginForeignInsert pointer is set to
+ NULL, no action is taken for the initialization.
+
+ Note that if the FDW does not support routable foreign-table partitions
+ and/or executing COPY FROM on foreign tables, this
+ function or ExecForeignInsert/ExecForeignBatchInsert
+ subsequently called must throw error as needed.
+
+
+ End the insert operation and release resources. It is normally not important
+ to release palloc'd memory, but for example open files and connections
+ to remote servers should be cleaned up.
+
+ If the EndForeignInsert pointer is set to
+ NULL, no action is taken for the termination.
+
+
+int
+IsForeignRelUpdatable(Relation rel);
+
+
+ Report which update operations the specified foreign table supports.
+ The return value should be a bit mask of rule event numbers indicating
+ which operations are supported by the foreign table, using the
+ CmdType enumeration; that is,
+ (1 << CMD_UPDATE) = 4 for UPDATE,
+ (1 << CMD_INSERT) = 8 for INSERT, and
+ (1 << CMD_DELETE) = 16 for DELETE.
+
+ If the IsForeignRelUpdatable pointer is set to
+ NULL, foreign tables are assumed to be insertable, updatable,
+ or deletable if the FDW provides ExecForeignInsert,
+ ExecForeignUpdate, or ExecForeignDelete
+ respectively. This function is only needed if the FDW supports some
+ tables that are updatable and some that are not. (Even then, it's
+ permissible to throw an error in the execution routine instead of
+ checking in this function. However, this function is used to determine
+ updatability for display in the information_schema views.)
+
+ Some inserts, updates, and deletes to foreign tables can be optimized
+ by implementing an alternative set of interfaces. The ordinary
+ interfaces for inserts, updates, and deletes fetch rows from the remote
+ server and then modify those rows one at a time. In some cases, this
+ row-by-row approach is necessary, but it can be inefficient. If it is
+ possible for the foreign server to determine which rows should be
+ modified without actually retrieving them, and if there are no local
+ structures which would affect the operation (row-level local triggers,
+ stored generated columns, or WITH CHECK OPTION
+ constraints from parent views), then it is possible to arrange things
+ so that the entire operation is performed on the remote server. The
+ interfaces described below make this possible.
+
+
+bool
+PlanDirectModify(PlannerInfo *root,
+ ModifyTable *plan,
+ Index resultRelation,
+ int subplan_index);
+
+
+ Decide whether it is safe to execute a direct modification
+ on the remote server. If so, return true after performing
+ planning actions needed for that. Otherwise, return false.
+ This optional function is called during query planning.
+ If this function succeeds, BeginDirectModify,
+ IterateDirectModify and EndDirectModify will
+ be called at the execution stage, instead. Otherwise, the table
+ modification will be executed using the table-updating functions
+ described above.
+ The parameters are the same as for PlanForeignModify.
+
+ To execute the direct modification on the remote server, this function
+ must rewrite the target subplan with a ForeignScan plan
+ node that executes the direct modification on the remote server. The
+ operation and resultRelation fields
+ of the ForeignScan must be set appropriately.
+ operation must be set to the CmdType
+ enumeration corresponding to the statement kind (that is,
+ CMD_UPDATE for UPDATE,
+ CMD_INSERT for INSERT, and
+ CMD_DELETE for DELETE), and the
+ resultRelation argument must be copied to the
+ resultRelation field.
+
+ If the PlanDirectModify pointer is set to
+ NULL, no attempts to execute a direct modification on the
+ remote server are taken.
+
+
+void
+BeginDirectModify(ForeignScanState *node,
+ int eflags);
+
+
+ Prepare to execute a direct modification on the remote server.
+ This is called during executor startup. It should perform any
+ initialization needed prior to the direct modification (that should be
+ done upon the first call to IterateDirectModify).
+ The ForeignScanState node has already been created, but
+ its fdw_state field is still NULL. Information about
+ the table to modify is accessible through the
+ ForeignScanState node (in particular, from the underlying
+ ForeignScan plan node, which contains any FDW-private
+ information provided by PlanDirectModify).
+ eflags contains flag bits describing the executor's
+ operating mode for this plan node.
+
+ Note that when (eflags & EXEC_FLAG_EXPLAIN_ONLY) is
+ true, this function should not perform any externally-visible actions;
+ it should only do the minimum required to make the node state valid
+ for ExplainDirectModify and EndDirectModify.
+
+ If the BeginDirectModify pointer is set to
+ NULL, no attempts to execute a direct modification on the
+ remote server are taken.
+
+
+ When the INSERT, UPDATE or DELETE
+ query doesn't have a RETURNING clause, just return NULL
+ after a direct modification on the remote server.
+ When the query has the clause, fetch one result containing the data
+ needed for the RETURNING calculation, returning it in a
+ tuple table slot (the node's ScanTupleSlot should be
+ used for this purpose). The data that was actually inserted, updated
+ or deleted must be stored in
+ node->resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_scantuple.
+ Return NULL if no more rows are available.
+ Note that this is called in a short-lived memory context that will be
+ reset between invocations. Create a memory context in
+ BeginDirectModify if you need longer-lived storage, or use
+ the es_query_cxt of the node's EState.
+
+ The rows returned must match the fdw_scan_tlist target
+ list if one was supplied, otherwise they must match the row type of the
+ foreign table being updated. If you choose to optimize away fetching
+ columns that are not needed for the RETURNING calculation,
+ you should insert nulls in those column positions, or else generate a
+ fdw_scan_tlist list with those columns omitted.
+
+ Whether the query has the clause or not, the query's reported row count
+ must be incremented by the FDW itself. When the query doesn't have the
+ clause, the FDW must also increment the row count for the
+ ForeignScanState node in the EXPLAIN ANALYZE
+ case.
+
+ If the IterateDirectModify pointer is set to
+ NULL, no attempts to execute a direct modification on the
+ remote server are taken.
+
+
+void
+EndDirectModify(ForeignScanState *node);
+
+
+ Clean up following a direct modification on the remote server. It is
+ normally not important to release palloc'd memory, but for example open
+ files and connections to the remote server should be cleaned up.
+
+ If the EndDirectModify pointer is set to
+ NULL, no attempts to execute a direct modification on the
+ remote server are taken.
+
+
+ Truncate foreign tables. This function is called when
+ TRUNCATE is executed on a foreign table.
+ rels is a list of Relation
+ data structures of foreign tables to truncate.
+
+ behavior is either DROP_RESTRICT
+ or DROP_CASCADE indicating that the
+ RESTRICT or CASCADE option was
+ requested in the original TRUNCATE command,
+ respectively.
+
+ If restart_seqs is true,
+ the original TRUNCATE command requested the
+ RESTART IDENTITY behavior, otherwise the
+ CONTINUE IDENTITY behavior was requested.
+
+ Note that the ONLY options specified
+ in the original TRUNCATE command are not passed to
+ ExecForeignTruncate. This behavior is similar to
+ the callback functions of SELECT,
+ UPDATE and DELETE on
+ a foreign table.
+
+ ExecForeignTruncate is invoked once per
+ foreign server for which foreign tables are to be truncated.
+ This means that all foreign tables included in rels
+ must belong to the same server.
+
+ If the ExecForeignTruncate pointer is set to
+ NULL, attempts to truncate foreign tables will
+ fail with an error message.
+
+
+ Report which row-marking option to use for a foreign table.
+ rte is the RangeTblEntry node for the table
+ and strength describes the lock strength requested by the
+ relevant FOR UPDATE/SHARE clause, if any. The result must be
+ a member of the RowMarkType enum type.
+
+ This function is called during query planning for each foreign table that
+ appears in an UPDATE, DELETE, or SELECT
+ FOR UPDATE/SHARE query and is not the target of UPDATE
+ or DELETE.
+
+ If the GetForeignRowMarkType pointer is set to
+ NULL, the ROW_MARK_COPY option is always used.
+ (This implies that RefetchForeignRow will never be called,
+ so it need not be provided either.)
+
+
+ Re-fetch one tuple slot from the foreign table, after locking it if required.
+ estate is global execution state for the query.
+ erm is the ExecRowMark struct describing
+ the target foreign table and the row lock type (if any) to acquire.
+ rowid identifies the tuple to be fetched.
+ slot contains nothing useful upon call, but can be used to
+ hold the returned tuple. updated is an output parameter.
+
+ This function should store the tuple into the provided slot, or clear it if
+ the row lock couldn't be obtained. The row lock type to acquire is
+ defined by erm->markType, which is the value
+ previously returned by GetForeignRowMarkType.
+ (ROW_MARK_REFERENCE means to just re-fetch the tuple
+ without acquiring any lock, and ROW_MARK_COPY will
+ never be seen by this routine.)
+
+ In addition, *updated should be set to true
+ if what was fetched was an updated version of the tuple rather than
+ the same version previously obtained. (If the FDW cannot be sure about
+ this, always returning true is recommended.)
+
+ Note that by default, failure to acquire a row lock should result in
+ raising an error; returning with an empty slot is only appropriate if
+ the SKIP LOCKED option is specified
+ by erm->waitPolicy.
+
+ The rowid is the ctid value previously read
+ for the row to be re-fetched. Although the rowid value is
+ passed as a Datum, it can currently only be a tid. The
+ function API is chosen in hopes that it may be possible to allow other
+ data types for row IDs in future.
+
+ If the RefetchForeignRow pointer is set to
+ NULL, attempts to re-fetch rows will fail
+ with an error message.
+
+ Recheck that a previously-returned tuple still matches the relevant
+ scan and join qualifiers, and possibly provide a modified version of
+ the tuple. For foreign data wrappers which do not perform join pushdown,
+ it will typically be more convenient to set this to NULL and
+ instead set fdw_recheck_quals appropriately.
+ When outer joins are pushed down, however, it isn't sufficient to
+ reapply the checks relevant to all the base tables to the result tuple,
+ even if all needed attributes are present, because failure to match some
+ qualifier might result in some attributes going to NULL, rather than in
+ no tuple being returned. RecheckForeignScan can recheck
+ qualifiers and return true if they are still satisfied and false
+ otherwise, but it can also store a replacement tuple into the supplied
+ slot.
+
+ To implement join pushdown, a foreign data wrapper will typically
+ construct an alternative local join plan which is used only for
+ rechecks; this will become the outer subplan of the
+ ForeignScan. When a recheck is required, this subplan
+ can be executed and the resulting tuple can be stored in the slot.
+ This plan need not be efficient since no base table will return more
+ than one row; for example, it may implement all joins as nested loops.
+ The function GetExistingLocalJoinPath may be used to search
+ existing paths for a suitable local join path, which can be used as the
+ alternative local join plan. GetExistingLocalJoinPath
+ searches for an unparameterized path in the path list of the specified
+ join relation. (If it does not find such a path, it returns NULL, in
+ which case a foreign data wrapper may build the local path by itself or
+ may choose not to create access paths for that join.)
+
+
+ Print additional EXPLAIN output for a foreign table scan.
+ This function can call ExplainPropertyText and
+ related functions to add fields to the EXPLAIN output.
+ The flag fields in es can be used to determine what to
+ print, and the state of the ForeignScanState node
+ can be inspected to provide run-time statistics in the EXPLAIN
+ ANALYZE case.
+
+ If the ExplainForeignScan pointer is set to
+ NULL, no additional information is printed during
+ EXPLAIN.
+
+
+void
+ExplainForeignModify(ModifyTableState *mtstate,
+ ResultRelInfo *rinfo,
+ List *fdw_private,
+ int subplan_index,
+ struct ExplainState *es);
+
+
+ Print additional EXPLAIN output for a foreign table update.
+ This function can call ExplainPropertyText and
+ related functions to add fields to the EXPLAIN output.
+ The flag fields in es can be used to determine what to
+ print, and the state of the ModifyTableState node
+ can be inspected to provide run-time statistics in the EXPLAIN
+ ANALYZE case. The first four arguments are the same as for
+ BeginForeignModify.
+
+ If the ExplainForeignModify pointer is set to
+ NULL, no additional information is printed during
+ EXPLAIN.
+
+
+ Print additional EXPLAIN output for a direct modification
+ on the remote server.
+ This function can call ExplainPropertyText and
+ related functions to add fields to the EXPLAIN output.
+ The flag fields in es can be used to determine what to
+ print, and the state of the ForeignScanState node
+ can be inspected to provide run-time statistics in the EXPLAIN
+ ANALYZE case.
+
+ If the ExplainDirectModify pointer is set to
+ NULL, no additional information is printed during
+ EXPLAIN.
+
+
+ This function is called when ANALYZE is executed on
+ a foreign table. If the FDW can collect statistics for this
+ foreign table, it should return true, and provide a pointer
+ to a function that will collect sample rows from the table in
+ func, plus the estimated size of the table in pages in
+ totalpages. Otherwise, return false.
+
+ If the FDW does not support collecting statistics for any tables, the
+ AnalyzeForeignTable pointer can be set to NULL.
+
+ If provided, the sample collection function must have the signature
+
+int
+AcquireSampleRowsFunc(Relation relation,
+ int elevel,
+ HeapTuple *rows,
+ int targrows,
+ double *totalrows,
+ double *totaldeadrows);
+
+
+ A random sample of up to targrows rows should be collected
+ from the table and stored into the caller-provided rows
+ array. The actual number of rows collected must be returned. In
+ addition, store estimates of the total numbers of live and dead rows in
+ the table into the output parameters totalrows and
+ totaldeadrows. (Set totaldeadrows to zero
+ if the FDW does not have any concept of dead rows.)
+
+List *
+ImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid);
+
+
+ Obtain a list of foreign table creation commands. This function is
+ called when executing IMPORT FOREIGN SCHEMA, and is
+ passed the parse tree for that statement, as well as the OID of the
+ foreign server to use. It should return a list of C strings, each of
+ which must contain a CREATE FOREIGN TABLE command.
+ These strings will be parsed and executed by the core server.
+
+ Within the ImportForeignSchemaStmt struct,
+ remote_schema is the name of the remote schema from
+ which tables are to be imported.
+ list_type identifies how to filter table names:
+ FDW_IMPORT_SCHEMA_ALL means that all tables in the remote
+ schema should be imported (in this case table_list is
+ empty), FDW_IMPORT_SCHEMA_LIMIT_TO means to include only
+ tables listed in table_list,
+ and FDW_IMPORT_SCHEMA_EXCEPT means to exclude the tables
+ listed in table_list.
+ options is a list of options used for the import process.
+ The meanings of the options are up to the FDW.
+ For example, an FDW could use an option to define whether the
+ NOT NULL attributes of columns should be imported.
+ These options need not have anything to do with those supported by the
+ FDW as database object options.
+
+ The FDW may ignore the local_schema field of
+ the ImportForeignSchemaStmt, because the core server
+ will automatically insert that name into the parsed CREATE
+ FOREIGN TABLE commands.
+
+ The FDW does not have to concern itself with implementing the filtering
+ specified by list_type and table_list,
+ either, as the core server will automatically skip any returned commands
+ for tables excluded according to those options. However, it's often
+ useful to avoid the work of creating commands for excluded tables in the
+ first place. The function IsImportableForeignTable() may be
+ useful to test whether a given foreign-table name will pass the filter.
+
+ If the FDW does not support importing table definitions, the
+ ImportForeignSchema pointer can be set to NULL.
+
+ A ForeignScan node can, optionally, support parallel
+ execution. A parallel ForeignScan will be executed
+ in multiple processes and must return each row exactly once across
+ all cooperating processes. To do this, processes can coordinate through
+ fixed-size chunks of dynamic shared memory. This shared memory is not
+ guaranteed to be mapped at the same address in every process, so it
+ must not contain pointers. The following functions are all optional,
+ but most are required if parallel execution is to be supported.
+
+ Test whether a scan can be performed within a parallel worker. This
+ function will only be called when the planner believes that a parallel
+ plan might be possible, and should return true if it is safe for that scan
+ to run within a parallel worker. This will generally not be the case if
+ the remote data source has transaction semantics, unless the worker's
+ connection to the data can somehow be made to share the same transaction
+ context as the leader.
+
+ If this function is not defined, it is assumed that the scan must take
+ place within the parallel leader. Note that returning true does not mean
+ that the scan itself can be done in parallel, only that the scan can be
+ performed within a parallel worker. Therefore, it can be useful to define
+ this method even when parallel execution is not supported.
+
+ Estimate the amount of dynamic shared memory that will be required
+ for parallel operation. This may be higher than the amount that will
+ actually be used, but it must not be lower. The return value is in bytes.
+ This function is optional, and can be omitted if not needed; but if it
+ is omitted, the next three functions must be omitted as well, because
+ no shared memory will be allocated for the FDW's use.
+
+ Initialize the dynamic shared memory that will be required for parallel
+ operation. coordinate points to a shared memory area of
+ size equal to the return value of EstimateDSMForeignScan.
+ This function is optional, and can be omitted if not needed.
+
+ Re-initialize the dynamic shared memory required for parallel operation
+ when the foreign-scan plan node is about to be re-scanned.
+ This function is optional, and can be omitted if not needed.
+ Recommended practice is that this function reset only shared state,
+ while the ReScanForeignScan function resets only local
+ state. Currently, this function will be called
+ before ReScanForeignScan, but it's best not to rely on
+ that ordering.
+
+ Initialize a parallel worker's local state based on the shared state
+ set up by the leader during InitializeDSMForeignScan.
+ This function is optional, and can be omitted if not needed.
+
+ Release resources when it is anticipated the node will not be executed
+ to completion. This is not called in all cases; sometimes,
+ EndForeignScan may be called without this function having
+ been called first. Since the DSM segment used by parallel query is
+ destroyed just after this callback is invoked, foreign data wrappers that
+ wish to take some action before the DSM segment goes away should implement
+ this method.
+
59.2.11. FDW Routines for Asynchronous Execution #
+ A ForeignScan node can, optionally, support
+ asynchronous execution as described in
+ src/backend/executor/README. The following
+ functions are all optional, but are all required if asynchronous
+ execution is to be supported.
+
+ Test whether a given ForeignPath path can scan
+ the underlying foreign relation asynchronously.
+ This function will only be called at the end of query planning when the
+ given path is a direct child of an AppendPath
+ path and when the planner believes that asynchronous execution improves
+ performance, and should return true if the given path is able to scan the
+ foreign relation asynchronously.
+
+ If this function is not defined, it is assumed that the given path scans
+ the foreign relation using IterateForeignScan.
+ (This implies that the callback functions described below will never be
+ called, so they need not be provided either.)
+
+
+void
+ForeignAsyncRequest(AsyncRequest *areq);
+
+ Produce one tuple asynchronously from the
+ ForeignScan node. areq is
+ the AsyncRequest struct describing the
+ ForeignScan node and the parent
+ Append node that requested the tuple from it.
+ This function should store the tuple into the slot specified by
+ areq->result, and set
+ areq->request_complete to true;
+ or if it needs to wait on an event external to the core server such as
+ network I/O, and cannot produce any tuple immediately, set the flag to
+ false, and set
+ areq->callback_pending to true
+ for the ForeignScan node to get a callback from
+ the callback functions described below. If no more tuples are available,
+ set the slot to NULL or an empty slot, and the
+ areq->request_complete flag to
+ true. It's recommended to use
+ ExecAsyncRequestDone or
+ ExecAsyncRequestPending to set the output parameters
+ in the areq.
+
+ Configure a file descriptor event for which the
+ ForeignScan node wishes to wait.
+ This function will only be called when the
+ ForeignScan node has the
+ areq->callback_pending flag set, and should add
+ the event to the as_eventset of the parent
+ Append node described by the
+ areq. See the comments for
+ ExecAsyncConfigureWait in
+ src/backend/executor/execAsync.c for additional
+ information. When the file descriptor event occurs,
+ ForeignAsyncNotify will be called.
+
+
+void
+ForeignAsyncNotify(AsyncRequest *areq);
+
+ Process a relevant event that has occurred, then produce one tuple
+ asynchronously from the ForeignScan node.
+ This function should set the output parameters in the
+ areq in the same way as
+ ForeignAsyncRequest.
+
59.2.12. FDW Routines for Reparameterization of Paths #
+
+List *
+ReparameterizeForeignPathByChild(PlannerInfo *root, List *fdw_private,
+ RelOptInfo *child_rel);
+
+ This function is called while converting a path parameterized by the
+ top-most parent of the given child relation child_rel to be
+ parameterized by the child relation. The function is used to reparameterize
+ any paths or translate any expression nodes saved in the given
+ fdw_private member of a ForeignPath. The
+ callback may use reparameterize_path_by_child,
+ adjust_appendrel_attrs or
+ adjust_appendrel_attrs_multilevel as required.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fdw-functions.html b/pgsql/doc/postgresql/html/fdw-functions.html
new file mode 100644
index 0000000000000000000000000000000000000000..c181e5ced10736b1f17b11e839b3324cd45bf1fa
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fdw-functions.html
@@ -0,0 +1,33 @@
+
+59.1. Foreign Data Wrapper Functions
+ The FDW author needs to implement a handler function, and optionally
+ a validator function. Both functions must be written in a compiled
+ language such as C, using the version-1 interface.
+ For details on C language calling conventions and dynamic loading,
+ see Section 38.10.
+
+ The handler function simply returns a struct of function pointers to
+ callback functions that will be called by the planner, executor, and
+ various maintenance commands.
+ Most of the effort in writing an FDW is in implementing these callback
+ functions.
+ The handler function must be registered with
+ PostgreSQL as taking no arguments and
+ returning the special pseudo-type fdw_handler. The
+ callback functions are plain C functions and are not visible or
+ callable at the SQL level. The callback functions are described in
+ Section 59.2.
+
+ The validator function is responsible for validating options given in
+ CREATE and ALTER commands for its
+ foreign data wrapper, as well as foreign servers, user mappings, and
+ foreign tables using the wrapper.
+ The validator function must be registered as taking two arguments, a
+ text array containing the options to be validated, and an OID
+ representing the type of object the options are associated with. The
+ latter corresponds to the OID of the system catalog the object
+ would be stored in, one of:
+
AttributeRelationId
ForeignDataWrapperRelationId
ForeignServerRelationId
ForeignTableRelationId
UserMappingRelationId
+ If no validator function is supplied, options are not checked at object
+ creation time or object alteration time.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fdw-helpers.html b/pgsql/doc/postgresql/html/fdw-helpers.html
new file mode 100644
index 0000000000000000000000000000000000000000..5d44f5c6c968366a624efe37373f7351c0aa212a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fdw-helpers.html
@@ -0,0 +1,114 @@
+
+59.3. Foreign Data Wrapper Helper Functions
+ Several helper functions are exported from the core server so that
+ authors of foreign data wrappers can get easy access to attributes of
+ FDW-related objects, such as FDW options.
+ To use any of these functions, you need to include the header file
+ foreign/foreign.h in your source file.
+ That header also defines the struct types that are returned by
+ these functions.
+
+
+ This function returns a ForeignDataWrapper
+ object for the foreign-data wrapper with the given OID. A
+ ForeignDataWrapper object contains properties
+ of the FDW (see foreign/foreign.h for details).
+ flags is a bitwise-or'd bit mask indicating
+ an extra set of options. It can take the value
+ FDW_MISSING_OK, in which case a NULL
+ result is returned to the caller instead of an error for an undefined
+ object.
+
+
+ This function returns a ForeignDataWrapper
+ object for the foreign-data wrapper with the given OID. A
+ ForeignDataWrapper object contains properties
+ of the FDW (see foreign/foreign.h for details).
+
+
+ This function returns a ForeignServer object
+ for the foreign server with the given OID. A
+ ForeignServer object contains properties
+ of the server (see foreign/foreign.h for details).
+ flags is a bitwise-or'd bit mask indicating
+ an extra set of options. It can take the value
+ FSV_MISSING_OK, in which case a NULL
+ result is returned to the caller instead of an error for an undefined
+ object.
+
+
+ This function returns a ForeignServer object
+ for the foreign server with the given OID. A
+ ForeignServer object contains properties
+ of the server (see foreign/foreign.h for details).
+
+
+UserMapping *
+GetUserMapping(Oid userid, Oid serverid);
+
+
+ This function returns a UserMapping object for
+ the user mapping of the given role on the given server. (If there is no
+ mapping for the specific user, it will return the mapping for
+ PUBLIC, or throw error if there is none.) A
+ UserMapping object contains properties of the
+ user mapping (see foreign/foreign.h for details).
+
+
+ForeignTable *
+GetForeignTable(Oid relid);
+
+
+ This function returns a ForeignTable object for
+ the foreign table with the given OID. A
+ ForeignTable object contains properties of the
+ foreign table (see foreign/foreign.h for details).
+
+
+ This function returns the per-column FDW options for the column with the
+ given foreign table OID and attribute number, in the form of a list of
+ DefElem. NIL is returned if the column has no
+ options.
+
+ Some object types have name-based lookup functions in addition to the
+ OID-based ones:
+
+
+ This function returns a ForeignDataWrapper
+ object for the foreign-data wrapper with the given name. If the wrapper
+ is not found, return NULL if missing_ok is true, otherwise raise an
+ error.
+
+
+ This function returns a ForeignServer object
+ for the foreign server with the given name. If the server is not found,
+ return NULL if missing_ok is true, otherwise raise an error.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fdw-planning.html b/pgsql/doc/postgresql/html/fdw-planning.html
new file mode 100644
index 0000000000000000000000000000000000000000..fdb205e55c12ebf372e48c5702bc5ba6763445bd
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fdw-planning.html
@@ -0,0 +1,191 @@
+
+59.4. Foreign Data Wrapper Query Planning
+ The FDW callback functions GetForeignRelSize,
+ GetForeignPaths, GetForeignPlan,
+ PlanForeignModify, GetForeignJoinPaths,
+ GetForeignUpperPaths, and PlanDirectModify
+ must fit into the workings of the PostgreSQL planner.
+ Here are some notes about what they must do.
+
+ The information in root and baserel can be used
+ to reduce the amount of information that has to be fetched from the
+ foreign table (and therefore reduce the cost).
+ baserel->baserestrictinfo is particularly interesting, as
+ it contains restriction quals (WHERE clauses) that should be
+ used to filter the rows to be fetched. (The FDW itself is not required
+ to enforce these quals, as the core executor can check them instead.)
+ baserel->reltarget->exprs can be used to determine which
+ columns need to be fetched; but note that it only lists columns that
+ have to be emitted by the ForeignScan plan node, not
+ columns that are used in qual evaluation but not output by the query.
+
+ Various private fields are available for the FDW planning functions to
+ keep information in. Generally, whatever you store in FDW private fields
+ should be palloc'd, so that it will be reclaimed at the end of planning.
+
+ baserel->fdw_private is a void pointer that is
+ available for FDW planning functions to store information relevant to
+ the particular foreign table. The core planner does not touch it except
+ to initialize it to NULL when the RelOptInfo node is created.
+ It is useful for passing information forward from
+ GetForeignRelSize to GetForeignPaths and/or
+ GetForeignPaths to GetForeignPlan, thereby
+ avoiding recalculation.
+
+ GetForeignPaths can identify the meaning of different
+ access paths by storing private information in the
+ fdw_private field of ForeignPath nodes.
+ fdw_private is declared as a List pointer, but
+ could actually contain anything since the core planner does not touch
+ it. However, best practice is to use a representation that's dumpable
+ by nodeToString, for use with debugging support available
+ in the backend.
+
+ GetForeignPlan can examine the fdw_private
+ field of the selected ForeignPath node, and can generate
+ fdw_exprs and fdw_private lists to be
+ placed in the ForeignScan plan node, where they will be
+ available at execution time. Both of these lists must be
+ represented in a form that copyObject knows how to copy.
+ The fdw_private list has no other restrictions and is
+ not interpreted by the core backend in any way. The
+ fdw_exprs list, if not NIL, is expected to contain
+ expression trees that are intended to be executed at run time. These
+ trees will undergo post-processing by the planner to make them fully
+ executable.
+
+ In GetForeignPlan, generally the passed-in target list can
+ be copied into the plan node as-is. The passed scan_clauses list
+ contains the same clauses as baserel->baserestrictinfo,
+ but may be re-ordered for better execution efficiency. In simple cases
+ the FDW can just strip RestrictInfo nodes from the
+ scan_clauses list (using extract_actual_clauses) and put
+ all the clauses into the plan node's qual list, which means that all the
+ clauses will be checked by the executor at run time. More complex FDWs
+ may be able to check some of the clauses internally, in which case those
+ clauses can be removed from the plan node's qual list so that the
+ executor doesn't waste time rechecking them.
+
+ As an example, the FDW might identify some restriction clauses of the
+ form foreign_variable=
+ sub_expression, which it determines can be executed on
+ the remote server given the locally-evaluated value of the
+ sub_expression. The actual identification of such a
+ clause should happen during GetForeignPaths, since it would
+ affect the cost estimate for the path. The path's
+ fdw_private field would probably include a pointer to
+ the identified clause's RestrictInfo node. Then
+ GetForeignPlan would remove that clause from scan_clauses,
+ but add the sub_expression to fdw_exprs
+ to ensure that it gets massaged into executable form. It would probably
+ also put control information into the plan node's
+ fdw_private field to tell the execution functions what
+ to do at run time. The query transmitted to the remote server would
+ involve something like WHERE foreign_variable =
+ $1, with the parameter value obtained at run time from
+ evaluation of the fdw_exprs expression tree.
+
+ Any clauses removed from the plan node's qual list must instead be added
+ to fdw_recheck_quals or rechecked by
+ RecheckForeignScan in order to ensure correct behavior
+ at the READ COMMITTED isolation level. When a concurrent
+ update occurs for some other table involved in the query, the executor
+ may need to verify that all of the original quals are still satisfied for
+ the tuple, possibly against a different set of parameter values. Using
+ fdw_recheck_quals is typically easier than implementing checks
+ inside RecheckForeignScan, but this method will be
+ insufficient when outer joins have been pushed down, since the join tuples
+ in that case might have some fields go to NULL without rejecting the
+ tuple entirely.
+
+ Another ForeignScan field that can be filled by FDWs
+ is fdw_scan_tlist, which describes the tuples returned by
+ the FDW for this plan node. For simple foreign table scans this can be
+ set to NIL, implying that the returned tuples have the
+ row type declared for the foreign table. A non-NIL value must be a
+ target list (list of TargetEntrys) containing Vars and/or
+ expressions representing the returned columns. This might be used, for
+ example, to show that the FDW has omitted some columns that it noticed
+ won't be needed for the query. Also, if the FDW can compute expressions
+ used by the query more cheaply than can be done locally, it could add
+ those expressions to fdw_scan_tlist. Note that join
+ plans (created from paths made by GetForeignJoinPaths) must
+ always supply fdw_scan_tlist to describe the set of
+ columns they will return.
+
+ The FDW should always construct at least one path that depends only on
+ the table's restriction clauses. In join queries, it might also choose
+ to construct path(s) that depend on join clauses, for example
+ foreign_variable=
+ local_variable. Such clauses will not be found in
+ baserel->baserestrictinfo but must be sought in the
+ relation's join lists. A path using such a clause is called a
+ “parameterized path”. It must identify the other relations
+ used in the selected join clause(s) with a suitable value of
+ param_info; use get_baserel_parampathinfo
+ to compute that value. In GetForeignPlan, the
+ local_variable portion of the join clause would be added
+ to fdw_exprs, and then at run time the case works the
+ same as for an ordinary restriction clause.
+
+ If an FDW supports remote joins, GetForeignJoinPaths should
+ produce ForeignPaths for potential remote joins in much
+ the same way as GetForeignPaths works for base tables.
+ Information about the intended join can be passed forward
+ to GetForeignPlan in the same ways described above.
+ However, baserestrictinfo is not relevant for join
+ relations; instead, the relevant join clauses for a particular join are
+ passed to GetForeignJoinPaths as a separate parameter
+ (extra->restrictlist).
+
+ An FDW might additionally support direct execution of some plan actions
+ that are above the level of scans and joins, such as grouping or
+ aggregation. To offer such options, the FDW should generate paths and
+ insert them into the appropriate upper relation. For
+ example, a path representing remote aggregation should be inserted into
+ the UPPERREL_GROUP_AGG relation, using add_path.
+ This path will be compared on a cost basis with local aggregation
+ performed by reading a simple scan path for the foreign relation (note
+ that such a path must also be supplied, else there will be an error at
+ plan time). If the remote-aggregation path wins, which it usually would,
+ it will be converted into a plan in the usual way, by
+ calling GetForeignPlan. The recommended place to generate
+ such paths is in the GetForeignUpperPaths
+ callback function, which is called for each upper relation (i.e., each
+ post-scan/join processing step), if all the base relations of the query
+ come from the same FDW.
+
+ PlanForeignModify and the other callbacks described in
+ Section 59.2.4 are designed around the assumption
+ that the foreign relation will be scanned in the usual way and then
+ individual row updates will be driven by a local ModifyTable
+ plan node. This approach is necessary for the general case where an
+ update requires reading local tables as well as foreign tables.
+ However, if the operation could be executed entirely by the foreign
+ server, the FDW could generate a path representing that and insert it
+ into the UPPERREL_FINAL upper relation, where it would
+ compete against the ModifyTable approach. This approach
+ could also be used to implement remote SELECT FOR UPDATE,
+ rather than using the row locking callbacks described in
+ Section 59.2.6. Keep in mind that a path
+ inserted into UPPERREL_FINAL is responsible for
+ implementing all behavior of the query.
+
+ When planning an UPDATE or DELETE,
+ PlanForeignModify and PlanDirectModify
+ can look up the RelOptInfo
+ struct for the foreign table and make use of the
+ baserel->fdw_private data previously created by the
+ scan-planning functions. However, in INSERT the target
+ table is not scanned so there is no RelOptInfo for it.
+ The List returned by PlanForeignModify has
+ the same restrictions as the fdw_private list of a
+ ForeignScan plan node, that is it must contain only
+ structures that copyObject knows how to copy.
+
+ INSERT with an ON CONFLICT clause does not
+ support specifying the conflict target, as unique constraints or
+ exclusion constraints on remote tables are not locally known. This
+ in turn implies that ON CONFLICT DO UPDATE is not supported,
+ since the specification is mandatory there.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fdw-row-locking.html b/pgsql/doc/postgresql/html/fdw-row-locking.html
new file mode 100644
index 0000000000000000000000000000000000000000..9296dc1775b141de83c27f9c972c36a0a97f5947
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fdw-row-locking.html
@@ -0,0 +1,93 @@
+
+59.5. Row Locking in Foreign Data Wrappers
+ If an FDW's underlying storage mechanism has a concept of locking
+ individual rows to prevent concurrent updates of those rows, it is
+ usually worthwhile for the FDW to perform row-level locking with as
+ close an approximation as practical to the semantics used in
+ ordinary PostgreSQL tables. There are multiple
+ considerations involved in this.
+
+ One key decision to be made is whether to perform early
+ locking or late locking. In early locking, a row is
+ locked when it is first retrieved from the underlying store, while in
+ late locking, the row is locked only when it is known that it needs to
+ be locked. (The difference arises because some rows may be discarded by
+ locally-checked restriction or join conditions.) Early locking is much
+ simpler and avoids extra round trips to a remote store, but it can cause
+ locking of rows that need not have been locked, resulting in reduced
+ concurrency or even unexpected deadlocks. Also, late locking is only
+ possible if the row to be locked can be uniquely re-identified later.
+ Preferably the row identifier should identify a specific version of the
+ row, as PostgreSQL TIDs do.
+
+ By default, PostgreSQL ignores locking considerations
+ when interfacing to FDWs, but an FDW can perform early locking without
+ any explicit support from the core code. The API functions described
+ in Section 59.2.6, which were added
+ in PostgreSQL 9.5, allow an FDW to use late locking if
+ it wishes.
+
+ An additional consideration is that in READ COMMITTED
+ isolation mode, PostgreSQL may need to re-check
+ restriction and join conditions against an updated version of some
+ target tuple. Rechecking join conditions requires re-obtaining copies
+ of the non-target rows that were previously joined to the target tuple.
+ When working with standard PostgreSQL tables, this is
+ done by including the TIDs of the non-target tables in the column list
+ projected through the join, and then re-fetching non-target rows when
+ required. This approach keeps the join data set compact, but it
+ requires inexpensive re-fetch capability, as well as a TID that can
+ uniquely identify the row version to be re-fetched. By default,
+ therefore, the approach used with foreign tables is to include a copy of
+ the entire row fetched from a foreign table in the column list projected
+ through the join. This puts no special demands on the FDW but can
+ result in reduced performance of merge and hash joins. An FDW that is
+ capable of meeting the re-fetch requirements can choose to do it the
+ first way.
+
+ For an UPDATE or DELETE on a foreign table, it
+ is recommended that the ForeignScan operation on the target
+ table perform early locking on the rows that it fetches, perhaps via the
+ equivalent of SELECT FOR UPDATE. An FDW can detect whether
+ a table is an UPDATE/DELETE target at plan time
+ by comparing its relid to root->parse->resultRelation,
+ or at execution time by using ExecRelationIsTargetRelation().
+ An alternative possibility is to perform late locking within the
+ ExecForeignUpdate or ExecForeignDelete
+ callback, but no special support is provided for this.
+
+ For foreign tables that are specified to be locked by a SELECT
+ FOR UPDATE/SHARE command, the ForeignScan operation can
+ again perform early locking by fetching tuples with the equivalent
+ of SELECT FOR UPDATE/SHARE. To perform late locking
+ instead, provide the callback functions defined
+ in Section 59.2.6.
+ In GetForeignRowMarkType, select rowmark option
+ ROW_MARK_EXCLUSIVE, ROW_MARK_NOKEYEXCLUSIVE,
+ ROW_MARK_SHARE, or ROW_MARK_KEYSHARE depending
+ on the requested lock strength. (The core code will act the same
+ regardless of which of these four options you choose.)
+ Elsewhere, you can detect whether a foreign table was specified to be
+ locked by this type of command by using get_plan_rowmark at
+ plan time, or ExecFindRowMark at execution time; you must
+ check not only whether a non-null rowmark struct is returned, but that
+ its strength field is not LCS_NONE.
+
+ Lastly, for foreign tables that are used in an UPDATE,
+ DELETE or SELECT FOR UPDATE/SHARE command but
+ are not specified to be row-locked, you can override the default choice
+ to copy entire rows by having GetForeignRowMarkType select
+ option ROW_MARK_REFERENCE when it sees lock strength
+ LCS_NONE. This will cause RefetchForeignRow to
+ be called with that value for markType; it should then
+ re-fetch the row without acquiring any new lock. (If you have
+ a GetForeignRowMarkType function but don't wish to re-fetch
+ unlocked rows, select option ROW_MARK_COPY
+ for LCS_NONE.)
+
+ See src/include/nodes/lockoptions.h, the comments
+ for RowMarkType and PlanRowMark
+ in src/include/nodes/plannodes.h, and the comments for
+ ExecRowMark in src/include/nodes/execnodes.h for
+ additional information.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fdwhandler.html b/pgsql/doc/postgresql/html/fdwhandler.html
new file mode 100644
index 0000000000000000000000000000000000000000..17a926353d797b113b0a0564cf8d85d65e243aaf
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fdwhandler.html
@@ -0,0 +1,21 @@
+
+Chapter 59. Writing a Foreign Data Wrapper
+ All operations on a foreign table are handled through its foreign data
+ wrapper, which consists of a set of functions that the core server
+ calls. The foreign data wrapper is responsible for fetching
+ data from the remote data source and returning it to the
+ PostgreSQL executor. If updating foreign
+ tables is to be supported, the wrapper must handle that, too.
+ This chapter outlines how to write a new foreign data wrapper.
+
+ The foreign data wrappers included in the standard distribution are good
+ references when trying to write your own. Look into the
+ contrib subdirectory of the source tree.
+ The CREATE FOREIGN DATA WRAPPER reference page also has
+ some useful details.
+
Note
+ The SQL standard specifies an interface for writing foreign data wrappers.
+ However, PostgreSQL does not implement that API, because the effort to
+ accommodate it into PostgreSQL would be large, and the standard API hasn't
+ gained wide adoption anyway.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/features-sql-standard.html b/pgsql/doc/postgresql/html/features-sql-standard.html
new file mode 100644
index 0000000000000000000000000000000000000000..b6bdb3ae52678debdbed92a12cbc07cd0ab0af44
--- /dev/null
+++ b/pgsql/doc/postgresql/html/features-sql-standard.html
@@ -0,0 +1,4 @@
+
+D.1. Supported Features
trims trailing spaces from CHARACTER values before counting
E021-05
Core
OCTET_LENGTH function
E021-06
Core
SUBSTRING function
E021-07
Core
Character concatenation
E021-08
Core
UPPER and LOWER functions
E021-09
Core
TRIM function
E021-10
Core
Implicit casting among the character string types
E021-11
Core
POSITION function
E021-12
Core
Character comparison
E031
Core
Identifiers
E031-01
Core
Delimited identifiers
E031-02
Core
Lower case identifiers
E031-03
Core
Trailing underscore
E051
Core
Basic query specification
E051-01
Core
SELECT DISTINCT
E051-02
Core
GROUP BY clause
E051-04
Core
GROUP BY can contain columns not in <select list>
E051-05
Core
Select list items can be renamed
E051-06
Core
HAVING clause
E051-07
Core
Qualified * in select list
E051-08
Core
Correlation names in the FROM clause
E051-09
Core
Rename columns in the FROM clause
E061
Core
Basic predicates and search conditions
E061-01
Core
Comparison predicate
E061-02
Core
BETWEEN predicate
E061-03
Core
IN predicate with list of values
E061-04
Core
LIKE predicate
E061-05
Core
LIKE predicate ESCAPE clause
E061-06
Core
NULL predicate
E061-07
Core
Quantified comparison predicate
E061-08
Core
EXISTS predicate
E061-09
Core
Subqueries in comparison predicate
E061-11
Core
Subqueries in IN predicate
E061-12
Core
Subqueries in quantified comparison predicate
E061-13
Core
Correlated subqueries
E061-14
Core
Search condition
E071
Core
Basic query expressions
E071-01
Core
UNION DISTINCT table operator
E071-02
Core
UNION ALL table operator
E071-03
Core
EXCEPT DISTINCT table operator
E071-05
Core
Columns combined via table operators need not have exactly the same data type
E071-06
Core
Table operators in subqueries
E081
Core
Basic Privileges
E081-01
Core
SELECT privilege
E081-02
Core
DELETE privilege
E081-03
Core
INSERT privilege at the table level
E081-04
Core
UPDATE privilege at the table level
E081-05
Core
UPDATE privilege at the column level
E081-06
Core
REFERENCES privilege at the table level
E081-07
Core
REFERENCES privilege at the column level
E081-08
Core
WITH GRANT OPTION
E081-09
Core
USAGE privilege
E081-10
Core
EXECUTE privilege
E091
Core
Set functions
E091-01
Core
AVG
E091-02
Core
COUNT
E091-03
Core
MAX
E091-04
Core
MIN
E091-05
Core
SUM
E091-06
Core
ALL quantifier
E091-07
Core
DISTINCT quantifier
E101
Core
Basic data manipulation
E101-01
Core
INSERT statement
E101-03
Core
Searched UPDATE statement
E101-04
Core
Searched DELETE statement
E111
Core
Single row SELECT statement
E121
Core
Basic cursor support
E121-01
Core
DECLARE CURSOR
E121-02
Core
ORDER BY columns need not be in select list
E121-03
Core
Value expressions in ORDER BY clause
E121-04
Core
OPEN statement
E121-06
Core
Positioned UPDATE statement
E121-07
Core
Positioned DELETE statement
E121-08
Core
CLOSE statement
E121-10
Core
FETCH statement implicit NEXT
E121-17
Core
WITH HOLD cursors
E131
Core
Null value support (nulls in lieu of values)
E141
Core
Basic integrity constraints
E141-01
Core
NOT NULL constraints
E141-02
Core
UNIQUE constraints of NOT NULL columns
E141-03
Core
PRIMARY KEY constraints
E141-04
Core
Basic FOREIGN KEY constraint with the NO ACTION default for both referential delete action and referential update action
E141-06
Core
CHECK constraints
E141-07
Core
Column defaults
E141-08
Core
NOT NULL inferred on PRIMARY KEY
E141-10
Core
Names in a foreign key can be specified in any order
E151
Core
Transaction support
E151-01
Core
COMMIT statement
E151-02
Core
ROLLBACK statement
E152
Core
Basic SET TRANSACTION statement
E152-01
Core
SET TRANSACTION statement: ISOLATION LEVEL SERIALIZABLE clause
E152-02
Core
SET TRANSACTION statement: READ ONLY and READ WRITE clauses
E153
Core
Updatable queries with subqueries
E161
Core
SQL comments using leading double minus
E171
Core
SQLSTATE support
E182
Core
Host language binding
F021
Core
Basic information schema
F021-01
Core
COLUMNS view
F021-02
Core
TABLES view
F021-03
Core
VIEWS view
F021-04
Core
TABLE_CONSTRAINTS view
F021-05
Core
REFERENTIAL_CONSTRAINTS view
F021-06
Core
CHECK_CONSTRAINTS view
F031
Core
Basic schema manipulation
F031-01
Core
CREATE TABLE statement to create persistent base tables
F031-02
Core
CREATE VIEW statement
F031-03
Core
GRANT statement
F031-04
Core
ALTER TABLE statement: ADD COLUMN clause
F031-13
Core
DROP TABLE statement: RESTRICT clause
F031-16
Core
DROP VIEW statement: RESTRICT clause
F031-19
Core
REVOKE statement: RESTRICT clause
F032
CASCADE drop behavior
F033
ALTER TABLE statement: DROP COLUMN clause
F034
Extended REVOKE statement
F035
REVOKE with CASCADE
F036
REVOKE statement performed by non-owner
F037
REVOKE statement: GRANT OPTION FOR clause
F038
REVOKE of a WITH GRANT OPTION privilege
F041
Core
Basic joined table
F041-01
Core
Inner join (but not necessarily the INNER keyword)
F041-02
Core
INNER keyword
F041-03
Core
LEFT OUTER JOIN
F041-04
Core
RIGHT OUTER JOIN
F041-05
Core
Outer joins can be nested
F041-07
Core
The inner table in a left or right outer join can also be used in an inner join
F041-08
Core
All comparison operators are supported (rather than just =)
F051
Core
Basic date and time
F051-01
Core
DATE data type (including support of DATE literal)
F051-02
Core
TIME data type (including support of TIME literal) with fractional seconds precision of at least 0
F051-03
Core
TIMESTAMP data type (including support of TIMESTAMP literal) with fractional seconds precision of at least 0 and 6
F051-04
Core
Comparison predicate on DATE, TIME, and TIMESTAMP data types
F051-05
Core
Explicit CAST between datetime types and character string types
F051-06
Core
CURRENT_DATE
F051-07
Core
LOCALTIME
F051-08
Core
LOCALTIMESTAMP
F052
Intervals and datetime arithmetic
F053
OVERLAPS predicate
F081
Core
UNION and EXCEPT in views
F111
Isolation levels other than SERIALIZABLE
F112
Isolation level READ UNCOMMITTED
F113
Isolation level READ COMMITTED
F114
Isolation level REPEATABLE READ
F131
Core
Grouped operations
F131-01
Core
WHERE, GROUP BY, and HAVING clauses supported in queries with grouped views
F131-02
Core
Multiple tables supported in queries with grouped views
F131-03
Core
Set functions supported in queries with grouped views
F131-04
Core
Subqueries with GROUP BY and HAVING clauses and grouped views
F131-05
Core
Single row SELECT with GROUP BY and HAVING clauses and grouped views
F171
Multiple schemas per user
F181
Core
Multiple module support
F191
Referential delete actions
F200
TRUNCATE TABLE statement
F201
Core
CAST function
F202
TRUNCATE TABLE: identity column restart option
F221
Core
Explicit defaults
F222
INSERT statement: DEFAULT VALUES clause
F231
Privilege tables
F251
Domain support
F261
Core
CASE expression
F261-01
Core
Simple CASE
F261-02
Core
Searched CASE
F261-03
Core
NULLIF
F261-04
Core
COALESCE
F262
Extended CASE expression
F271
Compound character literals
F281
LIKE enhancements
F292
UNIQUE null treatment
F302
INTERSECT table operator
F303
INTERSECT DISTINCT table operator
F304
EXCEPT ALL table operator
F305
INTERSECT ALL table operator
F311
Core
Schema definition statement
F311-01
Core
CREATE SCHEMA
F311-02
Core
CREATE TABLE for persistent base tables
F311-03
Core
CREATE VIEW
F311-04
Core
CREATE VIEW: WITH CHECK OPTION
F311-05
Core
GRANT statement
F312
MERGE statement
F313
Enhanced MERGE statement
F314
MERGE statement with DELETE branch
F321
User authorization
F341
Usage tables
F361
Subprogram support
F381
Extended schema manipulation
F382
Alter column data type
F383
Set column not null clause
F384
Drop identity property clause
F385
Drop column generation expression clause
F386
Set identity column generation clause
F387
ALTER TABLE statement: ALTER COLUMN clause
F388
ALTER TABLE statement: ADD/DROP CONSTRAINT clause
F391
Long identifiers
F392
Unicode escapes in identifiers
F393
Unicode escapes in literals
F394
Optional normal form specification
F401
Extended joined table
F402
Named column joins for LOBs, arrays, and multisets
F404
Range variable for common column names
F405
NATURAL JOIN
F406
FULL OUTER JOIN
F407
CROSS JOIN
F411
Time zone specification
differences regarding literal interpretation
F421
National character
F431
Read-only scrollable cursors
F432
FETCH with explicit NEXT
F433
FETCH FIRST
F434
FETCH LAST
F435
FETCH PRIOR
F436
FETCH ABSOLUTE
F437
FETCH RELATIVE
F438
Scrollable cursors
F441
Extended set function support
F442
Mixed column references in set functions
F471
Core
Scalar subquery values
F481
Core
Expanded NULL predicate
F491
Constraint management
F501
Core
Features and conformance views
F501-01
Core
SQL_FEATURES view
F501-02
Core
SQL_SIZING view
F502
Enhanced documentation tables
F531
Temporary tables
F555
Enhanced seconds precision
F561
Full value expressions
F571
Truth value tests
F591
Derived tables
F611
Indicator data types
F641
Row and table constructors
F651
Catalog name qualifiers
F661
Simple tables
F672
Retrospective CHECK constraints
F690
Collation support
F692
Extended collation support
F701
Referential update actions
F711
ALTER domain
F731
INSERT column privileges
F751
View CHECK enhancements
F761
Session management
F762
CURRENT_CATALOG
F763
CURRENT_SCHEMA
F771
Connection management
F781
Self-referencing operations
F791
Insensitive cursors
F801
Full set function
F850
Top-level ORDER BY in query expression
F851
ORDER BY in subqueries
F852
Top-level ORDER BY in views
F855
Nested ORDER BY in query expression
F856
Nested FETCH FIRST in query expression
F857
Top-level FETCH FIRST in query expression
F858
FETCH FIRST in subqueries
F859
Top-level FETCH FIRST in views
F860
Dynamic FETCH FIRST row count
F861
Top-level OFFSET in query expression
F862
OFFSET in subqueries
F863
Nested OFFSET in query expression
F864
Top-level OFFSET in views
F865
Dynamic offset row count in OFFSET
F867
FETCH FIRST clause: WITH TIES option
F868
ORDER BY in grouped table
F869
SQL implementation info population
S071
SQL paths in function and type name resolution
S090
Minimal array support
S092
Arrays of user-defined types
S095
Array constructors by query
S096
Optional array bounds
S098
ARRAY_AGG
S099
Array expressions
S111
ONLY in query expressions
S201
SQL-invoked routines on arrays
S203
Array parameters
S204
Array as result type of functions
S211
User-defined cast functions
S301
Enhanced UNNEST
S404
TRIM_ARRAY
T031
BOOLEAN data type
T054
GREATEST and LEAST
different null handling
T055
String padding functions
T056
Multi-character TRIM functions
T061
UCS support
T071
BIGINT data type
T081
Optional string types maximum length
T121
WITH (excluding RECURSIVE) in query expression
T122
WITH (excluding RECURSIVE) in subquery
T131
Recursive query
T132
Recursive query in subquery
T133
Enhanced cycle mark values
T141
SIMILAR predicate
T151
DISTINCT predicate
T152
DISTINCT predicate with negation
T171
LIKE clause in table definition
T172
AS subquery clause in table definition
T173
Extended LIKE clause in table definition
T174
Identity columns
T177
Sequence generator support: simple restart option
T178
Identity columns: simple restart option
T191
Referential action RESTRICT
T201
Comparable data types for referential constraints
T212
Enhanced trigger capability
T213
INSTEAD OF triggers
T214
BEFORE triggers
T215
AFTER triggers
T216
Ability to require true search condition before trigger is invoked
T217
TRIGGER privilege
T241
START TRANSACTION statement
T261
Chained transactions
T271
Savepoints
T281
SELECT privilege with column granularity
T285
Enhanced derived column names
T312
OVERLAY function
T321-01
Core
User-defined functions with no overloading
T321-02
Core
User-defined stored procedures with no overloading
T321-03
Core
Function invocation
T321-04
Core
CALL statement
T321-05
Core
RETURN statement
T321-06
Core
ROUTINES view
T321-07
Core
PARAMETERS view
T323
Explicit security for external routines
T325
Qualified SQL parameter references
T331
Basic roles
T332
Extended roles
T341
Overloading of SQL-invoked functions and SQL-invoked procedures
T351
Bracketed comments
T431
Extended grouping capabilities
T432
Nested and concatenated GROUPING SETS
T433
Multi-argument GROUPING function
T434
GROUP BY DISTINCT
T441
ABS and MOD functions
T461
Symmetric BETWEEN predicate
T491
LATERAL derived table
T501
Enhanced EXISTS predicate
T521
Named arguments in CALL statement
T523
Default values for INOUT parameters of SQL-invoked procedures
T524
Named arguments in routine invocations other than a CALL statement
T525
Default values for parameters of SQL-invoked functions
T551
Optional key words for default syntax
T581
Regular expression substring function
T591
UNIQUE constraints of possibly null columns
T611
Elementary OLAP operations
T612
Advanced OLAP operations
T613
Sampling
T614
NTILE function
T615
LEAD and LAG functions
T617
FIRST_VALUE and LAST_VALUE functions
T620
WINDOW clause: GROUPS option
T621
Enhanced numeric functions
T622
Trigonometric functions
T623
General logarithm functions
T624
Common logarithm functions
T626
ANY_VALUE
T627
Window framed COUNT DISTINCT
T631
Core
IN predicate with one list element
T651
SQL-schema statements in SQL routines
T653
SQL-schema statements in external routines
T655
Cyclically dependent routines
T661
Non-decimal integer literals
T662
Underscores in numeric literals
T670
Schema and data statement mixing
T803
String-based JSON
T811
Basic SQL/JSON constructor functions
T812
SQL/JSON: JSON_OBJECTAGG
T813
SQL/JSON: JSON_ARRAYAGG with ORDER BY
T814
Colon in JSON_OBJECT or JSON_OBJECTAGG
T822
SQL/JSON: IS JSON WITH UNIQUE KEYS predicate
T830
Enforcing unique keys in SQL/JSON constructor functions
T831
SQL/JSON path language: strict mode
T832
SQL/JSON path language: item method
T833
SQL/JSON path language: multiple subscripts
T834
SQL/JSON path language: wildcard member accessor
T835
SQL/JSON path language: filter expressions
T836
SQL/JSON path language: starts with predicate
T837
SQL/JSON path language: regex_like predicate
T840
Hex integer literals in SQL/JSON path language
T851
SQL/JSON: optional keywords for default syntax
T879
JSON in equality operations
with jsonb
T880
JSON in grouping operations
with jsonb
X010
XML type
X011
Arrays of XML type
X014
Attributes of XML type
X016
Persistent XML values
X020
XMLConcat
X031
XMLElement
X032
XMLForest
X034
XMLAgg
X035
XMLAgg: ORDER BY option
X036
XMLComment
X037
XMLPI
X040
Basic table mapping
X041
Basic table mapping: null absent
X042
Basic table mapping: null as nil
X043
Basic table mapping: table as forest
X044
Basic table mapping: table as element
X045
Basic table mapping: with target namespace
X046
Basic table mapping: data mapping
X047
Basic table mapping: metadata mapping
X048
Basic table mapping: base64 encoding of binary strings
X049
Basic table mapping: hex encoding of binary strings
X050
Advanced table mapping
X051
Advanced table mapping: null absent
X052
Advanced table mapping: null as nil
X053
Advanced table mapping: table as forest
X054
Advanced table mapping: table as element
X055
Advanced table mapping: with target namespace
X056
Advanced table mapping: data mapping
X057
Advanced table mapping: metadata mapping
X058
Advanced table mapping: base64 encoding of binary strings
X059
Advanced table mapping: hex encoding of binary strings
X060
XMLParse: character string input and CONTENT option
X061
XMLParse: character string input and DOCUMENT option
X069
XMLSerialize: INDENT
X070
XMLSerialize: character string serialization and CONTENT option
X071
XMLSerialize: character string serialization and DOCUMENT option
X072
XMLSerialize: character string serialization
X090
XML document predicate
X120
XML parameters in SQL routines
X121
XML parameters in external routines
X221
XML passing mechanism BY VALUE
X301
XMLTable: derived column list option
X302
XMLTable: ordinality column option
X303
XMLTable: column default option
X304
XMLTable: passing a context item
must be XML DOCUMENT
X400
Name and identifier mapping
X410
Alter column data type: XML type
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/features.html b/pgsql/doc/postgresql/html/features.html
new file mode 100644
index 0000000000000000000000000000000000000000..327053dc552b6fcce16b409670958dcdc9cc0eaf
--- /dev/null
+++ b/pgsql/doc/postgresql/html/features.html
@@ -0,0 +1,73 @@
+
+Appendix D. SQL Conformance
+ This section attempts to outline to what extent
+ PostgreSQL conforms to the current SQL
+ standard. The following information is not a full statement of
+ conformance, but it presents the main topics in as much detail as is
+ both reasonable and useful for users.
+
+ The formal name of the SQL standard is ISO/IEC 9075 “Database
+ Language SQL”. A revised version of the standard is released
+ from time to time; the most recent update appearing in 2023.
+ The 2023 version is referred to as ISO/IEC 9075:2023, or simply as SQL:2023.
+ The versions prior to that were SQL:2016, SQL:2011, SQL:2008, SQL:2006, SQL:2003,
+ SQL:1999, and SQL-92. Each version
+ replaces the previous one, so claims of conformance to earlier
+ versions have no official merit.
+ PostgreSQL development aims for
+ conformance with the latest official version of the standard where
+ such conformance does not contradict traditional features or common
+ sense. Many of the features required by the SQL
+ standard are supported, though sometimes with slightly differing
+ syntax or function. Further moves towards conformance can be
+ expected over time.
+
+ SQL-92 defined three feature sets for
+ conformance: Entry, Intermediate, and Full. Most database
+ management systems claiming SQL standard
+ conformance were conforming at only the Entry level, since the
+ entire set of features in the Intermediate and Full levels was
+ either too voluminous or in conflict with legacy behaviors.
+
+ Starting with SQL:1999, the SQL standard defines
+ a large set of individual features rather than the ineffectively
+ broad three levels found in SQL-92. A large
+ subset of these features represents the “Core”
+ features, which every conforming SQL implementation must supply.
+ The rest of the features are purely optional.
+
+ The standard is split into a number of parts, each also known by a shorthand
+ name:
+
+
+
+ Note that some part numbers are not (or no longer) used.
+
+ The PostgreSQL core covers parts 1, 2, 9,
+ 11, and 14. Part 3 is covered by the ODBC driver, and part 13 is
+ covered by the PL/Java plug-in, but exact conformance is currently
+ not being verified for these components. There are currently no
+ implementations of parts 4, 10, 15, and 16
+ for PostgreSQL.
+
+ PostgreSQL supports most of the major features of SQL:2023. Out of
+ 177 mandatory features required for full Core conformance,
+ PostgreSQL conforms to at least 170. In addition, there is a long
+ list of supported optional features. It might be worth noting that at
+ the time of writing, no current version of any database management
+ system claims full conformance to Core SQL:2023.
+
+ In the following two sections, we provide a list of those features
+ that PostgreSQL supports, followed by a
+ list of the features defined in SQL:2023 which
+ are not yet supported in PostgreSQL.
+ Both of these lists are approximate: There might be minor details that
+ are nonconforming for a feature that is listed as supported, and
+ large parts of an unsupported feature might in fact be implemented.
+ The main body of the documentation always contains the most accurate
+ information about what does and does not work.
+
Note
+ Feature codes containing a hyphen are subfeatures. Therefore, if a
+ particular subfeature is not supported, the main feature is listed
+ as unsupported even if some other subfeatures are supported.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/file-fdw.html b/pgsql/doc/postgresql/html/file-fdw.html
new file mode 100644
index 0000000000000000000000000000000000000000..d51a45527487dfce71fc8669a1bb8d70e52a8587
--- /dev/null
+++ b/pgsql/doc/postgresql/html/file-fdw.html
@@ -0,0 +1,145 @@
+
+F.16. file_fdw — access data files in the server's file system
F.16. file_fdw — access data files in the server's file system
F.16. file_fdw — access data files in the server's file system #
+ The file_fdw module provides the foreign-data wrapper
+ file_fdw, which can be used to access data
+ files in the server's file system, or to execute programs on the server
+ and read their output. The data file or program output must be in a format
+ that can be read by COPY FROM;
+ see COPY for details.
+ Access to data files is currently read-only.
+
+ A foreign table created using this wrapper can have the following options:
+
filename
+ Specifies the file to be read. Relative paths are relative to the
+ data directory.
+ Either filename or program must be
+ specified, but not both.
+
program
+ Specifies the command to be executed. The standard output of this
+ command will be read as though COPY FROM PROGRAM were used.
+ Either program or filename must be
+ specified, but not both.
+
format
+ Specifies the data format,
+ the same as COPY's FORMAT option.
+
header
+ Specifies whether the data has a header line,
+ the same as COPY's HEADER option.
+
delimiter
+ Specifies the data delimiter character,
+ the same as COPY's DELIMITER option.
+
quote
+ Specifies the data quote character,
+ the same as COPY's QUOTE option.
+
escape
+ Specifies the data escape character,
+ the same as COPY's ESCAPE option.
+
null
+ Specifies the data null string,
+ the same as COPY's NULL option.
+
encoding
+ Specifies the data encoding,
+ the same as COPY's ENCODING option.
+
+ Note that while COPY allows options such as HEADER
+ to be specified without a corresponding value, the foreign table option
+ syntax requires a value to be present in all cases. To activate
+ COPY options typically written without a value, you can pass
+ the value TRUE, since all such options are Booleans.
+
+ A column of a foreign table created using this wrapper can have the
+ following options:
+
force_not_null
+ This is a Boolean option. If true, it specifies that values of the
+ column should not be matched against the null string (that is, the
+ table-level null option). This has the same effect
+ as listing the column in COPY's
+ FORCE_NOT_NULL option.
+
force_null
+ This is a Boolean option. If true, it specifies that values of the
+ column which match the null string are returned as NULL
+ even if the value is quoted. Without this option, only unquoted
+ values matching the null string are returned as NULL.
+ This has the same effect as listing the column in
+ COPY's FORCE_NULL option.
+
+ COPY's FORCE_QUOTE option is
+ currently not supported by file_fdw.
+
+ These options can only be specified for a foreign table or its columns, not
+ in the options of the file_fdw foreign-data wrapper, nor in the
+ options of a server or user mapping using the wrapper.
+
+ Changing table-level options requires being a superuser or having the privileges
+ of the role pg_read_server_files (to use a filename) or
+ the role pg_execute_server_program (to use a program),
+ for security reasons: only certain users should be able to control which file is
+ read or which program is run. In principle regular users could be allowed to
+ change the other options, but that's not supported at present.
+
+ When specifying the program option, keep in mind that the option
+ string is executed by the shell. If you need to pass any arguments to the
+ command that come from an untrusted source, you must be careful to strip or
+ escape any characters that might have special meaning to the shell.
+ For security reasons, it is best to use a fixed command string, or at least
+ avoid passing any user input in it.
+
+ For a foreign table using file_fdw, EXPLAIN shows
+ the name of the file to be read or program to be run.
+ For a file, unless COSTS OFF is
+ specified, the file size (in bytes) is shown as well.
+
Example F.1. Create a Foreign Table for PostgreSQL CSV Logs
+ One of the obvious uses for file_fdw is to make
+ the PostgreSQL activity log available as a table for querying. To
+ do this, first you must be logging to a CSV file,
+ which here we
+ will call pglog.csv. First, install file_fdw
+ as an extension:
+
+CREATE EXTENSION file_fdw;
+
+ Then create a foreign server:
+
+
+CREATE SERVER pglog FOREIGN DATA WRAPPER file_fdw;
+
+
+ Now you are ready to create the foreign data table. Using the
+ CREATE FOREIGN TABLE command, you will need to define
+ the columns for the table, the CSV file name, and its format:
+
+
+ That's it — now you can query your log directly. In production, of
+ course, you would need to define some way to deal with log rotation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-admin.html b/pgsql/doc/postgresql/html/functions-admin.html
new file mode 100644
index 0000000000000000000000000000000000000000..79abf74243c12cacef1cb44eef07cc5535c12af1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-admin.html
@@ -0,0 +1,1694 @@
+
+9.27. System Administration Functions
+ Returns the current value of the
+ setting setting_name. If there is no such
+ setting, current_setting throws an error
+ unless missing_ok is supplied and
+ is true (in which case NULL is returned).
+ This function corresponds to
+ the SQL command SHOW.
+
+ Sets the parameter setting_name
+ to new_value, and returns that value.
+ If is_local is true, the new
+ value will only apply during the current transaction. If you want the
+ new value to apply for the rest of the current session,
+ use false instead. This function corresponds to
+ the SQL command SET.
+
+
+ set_config('log_statement_stats', 'off', false)
+ → off
+
+ The functions shown in Table 9.90 send control signals to
+ other server processes. Use of these functions is restricted to
+ superusers by default but access may be granted to others using
+ GRANT, with noted exceptions.
+
+ Each of these functions returns true if
+ the signal was successfully sent and false
+ if sending the signal failed.
+
+ Cancels the current query of the session whose backend process has the
+ specified process ID. This is also allowed if the
+ calling role is a member of the role whose backend is being canceled or
+ the calling role has privileges of pg_signal_backend,
+ however only superusers can cancel superuser backends.
+
+ Requests to log the memory contexts of the backend with the
+ specified process ID. This function can send the request to
+ backends and auxiliary processes except logger. These memory contexts
+ will be logged at
+ LOG message level. They will appear in
+ the server log based on the log configuration set
+ (see Section 20.8 for more information),
+ but will not be sent to the client regardless of
+ client_min_messages.
+
+
+ pg_reload_conf ()
+ → boolean
+
+
+ Causes all processes of the PostgreSQL
+ server to reload their configuration files. (This is initiated by
+ sending a SIGHUP signal to the postmaster
+ process, which in turn sends SIGHUP to each
+ of its children.) You can use the
+ pg_file_settings,
+ pg_hba_file_rules and
+ pg_ident_file_mappings views
+ to check the configuration files for possible errors, before reloading.
+
+
+ pg_rotate_logfile ()
+ → boolean
+
+
+ Signals the log-file manager to switch to a new output file
+ immediately. This works only when the built-in log collector is
+ running, since otherwise there is no log-file manager subprocess.
+
+ Terminates the session whose backend process has the
+ specified process ID. This is also allowed if the calling role
+ is a member of the role whose backend is being terminated or the
+ calling role has privileges of pg_signal_backend,
+ however only superusers can terminate superuser backends.
+
+
+ If timeout is not specified or zero, this
+ function returns true whether the process actually
+ terminates or not, indicating only that the sending of the signal was
+ successful. If the timeout is specified (in
+ milliseconds) and greater than zero, the function waits until the
+ process is actually terminated or until the given time has passed. If
+ the process is terminated, the function
+ returns true. On timeout, a warning is emitted and
+ false is returned.
+
+ pg_cancel_backend and pg_terminate_backend
+ send signals (SIGINT or SIGTERM
+ respectively) to backend processes identified by process ID.
+ The process ID of an active backend can be found from
+ the pid column of the
+ pg_stat_activity view, or by listing the
+ postgres processes on the server (using
+ ps on Unix or the Task
+ Manager on Windows).
+ The role of an active backend can be found from the
+ usename column of the
+ pg_stat_activity view.
+
+ pg_log_backend_memory_contexts can be used
+ to log the memory contexts of a backend process. For example:
+
+One message for each memory context will be logged. For example:
+
+LOG: logging memory contexts of PID 10377
+STATEMENT: SELECT pg_log_backend_memory_contexts(pg_backend_pid());
+LOG: level: 0; TopMemoryContext: 80800 total in 6 blocks; 14432 free (5 chunks); 66368 used
+LOG: level: 1; pgstat TabStatusArray lookup hash table: 8192 total in 1 blocks; 1408 free (0 chunks); 6784 used
+LOG: level: 1; TopTransactionContext: 8192 total in 1 blocks; 7720 free (1 chunks); 472 used
+LOG: level: 1; RowDescriptionContext: 8192 total in 1 blocks; 6880 free (0 chunks); 1312 used
+LOG: level: 1; MessageContext: 16384 total in 2 blocks; 5152 free (0 chunks); 11232 used
+LOG: level: 1; Operator class cache: 8192 total in 1 blocks; 512 free (0 chunks); 7680 used
+LOG: level: 1; smgr relation table: 16384 total in 2 blocks; 4544 free (3 chunks); 11840 used
+LOG: level: 1; TransactionAbortContext: 32768 total in 1 blocks; 32504 free (0 chunks); 264 used
+...
+LOG: level: 1; ErrorContext: 8192 total in 1 blocks; 7928 free (3 chunks); 264 used
+LOG: Grand total: 1651920 bytes in 201 blocks; 622360 free (88 chunks); 1029560 used
+
+ If there are more than 100 child contexts under the same parent, the first
+ 100 child contexts are logged, along with a summary of the remaining contexts.
+ Note that frequent calls to this function could incur significant overhead,
+ because it may generate a large number of log messages.
+
+ The functions shown in Table 9.91 assist in making on-line backups.
+ These functions cannot be executed during recovery (except
+ pg_backup_start,
+ pg_backup_stop,
+ and pg_wal_lsn_diff).
+
+ For details about proper usage of these functions, see
+ Section 26.3.
+
+ Creates a named marker record in the write-ahead log that can later be
+ used as a recovery target, and returns the corresponding write-ahead
+ log location. The given name can then be used with
+ recovery_target_name to specify the point up to
+ which recovery will proceed. Avoid creating multiple restore points
+ with the same name, since recovery will stop at the first one whose
+ name matches the recovery target.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ pg_current_wal_flush_lsn ()
+ → pg_lsn
+
+
+ Returns the current write-ahead log flush location (see notes below).
+
+
+ pg_current_wal_insert_lsn ()
+ → pg_lsn
+
+
+ Returns the current write-ahead log insert location (see notes below).
+
+
+ pg_current_wal_lsn ()
+ → pg_lsn
+
+
+ Returns the current write-ahead log write location (see notes below).
+
+ Prepares the server to begin an on-line backup. The only required
+ parameter is an arbitrary user-defined label for the backup.
+ (Typically this would be the name under which the backup dump file
+ will be stored.)
+ If the optional second parameter is given as true,
+ it specifies executing pg_backup_start as quickly
+ as possible. This forces an immediate checkpoint which will cause a
+ spike in I/O operations, slowing any concurrently executing queries.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+ Finishes performing an on-line backup. The desired contents of the
+ backup label file and the tablespace map file are returned as part of
+ the result of the function and must be written to files in the
+ backup area. These files must not be written to the live data directory
+ (doing so will cause PostgreSQL to fail to restart in the event of a
+ crash).
+
+
+ There is an optional parameter of type boolean.
+ If false, the function will return immediately after the backup is
+ completed, without waiting for WAL to be archived. This behavior is
+ only useful with backup software that independently monitors WAL
+ archiving. Otherwise, WAL required to make the backup consistent might
+ be missing and make the backup useless. By default or when this
+ parameter is true, pg_backup_stop will wait for
+ WAL to be archived when archiving is enabled. (On a standby, this
+ means that it will wait only when archive_mode =
+ always. If write activity on the primary is low,
+ it may be useful to run pg_switch_wal on the
+ primary in order to trigger an immediate segment switch.)
+
+
+ When executed on a primary, this function also creates a backup
+ history file in the write-ahead log archive area. The history file
+ includes the label given to pg_backup_start, the
+ starting and ending write-ahead log locations for the backup, and the
+ starting and ending times of the backup. After recording the ending
+ location, the current write-ahead log insertion point is automatically
+ advanced to the next write-ahead log file, so that the ending
+ write-ahead log file can be archived immediately to complete the
+ backup.
+
+
+ The result of the function is a single record.
+ The lsn column holds the backup's ending
+ write-ahead log location (which again can be ignored). The second
+ column returns the contents of the backup label file, and the third
+ column returns the contents of the tablespace map file. These must be
+ stored as part of the backup and are required as part of the restore
+ process.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ pg_switch_wal ()
+ → pg_lsn
+
+
+ Forces the server to switch to a new write-ahead log file, which
+ allows the current file to be archived (assuming you are using
+ continuous archiving). The result is the ending write-ahead log
+ location plus 1 within the just-completed write-ahead log file. If
+ there has been no write-ahead log activity since the last write-ahead
+ log switch, pg_switch_wal does nothing and
+ returns the start location of the write-ahead log file currently in
+ use.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ pg_walfile_name ( lsnpg_lsn )
+ → text
+
+
+ Converts a write-ahead log location to the name of the WAL file
+ holding that location.
+
+ Calculates the difference in bytes (lsn1 - lsn2) between two write-ahead log
+ locations. This can be used
+ with pg_stat_replication or some of the
+ functions shown in Table 9.91 to
+ get the replication lag.
+
+ pg_current_wal_lsn displays the current write-ahead
+ log write location in the same format used by the above functions.
+ Similarly, pg_current_wal_insert_lsn displays the
+ current write-ahead log insertion location
+ and pg_current_wal_flush_lsn displays the current
+ write-ahead log flush location. The insertion location is
+ the “logical” end of the write-ahead log at any instant,
+ while the write location is the end of what has actually been written out
+ from the server's internal buffers, and the flush location is the last
+ location known to be written to durable storage. The write location is the
+ end of what can be examined from outside the server, and is usually what
+ you want if you are interested in archiving partially-complete write-ahead
+ log files. The insertion and flush locations are made available primarily
+ for server debugging purposes. These are all read-only operations and do
+ not require superuser permissions.
+
+ You can use pg_walfile_name_offset to extract the
+ corresponding write-ahead log file name and byte offset from
+ a pg_lsn value. For example:
+
+ Similarly, pg_walfile_name extracts just the write-ahead log file name.
+ When the given write-ahead log location is exactly at a write-ahead log file boundary, both
+ these functions return the name of the preceding write-ahead log file.
+ This is usually the desired behavior for managing write-ahead log archiving
+ behavior, since the preceding file is the last one that currently
+ needs to be archived.
+
+ pg_split_walfile_name is useful to compute a
+ LSN from a file offset and WAL file name, for example:
+
+ The functions shown in Table 9.92 provide information
+ about the current status of a standby server.
+ These functions may be executed both during recovery and in normal running.
+
Table 9.92. Recovery Information Functions
+ Function
+
+
+ Description
+
+
+ pg_is_in_recovery ()
+ → boolean
+
+
+ Returns true if recovery is still in progress.
+
+
+ pg_last_wal_receive_lsn ()
+ → pg_lsn
+
+
+ Returns the last write-ahead log location that has been received and
+ synced to disk by streaming replication. While streaming replication
+ is in progress this will increase monotonically. If recovery has
+ completed then this will remain static at the location of the last WAL
+ record received and synced to disk during recovery. If streaming
+ replication is disabled, or if it has not yet started, the function
+ returns NULL.
+
+
+ pg_last_wal_replay_lsn ()
+ → pg_lsn
+
+
+ Returns the last write-ahead log location that has been replayed
+ during recovery. If recovery is still in progress this will increase
+ monotonically. If recovery has completed then this will remain
+ static at the location of the last WAL record applied during recovery.
+ When the server has been started normally without recovery, the
+ function returns NULL.
+
+
+ pg_last_xact_replay_timestamp ()
+ → timestamp with time zone
+
+
+ Returns the time stamp of the last transaction replayed during
+ recovery. This is the time at which the commit or abort WAL record
+ for that transaction was generated on the primary. If no transactions
+ have been replayed during recovery, the function
+ returns NULL. Otherwise, if recovery is still in
+ progress this will increase monotonically. If recovery has completed
+ then this will remain static at the time of the last transaction
+ applied during recovery. When the server has been started normally
+ without recovery, the function returns NULL.
+
+ Returns the currently-loaded WAL resource managers in the system. The
+ column rm_builtin indicates whether it's a
+ built-in resource manager, or a custom resource manager loaded by an
+ extension.
+
+ The functions shown in Table 9.93 control the progress of recovery.
+ These functions may be executed only during recovery.
+
Table 9.93. Recovery Control Functions
+ Function
+
+
+ Description
+
+
+ pg_is_wal_replay_paused ()
+ → boolean
+
+
+ Returns true if recovery pause is requested.
+
+
+ pg_get_wal_replay_pause_state ()
+ → text
+
+
+ Returns recovery pause state. The return values are
+ not paused if pause is not requested,
+ pause requested if pause is requested but recovery is
+ not yet paused, and paused if the recovery is
+ actually paused.
+
+ Promotes a standby server to primary status.
+ With wait set to true (the
+ default), the function waits until promotion is completed
+ or wait_seconds seconds have passed, and
+ returns true if promotion is successful
+ and false otherwise.
+ If wait is set to false, the
+ function returns true immediately after sending a
+ SIGUSR1 signal to the postmaster to trigger
+ promotion.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ pg_wal_replay_pause ()
+ → void
+
+
+ Request to pause recovery. A request doesn't mean that recovery stops
+ right away. If you want a guarantee that recovery is actually paused,
+ you need to check for the recovery pause state returned by
+ pg_get_wal_replay_pause_state(). Note that
+ pg_is_wal_replay_paused() returns whether a request
+ is made. While recovery is paused, no further database changes are applied.
+ If hot standby is active, all new queries will see the same consistent
+ snapshot of the database, and no further query conflicts will be generated
+ until recovery is resumed.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ pg_wal_replay_resume ()
+ → void
+
+
+ Restarts recovery if it was paused.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+ pg_wal_replay_pause and
+ pg_wal_replay_resume cannot be executed while
+ a promotion is ongoing. If a promotion is triggered while recovery
+ is paused, the paused state ends and promotion continues.
+
+ If streaming replication is disabled, the paused state may continue
+ indefinitely without a problem. If streaming replication is in
+ progress then WAL records will continue to be received, which will
+ eventually fill available disk space, depending upon the duration of
+ the pause, the rate of WAL generation and available disk space.
+
+ PostgreSQL allows database sessions to synchronize their
+ snapshots. A snapshot determines which data is visible to the
+ transaction that is using the snapshot. Synchronized snapshots are
+ necessary when two or more sessions need to see identical content in the
+ database. If two sessions just start their transactions independently,
+ there is always a possibility that some third transaction commits
+ between the executions of the two START TRANSACTION commands,
+ so that one session sees the effects of that transaction and the other
+ does not.
+
+ To solve this problem, PostgreSQL allows a transaction to
+ export the snapshot it is using. As long as the exporting
+ transaction remains open, other transactions can import its
+ snapshot, and thereby be guaranteed that they see exactly the same view
+ of the database that the first transaction sees. But note that any
+ database changes made by any one of these transactions remain invisible
+ to the other transactions, as is usual for changes made by uncommitted
+ transactions. So the transactions are synchronized with respect to
+ pre-existing data, but act normally for changes they make themselves.
+
+ Snapshots are exported with the pg_export_snapshot function,
+ shown in Table 9.94, and
+ imported with the SET TRANSACTION command.
+
Table 9.94. Snapshot Synchronization Functions
+ Function
+
+
+ Description
+
+
+ pg_export_snapshot ()
+ → text
+
+
+ Saves the transaction's current snapshot and returns
+ a text string identifying the snapshot. This string must
+ be passed (outside the database) to clients that want to import the
+ snapshot. The snapshot is available for import only until the end of
+ the transaction that exported it.
+
+
+ A transaction can export more than one snapshot, if needed. Note that
+ doing so is only useful in READ COMMITTED
+ transactions, since in REPEATABLE READ and higher
+ isolation levels, transactions use the same snapshot throughout their
+ lifetime. Once a transaction has exported any snapshots, it cannot be
+ prepared with PREPARE TRANSACTION.
+
+
+ pg_log_standby_snapshot ()
+ → pg_lsn
+
+
+ Take a snapshot of running transactions and write it to WAL, without
+ having to wait for bgwriter or checkpointer to log one. This is useful
+ for logical decoding on standby, as logical slot creation has to wait
+ until such a record is replayed on the standby.
+
+ The functions shown
+ in Table 9.95 are for
+ controlling and interacting with replication features.
+ See Section 27.2.5,
+ Section 27.2.6, and
+ Chapter 50
+ for information about the underlying features.
+ Use of functions for replication origin is only allowed to the
+ superuser by default, but may be allowed to other users by using the
+ GRANT command.
+ Use of functions for replication slots is restricted to superusers
+ and users having REPLICATION privilege.
+
+ Many of these functions have equivalent commands in the replication
+ protocol; see Section 55.4.
+
+ Creates a new physical replication slot named
+ slot_name. The optional second parameter,
+ when true, specifies that the LSN for this
+ replication slot be reserved immediately; otherwise
+ the LSN is reserved on first connection from a streaming
+ replication client. Streaming changes from a physical slot is only
+ possible with the streaming-replication protocol —
+ see Section 55.4. The optional third
+ parameter, temporary, when set to true, specifies that
+ the slot should not be permanently stored to disk and is only meant
+ for use by the current session. Temporary slots are also
+ released upon any error. This function corresponds
+ to the replication protocol command CREATE_REPLICATION_SLOT
+ ... PHYSICAL.
+
+ Drops the physical or logical replication slot
+ named slot_name. Same as replication protocol
+ command DROP_REPLICATION_SLOT. For logical slots, this must
+ be called while connected to the same database the slot was created on.
+
+ Creates a new logical (decoding) replication slot named
+ slot_name using the output plugin
+ plugin. The optional third
+ parameter, temporary, when set to true, specifies that
+ the slot should not be permanently stored to disk and is only meant
+ for use by the current session. Temporary slots are also
+ released upon any error. The optional fourth parameter,
+ twophase, when set to true, specifies
+ that the decoding of prepared transactions is enabled for this
+ slot. A call to this function has the same effect as the replication
+ protocol command CREATE_REPLICATION_SLOT ... LOGICAL.
+
+ Copies an existing physical replication slot named src_slot_name
+ to a physical replication slot named dst_slot_name.
+ The copied physical slot starts to reserve WAL from the same LSN as the
+ source slot.
+ temporary is optional. If temporary
+ is omitted, the same value as the source slot is used.
+
+ Copies an existing logical replication slot
+ named src_slot_name to a logical replication
+ slot named dst_slot_name, optionally changing
+ the output plugin and persistence. The copied logical slot starts
+ from the same LSN as the source logical slot. Both
+ temporary and plugin are
+ optional; if they are omitted, the values of the source slot are used.
+
+ Returns changes in the slot slot_name, starting
+ from the point from which changes have been consumed last. If
+ upto_lsn
+ and upto_nchanges are NULL,
+ logical decoding will continue until end of WAL. If
+ upto_lsn is non-NULL, decoding will include only
+ those transactions which commit prior to the specified LSN. If
+ upto_nchanges is non-NULL, decoding will
+ stop when the number of rows produced by decoding exceeds
+ the specified value. Note, however, that the actual number of
+ rows returned may be larger, since this limit is only checked after
+ adding the rows produced when decoding each new transaction commit.
+
+ Behaves just like
+ the pg_logical_slot_get_changes() function,
+ except that changes are not consumed; that is, they will be returned
+ again on future calls.
+
+ Advances the current confirmed position of a replication slot named
+ slot_name. The slot will not be moved backwards,
+ and it will not be moved beyond the current insert location. Returns
+ the name of the slot and the actual position that it was advanced to.
+ The updated slot position information is written out at the next
+ checkpoint if any advancing is done. So in the event of a crash, the
+ slot may return to an earlier position.
+
+
+ pg_replication_origin_create ( node_nametext )
+ → oid
+
+
+ Creates a replication origin with the given external
+ name, and returns the internal ID assigned to it.
+
+ Marks the current session as replaying from the given
+ origin, allowing replay progress to be tracked.
+ Can only be used if no origin is currently selected.
+ Use pg_replication_origin_session_reset to undo.
+
+ Returns the replay location for the replication origin selected in
+ the current session. The parameter flush
+ determines whether the corresponding local transaction will be
+ guaranteed to have been flushed to disk or not.
+
+
+ pg_replication_origin_xact_setup ( origin_lsnpg_lsn, origin_timestamptimestamp with time zone )
+ → void
+
+
+ Marks the current transaction as replaying a transaction that has
+ committed at the given LSN and timestamp. Can
+ only be called when a replication origin has been selected
+ using pg_replication_origin_session_setup.
+
+ Sets replication progress for the given node to the given
+ location. This is primarily useful for setting up the initial
+ location, or setting a new location after configuration changes and
+ similar. Be aware that careless use of this function can lead to
+ inconsistently replicated data.
+
+ Returns the replay location for the given replication origin. The
+ parameter flush determines whether the
+ corresponding local transaction will be guaranteed to have been
+ flushed to disk or not.
+
+ Emits a logical decoding message. This can be used to pass generic
+ messages to logical decoding plugins through
+ WAL. The transactional parameter specifies if
+ the message should be part of the current transaction, or if it should
+ be written immediately and decoded as soon as the logical decoder
+ reads the record. The prefix parameter is a
+ textual prefix that can be used by logical decoding plugins to easily
+ recognize messages that are interesting for them.
+ The content parameter is the content of the
+ message, given either in text or binary form.
+
+ The functions shown in Table 9.96 calculate
+ the disk space usage of database objects, or assist in presentation
+ or understanding of usage results. bigint results
+ are measured in bytes. If an OID that does
+ not represent an existing object is passed to one of these
+ functions, NULL is returned.
+
Table 9.96. Database Object Size Functions
+ Function
+
+
+ Description
+
+
+ pg_column_size ( "any" )
+ → integer
+
+
+ Shows the number of bytes used to store any individual data value. If
+ applied directly to a table column value, this reflects any
+ compression that was done.
+
+
+ pg_column_compression ( "any" )
+ → text
+
+
+ Shows the compression algorithm that was used to compress
+ an individual variable-length value. Returns NULL
+ if the value is not compressed.
+
+
+ pg_database_size ( name )
+ → bigint
+
+
+ pg_database_size ( oid )
+ → bigint
+
+
+ Computes the total disk space used by the database with the specified
+ name or OID. To use this function, you must
+ have CONNECT privilege on the specified database
+ (which is granted by default) or have privileges of
+ the pg_read_all_stats role.
+
+
+ pg_indexes_size ( regclass )
+ → bigint
+
+
+ Computes the total disk space used by indexes attached to the
+ specified table.
+
+ Computes the disk space used by one “fork” of the
+ specified relation. (Note that for most purposes it is more
+ convenient to use the higher-level
+ functions pg_total_relation_size
+ or pg_table_size, which sum the sizes of all
+ forks.) With one argument, this returns the size of the main data
+ fork of the relation. The second argument can be provided to specify
+ which fork to examine:
+
+ main returns the size of the main
+ data fork of the relation.
+
+ fsm returns the size of the Free Space Map
+ (see Section 73.3) associated with the relation.
+
+ vm returns the size of the Visibility Map
+ (see Section 73.4) associated with the relation.
+
+ init returns the size of the initialization
+ fork, if any, associated with the relation.
+
+
+
+ pg_size_bytes ( text )
+ → bigint
+
+
+ Converts a size in human-readable format (as returned
+ by pg_size_pretty) into bytes. Valid units are
+ bytes, B, kB,
+ MB, GB, TB,
+ and PB.
+
+
+ pg_size_pretty ( bigint )
+ → text
+
+
+ pg_size_pretty ( numeric )
+ → text
+
+
+ Converts a size in bytes into a more easily human-readable format with
+ size units (bytes, kB, MB, GB, TB, or PB as appropriate). Note that the
+ units are powers of 2 rather than powers of 10, so 1kB is 1024 bytes,
+ 1MB is 10242 = 1048576 bytes, and so on.
+
+
+ pg_table_size ( regclass )
+ → bigint
+
+
+ Computes the disk space used by the specified table, excluding indexes
+ (but including its TOAST table if any, free space map, and visibility
+ map).
+
+
+ pg_tablespace_size ( name )
+ → bigint
+
+
+ pg_tablespace_size ( oid )
+ → bigint
+
+
+ Computes the total disk space used in the tablespace with the
+ specified name or OID. To use this function, you must
+ have CREATE privilege on the specified tablespace
+ or have privileges of the pg_read_all_stats role,
+ unless it is the default tablespace for the current database.
+
+ Computes the total disk space used by the specified table, including
+ all indexes and TOAST data. The result is
+ equivalent to pg_table_size
+ +pg_indexes_size.
+
+ The functions above that operate on tables or indexes accept a
+ regclass argument, which is simply the OID of the table or index
+ in the pg_class system catalog. You do not have to look up
+ the OID by hand, however, since the regclass data type's input
+ converter will do the work for you. See Section 8.19
+ for details.
+
+ The functions shown in Table 9.97 assist
+ in identifying the specific disk files associated with database objects.
+
Table 9.97. Database Object Location Functions
+ Function
+
+
+ Description
+
+
+ pg_relation_filenode ( relationregclass )
+ → oid
+
+
+ Returns the “filenode” number currently assigned to the
+ specified relation. The filenode is the base component of the file
+ name(s) used for the relation (see
+ Section 73.1 for more information).
+ For most relations the result is the same as
+ pg_class.relfilenode,
+ but for certain system catalogs relfilenode
+ is zero and this function must be used to get the correct value. The
+ function returns NULL if passed a relation that does not have storage,
+ such as a view.
+
+
+ pg_relation_filepath ( relationregclass )
+ → text
+
+
+ Returns the entire file path name (relative to the database cluster's
+ data directory, PGDATA) of the relation.
+
+ Returns a relation's OID given the tablespace OID and filenode it is
+ stored under. This is essentially the inverse mapping of
+ pg_relation_filepath. For a relation in the
+ database's default tablespace, the tablespace can be specified as zero.
+ Returns NULL if no relation in the current database
+ is associated with the given values.
+
+ Table 9.98 lists functions used to manage
+ collations.
+
Table 9.98. Collation Management Functions
+ Function
+
+
+ Description
+
+
+ pg_collation_actual_version ( oid )
+ → text
+
+
+ Returns the actual version of the collation object as it is currently
+ installed in the operating system. If this is different from the
+ value in
+ pg_collation.collversion,
+ then objects depending on the collation might need to be rebuilt. See
+ also ALTER COLLATION.
+
+
+ pg_database_collation_actual_version ( oid )
+ → text
+
+
+ Returns the actual version of the database's collation as it is currently
+ installed in the operating system. If this is different from the
+ value in
+ pg_database.datcollversion,
+ then objects depending on the collation might need to be rebuilt. See
+ also ALTER DATABASE.
+
+ Adds collations to the system
+ catalog pg_collation based on all the locales
+ it finds in the operating system. This is
+ what initdb uses; see
+ Section 24.2.2 for more details. If additional
+ locales are installed into the operating system later on, this
+ function can be run again to add collations for the new locales.
+ Locales that match existing entries
+ in pg_collation will be skipped. (But
+ collation objects based on locales that are no longer present in the
+ operating system are not removed by this function.)
+ The schema parameter would typically
+ be pg_catalog, but that is not a requirement; the
+ collations could be installed into some other schema as well. The
+ function returns the number of new collation objects it created.
+ Use of this function is restricted to superusers.
+
+ Table 9.99 lists functions that provide
+ information about the structure of partitioned tables.
+
+ Lists the tables or indexes in the partition tree of the
+ given partitioned table or partitioned index, with one row for each
+ partition. Information provided includes the OID of the partition,
+ the OID of its immediate parent, a boolean value telling if the
+ partition is a leaf, and an integer telling its level in the hierarchy.
+ The level value is 0 for the input table or index, 1 for its
+ immediate child partitions, 2 for their partitions, and so on.
+ Returns no rows if the relation does not exist or is not a partition
+ or partitioned table.
+
+ Lists the ancestor relations of the given partition,
+ including the relation itself. Returns no rows if the relation
+ does not exist or is not a partition or partitioned table.
+
+
+ pg_partition_root ( regclass )
+ → regclass
+
+
+ Returns the top-most parent of the partition tree to which the given
+ relation belongs. Returns NULL if the relation
+ does not exist or is not a partition or partitioned table.
+
+ For example, to check the total size of the data contained in a
+ partitioned table measurement, one could use the
+ following query:
+
+SELECT pg_size_pretty(sum(pg_relation_size(relid))) AS total_size
+ FROM pg_partition_tree('measurement');
+
+ Table 9.100 shows the functions
+ available for index maintenance tasks. (Note that these maintenance
+ tasks are normally done automatically by autovacuum; use of these
+ functions is only required in special cases.)
+ These functions cannot be executed during recovery.
+ Use of these functions is restricted to superusers and the owner
+ of the given index.
+
+ Scans the specified BRIN index to find page ranges in the base table
+ that are not currently summarized by the index; for any such range it
+ creates a new summary index tuple by scanning those table pages.
+ Returns the number of new page range summaries that were inserted
+ into the index.
+
+ Summarizes the page range covering the given block, if not already
+ summarized. This is
+ like brin_summarize_new_values except that it
+ only processes the page range that covers the given table block number.
+
+ Cleans up the “pending” list of the specified GIN index
+ by moving entries in it, in bulk, to the main GIN data structure.
+ Returns the number of pages removed from the pending list.
+ If the argument is a GIN index built with
+ the fastupdate option disabled, no cleanup happens
+ and the result is zero, because the index doesn't have a pending list.
+ See Section 70.4.1 and Section 70.5
+ for details about the pending list and fastupdate
+ option.
+
+ The functions shown in Table 9.101 provide native access to
+ files on the machine hosting the server. Only files within the
+ database cluster directory and the log_directory can be
+ accessed, unless the user is a superuser or is granted the role
+ pg_read_server_files. Use a relative path for files in
+ the cluster directory, and a path matching the log_directory
+ configuration setting for log files.
+
+ Note that granting users the EXECUTE privilege on
+ pg_read_file(), or related functions, allows them the
+ ability to read any file on the server that the database server process can
+ read; these functions bypass all in-database privilege checks. This means
+ that, for example, a user with such access is able to read the contents of
+ the pg_authid table where authentication
+ information is stored, as well as read any table data in the database.
+ Therefore, granting access to these functions should be carefully
+ considered.
+
+ When granting privilege on these functions, note that the table entries
+ showing optional parameters are mostly implemented as several physical
+ functions with different parameter lists. Privilege must be granted
+ separately on each such function, if it is to be
+ used. psql's \df command
+ can be useful to check what the actual function signatures are.
+
+ Some of these functions take an optional missing_ok
+ parameter, which specifies the behavior when the file or directory does
+ not exist. If true, the function
+ returns NULL or an empty result set, as appropriate.
+ If false, an error is raised. (Failure conditions
+ other than “file not found” are reported as errors in any
+ case.) The default is false.
+
+ Returns the names of all files (and directories and other special
+ files) in the specified
+ directory. The include_dot_dirs parameter
+ indicates whether “.” and “..” are to be
+ included in the result set; the default is to exclude them. Including
+ them can be useful when missing_ok
+ is true, to distinguish an empty directory from a
+ non-existent directory.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ pg_ls_logdir ()
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the server's log directory. Filenames beginning with
+ a dot, directories, and other special files are excluded.
+
+
+ This function is restricted to superusers and roles with privileges of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+
+ pg_ls_waldir ()
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the server's write-ahead log (WAL) directory.
+ Filenames beginning with a dot, directories, and other special files
+ are excluded.
+
+
+ This function is restricted to superusers and roles with privileges of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+
+ pg_ls_logicalmapdir ()
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the server's pg_logical/mappings
+ directory. Filenames beginning with a dot, directories, and other
+ special files are excluded.
+
+
+ This function is restricted to superusers and members of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+
+ pg_ls_logicalsnapdir ()
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the server's pg_logical/snapshots
+ directory. Filenames beginning with a dot, directories, and other
+ special files are excluded.
+
+
+ This function is restricted to superusers and members of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+
+ pg_ls_replslotdir ( slot_nametext )
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the server's pg_replslot/slot_name
+ directory, where slot_name is the name of the
+ replication slot provided as input of the function. Filenames beginning
+ with a dot, directories, and other special files are excluded.
+
+
+ This function is restricted to superusers and members of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+
+ pg_ls_archive_statusdir ()
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the server's WAL archive status directory
+ (pg_wal/archive_status). Filenames beginning
+ with a dot, directories, and other special files are excluded.
+
+
+ This function is restricted to superusers and members of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+
+
+ pg_ls_tmpdir ( [tablespaceoid] )
+ → setof record
+ ( nametext,
+ sizebigint,
+ modificationtimestamp with time zone )
+
+
+ Returns the name, size, and last modification time (mtime) of each
+ ordinary file in the temporary file directory for the
+ specified tablespace.
+ If tablespace is not provided,
+ the pg_default tablespace is examined. Filenames
+ beginning with a dot, directories, and other special files are
+ excluded.
+
+
+ This function is restricted to superusers and members of
+ the pg_monitor role by default, but other users can
+ be granted EXECUTE to run the function.
+
+ Returns all or part of a text file, starting at the
+ given byte offset, returning at
+ most length bytes (less if the end of file is
+ reached first). If offset is negative, it is
+ relative to the end of the file. If offset
+ and length are omitted, the entire file is
+ returned. The bytes read from the file are interpreted as a string in
+ the database's encoding; an error is thrown if they are not valid in
+ that encoding.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+ Returns all or part of a file. This function is identical to
+ pg_read_file except that it can read arbitrary
+ binary data, returning the result as bytea
+ not text; accordingly, no encoding checks are performed.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+
+ In combination with the convert_from function,
+ this function can be used to read a text file in a specified encoding
+ and convert to the database's encoding:
+
+
+ pg_stat_file ( filenametext [, missing_okboolean] )
+ → record
+ ( sizebigint,
+ accesstimestamp with time zone,
+ modificationtimestamp with time zone,
+ changetimestamp with time zone,
+ creationtimestamp with time zone,
+ isdirboolean )
+
+
+ Returns a record containing the file's size, last access time stamp,
+ last modification time stamp, last file status change time stamp (Unix
+ platforms only), file creation time stamp (Windows only), and a flag
+ indicating if it is a directory.
+
+
+ This function is restricted to superusers by default, but other users
+ can be granted EXECUTE to run the function.
+
+ The functions shown in Table 9.102
+ manage advisory locks. For details about proper use of these functions,
+ see Section 13.3.5.
+
+ All these functions are intended to be used to lock application-defined
+ resources, which can be identified either by a single 64-bit key value or
+ two 32-bit key values (note that these two key spaces do not overlap).
+ If another session already holds a conflicting lock on the same resource
+ identifier, the functions will either wait until the resource becomes
+ available, or return a false result, as appropriate for
+ the function.
+ Locks can be either shared or exclusive: a shared lock does not conflict
+ with other shared locks on the same resource, only with exclusive locks.
+ Locks can be taken at session level (so that they are held until released
+ or the session ends) or at transaction level (so that they are held until
+ the current transaction ends; there is no provision for manual release).
+ Multiple session-level lock requests stack, so that if the same resource
+ identifier is locked three times there must then be three unlock requests
+ to release the resource in advance of session end.
+
+ Releases a previously-acquired exclusive session-level advisory lock.
+ Returns true if the lock is successfully released.
+ If the lock was not held, false is returned, and in
+ addition, an SQL warning will be reported by the server.
+
+
+ pg_advisory_unlock_all ()
+ → void
+
+
+ Releases all session-level advisory locks held by the current session.
+ (This function is implicitly invoked at session end, even if the
+ client disconnects ungracefully.)
+
+ Releases a previously-acquired shared session-level advisory lock.
+ Returns true if the lock is successfully released.
+ If the lock was not held, false is returned, and in
+ addition, an SQL warning will be reported by the server.
+
+ Obtains an exclusive session-level advisory lock if available.
+ This will either obtain the lock immediately and
+ return true, or return false
+ without waiting if the lock cannot be acquired immediately.
+
+ Obtains a shared session-level advisory lock if available.
+ This will either obtain the lock immediately and
+ return true, or return false
+ without waiting if the lock cannot be acquired immediately.
+
+ Obtains an exclusive transaction-level advisory lock if available.
+ This will either obtain the lock immediately and
+ return true, or return false
+ without waiting if the lock cannot be acquired immediately.
+
+ Obtains a shared transaction-level advisory lock if available.
+ This will either obtain the lock immediately and
+ return true, or return false
+ without waiting if the lock cannot be acquired immediately.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-aggregate.html b/pgsql/doc/postgresql/html/functions-aggregate.html
new file mode 100644
index 0000000000000000000000000000000000000000..40f265ddbe67eb5effccfecf79fdafaaaac37ba4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-aggregate.html
@@ -0,0 +1,853 @@
+
+9.21. Aggregate Functions
+ Aggregate functions compute a single result
+ from a set of input values. The built-in general-purpose aggregate
+ functions are listed in Table 9.59
+ while statistical aggregates are in Table 9.60.
+ The built-in within-group ordered-set aggregate functions
+ are listed in Table 9.61
+ while the built-in within-group hypothetical-set ones are in Table 9.62. Grouping operations,
+ which are closely related to aggregate functions, are listed in
+ Table 9.63.
+ The special syntax considerations for aggregate
+ functions are explained in Section 4.2.7.
+ Consult Section 2.7 for additional introductory
+ information.
+
+ Aggregate functions that support Partial Mode
+ are eligible to participate in various optimizations, such as parallel
+ aggregation.
+
Table 9.59. General-Purpose Aggregate Functions
+ Function
+
+
+ Description
+
Partial Mode
+
+ any_value ( anyelement )
+ → same as input type
+
+
+ Returns an arbitrary value from the non-null input values.
+
Yes
+
+ array_agg ( anynonarray )
+ → anyarray
+
+
+ Collects all the input values, including nulls, into an array.
+
Yes
+ array_agg ( anyarray )
+ → anyarray
+
+
+ Concatenates all the input arrays into an array of one higher
+ dimension. (The inputs must all have the same dimensionality, and
+ cannot be empty or null.)
+
Yes
+
+
+ avg ( smallint )
+ → numeric
+
+
+ avg ( integer )
+ → numeric
+
+
+ avg ( bigint )
+ → numeric
+
+
+ avg ( numeric )
+ → numeric
+
+
+ avg ( real )
+ → double precision
+
+
+ avg ( double precision )
+ → double precision
+
+
+ avg ( interval )
+ → interval
+
+
+ Computes the average (arithmetic mean) of all the non-null input
+ values.
+
Yes
+
+ bit_and ( smallint )
+ → smallint
+
+
+ bit_and ( integer )
+ → integer
+
+
+ bit_and ( bigint )
+ → bigint
+
+
+ bit_and ( bit )
+ → bit
+
+
+ Computes the bitwise AND of all non-null input values.
+
Yes
+
+ bit_or ( smallint )
+ → smallint
+
+
+ bit_or ( integer )
+ → integer
+
+
+ bit_or ( bigint )
+ → bigint
+
+
+ bit_or ( bit )
+ → bit
+
+
+ Computes the bitwise OR of all non-null input values.
+
Yes
+
+ bit_xor ( smallint )
+ → smallint
+
+
+ bit_xor ( integer )
+ → integer
+
+
+ bit_xor ( bigint )
+ → bigint
+
+
+ bit_xor ( bit )
+ → bit
+
+
+ Computes the bitwise exclusive OR of all non-null input values.
+ Can be useful as a checksum for an unordered set of values.
+
Yes
+
+ bool_and ( boolean )
+ → boolean
+
+
+ Returns true if all non-null input values are true, otherwise false.
+
Yes
+
+ bool_or ( boolean )
+ → boolean
+
+
+ Returns true if any non-null input value is true, otherwise false.
+
Yes
+
+ count ( * )
+ → bigint
+
+
+ Computes the number of input rows.
+
Yes
+ count ( "any" )
+ → bigint
+
+
+ Computes the number of input rows in which the input value is not
+ null.
+
Yes
+
+ every ( boolean )
+ → boolean
+
+
+ This is the SQL standard's equivalent to bool_and.
+
Yes
+
+ json_agg ( anyelement )
+ → json
+
+
+
+ jsonb_agg ( anyelement )
+ → jsonb
+
+
+ Collects all the input values, including nulls, into a JSON array.
+ Values are converted to JSON as per to_json
+ or to_jsonb.
+
+ Collects all the key/value pairs into a JSON object. Key arguments
+ are coerced to text; value arguments are converted as per
+ to_json or to_jsonb.
+ Values can be null, but keys cannot.
+
+ Collects all the key/value pairs into a JSON object. Key arguments
+ are coerced to text; value arguments are converted as per
+ to_json or to_jsonb.
+ The key can not be null. If the
+ value is null then the entry is skipped,
+
+ Collects all the key/value pairs into a JSON object. Key arguments
+ are coerced to text; value arguments are converted as per
+ to_json or to_jsonb.
+ Values can be null, but keys cannot.
+ If there is a duplicate key an error is thrown.
+
+ Behaves in the same way as json_array
+ but as an aggregate function so it only takes one
+ value_expression parameter.
+ If ABSENT ON NULL is specified, any NULL
+ values are omitted.
+ If ORDER BY is specified, the elements will
+ appear in the array in that order rather than in the input order.
+
+ Collects all the key/value pairs into a JSON object. Key arguments
+ are coerced to text; value arguments are converted as per
+ to_json or to_jsonb.
+ The key can not be null. If the
+ value is null then the entry is skipped.
+ If there is a duplicate key an error is thrown.
+
No
+
+ max ( see text )
+ → same as input type
+
+
+ Computes the maximum of the non-null input
+ values. Available for any numeric, string, date/time, or enum type,
+ as well as inet, interval,
+ money, oid, pg_lsn,
+ tid, xid8,
+ and arrays of any of these types.
+
Yes
+
+ min ( see text )
+ → same as input type
+
+
+ Computes the minimum of the non-null input
+ values. Available for any numeric, string, date/time, or enum type,
+ as well as inet, interval,
+ money, oid, pg_lsn,
+ tid, xid8,
+ and arrays of any of these types.
+
+ Concatenates the non-null input values into a string. Each value
+ after the first is preceded by the
+ corresponding delimiter (if it's not null).
+
Yes
+
+ sum ( smallint )
+ → bigint
+
+
+ sum ( integer )
+ → bigint
+
+
+ sum ( bigint )
+ → numeric
+
+
+ sum ( numeric )
+ → numeric
+
+
+ sum ( real )
+ → real
+
+
+ sum ( double precision )
+ → double precision
+
+
+ sum ( interval )
+ → interval
+
+
+ sum ( money )
+ → money
+
+
+ Computes the sum of the non-null input values.
+
Yes
+
+ xmlagg ( xml )
+ → xml
+
+
+ Concatenates the non-null XML input values (see
+ Section 9.15.1.7).
+
No
+ It should be noted that except for count,
+ these functions return a null value when no rows are selected. In
+ particular, sum of no rows returns null, not
+ zero as one might expect, and array_agg
+ returns null rather than an empty array when there are no input
+ rows. The coalesce function can be used to
+ substitute zero or an empty array for null when necessary.
+
+ The aggregate functions array_agg,
+ json_agg, jsonb_agg,
+ json_agg_strict, jsonb_agg_strict,
+ json_object_agg, jsonb_object_agg,
+ json_object_agg_strict, jsonb_object_agg_strict,
+ json_object_agg_unique, jsonb_object_agg_unique,
+ json_object_agg_unique_strict,
+ jsonb_object_agg_unique_strict,
+ string_agg,
+ and xmlagg, as well as similar user-defined
+ aggregate functions, produce meaningfully different result values
+ depending on the order of the input values. This ordering is
+ unspecified by default, but can be controlled by writing an
+ ORDER BY clause within the aggregate call, as shown in
+ Section 4.2.7.
+ Alternatively, supplying the input values from a sorted subquery
+ will usually work. For example:
+
+
+SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;
+
+
+ Beware that this approach can fail if the outer query level contains
+ additional processing, such as a join, because that might cause the
+ subquery's output to be reordered before the aggregate is computed.
+
Note
+ The boolean aggregates bool_and and
+ bool_or correspond to the standard SQL aggregates
+ every and any or
+ some.
+ PostgreSQL
+ supports every, but not any
+ or some, because there is an ambiguity built into
+ the standard syntax:
+
+SELECT b1 = ANY((SELECT b2 FROM t2 ...)) FROM t1 ...;
+
+ Here ANY can be considered either as introducing
+ a subquery, or as being an aggregate function, if the subquery
+ returns one row with a Boolean value.
+ Thus the standard name cannot be given to these aggregates.
+
Note
+ Users accustomed to working with other SQL database management
+ systems might be disappointed by the performance of the
+ count aggregate when it is applied to the
+ entire table. A query like:
+
+SELECT count(*) FROM sometable;
+
+ will require effort proportional to the size of the table:
+ PostgreSQL will need to scan either the
+ entire table or the entirety of an index that includes all rows in
+ the table.
+
+ Table 9.60 shows
+ aggregate functions typically used in statistical analysis.
+ (These are separated out merely to avoid cluttering the listing
+ of more-commonly-used aggregates.) Functions shown as
+ accepting numeric_type are available for all
+ the types smallint, integer,
+ bigint, numeric, real,
+ and double precision.
+ Where the description mentions
+ N, it means the
+ number of input rows for which all the input expressions are non-null.
+ In all cases, null is returned if the computation is meaningless,
+ for example when N is zero.
+
+ Computes the “sum of squares” of the dependent
+ variable,
+ sum(Y^2) - sum(Y)^2/N.
+
Yes
+
+
+ stddev ( numeric_type )
+ → double precision
+ for real or double precision,
+ otherwise numeric
+
+
+ This is a historical alias for stddev_samp.
+
Yes
+
+
+ stddev_pop ( numeric_type )
+ → double precision
+ for real or double precision,
+ otherwise numeric
+
+
+ Computes the population standard deviation of the input values.
+
Yes
+
+
+ stddev_samp ( numeric_type )
+ → double precision
+ for real or double precision,
+ otherwise numeric
+
+
+ Computes the sample standard deviation of the input values.
+
Yes
+
+ variance ( numeric_type )
+ → double precision
+ for real or double precision,
+ otherwise numeric
+
+
+ This is a historical alias for var_samp.
+
Yes
+
+
+ var_pop ( numeric_type )
+ → double precision
+ for real or double precision,
+ otherwise numeric
+
+
+ Computes the population variance of the input values (square of the
+ population standard deviation).
+
Yes
+
+
+ var_samp ( numeric_type )
+ → double precision
+ for real or double precision,
+ otherwise numeric
+
+
+ Computes the sample variance of the input values (square of the sample
+ standard deviation).
+
Yes
+ Table 9.61 shows some
+ aggregate functions that use the ordered-set aggregate
+ syntax. These functions are sometimes referred to as “inverse
+ distribution” functions. Their aggregated input is introduced by
+ ORDER BY, and they may also take a direct
+ argument that is not aggregated, but is computed only once.
+ All these functions ignore null values in their aggregated input.
+ For those that take a fraction parameter, the
+ fraction value must be between 0 and 1; an error is thrown if not.
+ However, a null fraction value simply produces a
+ null result.
+
Table 9.61. Ordered-Set Aggregate Functions
+ Function
+
+
+ Description
+
Partial Mode
+
+ mode () WITHIN GROUP ( ORDER BYanyelement )
+ → anyelement
+
+
+ Computes the mode, the most frequent
+ value of the aggregated argument (arbitrarily choosing the first one
+ if there are multiple equally-frequent values). The aggregated
+ argument must be of a sortable type.
+
No
+
+ percentile_cont ( fractiondouble precision ) WITHIN GROUP ( ORDER BYdouble precision )
+ → double precision
+
+
+ percentile_cont ( fractiondouble precision ) WITHIN GROUP ( ORDER BYinterval )
+ → interval
+
+
+ Computes the continuous percentile, a value
+ corresponding to the specified fraction
+ within the ordered set of aggregated argument values. This will
+ interpolate between adjacent input items if needed.
+
No
+ percentile_cont ( fractionsdouble precision[] ) WITHIN GROUP ( ORDER BYdouble precision )
+ → double precision[]
+
+
+ percentile_cont ( fractionsdouble precision[] ) WITHIN GROUP ( ORDER BYinterval )
+ → interval[]
+
+
+ Computes multiple continuous percentiles. The result is an array of
+ the same dimensions as the fractions
+ parameter, with each non-null element replaced by the (possibly
+ interpolated) value corresponding to that percentile.
+
No
+
+ percentile_disc ( fractiondouble precision ) WITHIN GROUP ( ORDER BYanyelement )
+ → anyelement
+
+
+ Computes the discrete percentile, the first
+ value within the ordered set of aggregated argument values whose
+ position in the ordering equals or exceeds the
+ specified fraction. The aggregated
+ argument must be of a sortable type.
+
No
+ percentile_disc ( fractionsdouble precision[] ) WITHIN GROUP ( ORDER BYanyelement )
+ → anyarray
+
+
+ Computes multiple discrete percentiles. The result is an array of the
+ same dimensions as the fractions parameter,
+ with each non-null element replaced by the input value corresponding
+ to that percentile.
+ The aggregated argument must be of a sortable type.
+
No
+ Each of the “hypothetical-set” aggregates listed in
+ Table 9.62 is associated with a
+ window function of the same name defined in
+ Section 9.22. In each case, the aggregate's result
+ is the value that the associated window function would have
+ returned for the “hypothetical” row constructed from
+ args, if such a row had been added to the sorted
+ group of rows represented by the sorted_args.
+ For each of these functions, the list of direct arguments
+ given in args must match the number and types of
+ the aggregated arguments given in sorted_args.
+ Unlike most built-in aggregates, these aggregates are not strict, that is
+ they do not drop input rows containing nulls. Null values sort according
+ to the rule specified in the ORDER BY clause.
+
Table 9.62. Hypothetical-Set Aggregate Functions
+ Function
+
+
+ Description
+
Partial Mode
+
+ rank ( args ) WITHIN GROUP ( ORDER BYsorted_args )
+ → bigint
+
+
+ Computes the rank of the hypothetical row, with gaps; that is, the row
+ number of the first row in its peer group.
+
No
+
+ dense_rank ( args ) WITHIN GROUP ( ORDER BYsorted_args )
+ → bigint
+
+
+ Computes the rank of the hypothetical row, without gaps; this function
+ effectively counts peer groups.
+
No
+
+ percent_rank ( args ) WITHIN GROUP ( ORDER BYsorted_args )
+ → double precision
+
+
+ Computes the relative rank of the hypothetical row, that is
+ (rank - 1) / (total rows - 1).
+ The value thus ranges from 0 to 1 inclusive.
+
No
+
+ cume_dist ( args ) WITHIN GROUP ( ORDER BYsorted_args )
+ → double precision
+
+
+ Computes the cumulative distribution, that is (number of rows
+ preceding or peers with hypothetical row) / (total rows). The value
+ thus ranges from 1/N to 1.
+
+ Returns a bit mask indicating which GROUP BY
+ expressions are not included in the current grouping set.
+ Bits are assigned with the rightmost argument corresponding to the
+ least-significant bit; each bit is 0 if the corresponding expression
+ is included in the grouping criteria of the grouping set generating
+ the current result row, and 1 if it is not included.
+
+ The grouping operations shown in
+ Table 9.63 are used in conjunction with
+ grouping sets (see Section 7.2.4) to distinguish
+ result rows. The arguments to the GROUPING function
+ are not actually evaluated, but they must exactly match expressions given
+ in the GROUP BY clause of the associated query level.
+ For example:
+
+=>SELECT * FROM items_sold;
+ make | model | sales
+-------+-------+-------
+ Foo | GT | 10
+ Foo | Tour | 20
+ Bar | City | 15
+ Bar | Sport | 5
+(4 rows)
+
+=>SELECT make, model, GROUPING(make,model), sum(sales) FROM items_sold GROUP BY ROLLUP(make,model);
+ make | model | grouping | sum
+-------+-------+----------+-----
+ Foo | GT | 0 | 10
+ Foo | Tour | 0 | 20
+ Bar | City | 0 | 15
+ Bar | Sport | 0 | 5
+ Foo | | 1 | 30
+ Bar | | 1 | 20
+ | | 3 | 50
+(7 rows)
+
+ Here, the grouping value 0 in the
+ first four rows shows that those have been grouped normally, over both the
+ grouping columns. The value 1 indicates
+ that model was not grouped by in the next-to-last two
+ rows, and the value 3 indicates that
+ neither make nor model was grouped
+ by in the last row (which therefore is an aggregate over all the input
+ rows).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-array.html b/pgsql/doc/postgresql/html/functions-array.html
new file mode 100644
index 0000000000000000000000000000000000000000..bec1ffefcfdc4ae5f3310e3785b6f6ba6711efe4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-array.html
@@ -0,0 +1,415 @@
+
+9.19. Array Functions and Operators
+ Table 9.53 shows the specialized operators
+ available for array types.
+ In addition to those, the usual comparison operators shown in Table 9.1 are available for
+ arrays. The comparison operators compare the array contents
+ element-by-element, using the default B-tree comparison function for
+ the element data type, and sort based on the first difference.
+ In multidimensional arrays the elements are visited in row-major order
+ (last subscript varies most rapidly).
+ If the contents of two arrays are equal but the dimensionality is
+ different, the first difference in the dimensionality information
+ determines the sort order.
+
Table 9.53. Array Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ anyarray@>anyarray
+ → boolean
+
+
+ Does the first array contain the second, that is, does each element
+ appearing in the second array equal some element of the first array?
+ (Duplicates are not treated specially,
+ thus ARRAY[1] and ARRAY[1,1] are
+ each considered to contain the other.)
+
+
+ ARRAY[1,4,3] @> ARRAY[3,1,3]
+ → t
+
+ anyarray<@anyarray
+ → boolean
+
+
+ Is the first array contained by the second?
+
+
+ ARRAY[2,2,7] <@ ARRAY[1,7,4,2,6]
+ → t
+
+ anyarray&&anyarray
+ → boolean
+
+
+ Do the arrays overlap, that is, have any elements in common?
+
+ Concatenates the two arrays. Concatenating a null or empty array is a
+ no-op; otherwise the arrays must have the same number of dimensions
+ (as illustrated by the first example) or differ in number of
+ dimensions by one (as illustrated by the second).
+ If the arrays are not of identical element types, they will be coerced
+ to a common type (see Section 10.5).
+
+ Concatenates an element onto the end of an array (which must be
+ empty or one-dimensional).
+
+
+ ARRAY[4,5,6] || 7
+ → {4,5,6,7}
+
+ See Section 8.15 for more details about array operator
+ behavior. See Section 11.2 for more details about
+ which operators support indexed operations.
+
+ Table 9.54 shows the functions
+ available for use with array types. See Section 8.15
+ for more information and examples of the use of these functions.
+
+ Returns an array filled with copies of the given value, having
+ dimensions of the lengths specified by the second argument.
+ The optional third argument supplies lower-bound values for each
+ dimension (which default to all 1).
+
+ Returns the subscript of the first occurrence of the second argument
+ in the array, or NULL if it's not present.
+ If the third argument is given, the search begins at that subscript.
+ The array must be one-dimensional.
+ Comparisons are done using IS NOT DISTINCT FROM
+ semantics, so it is possible to search for NULL.
+
+ Returns an array of the subscripts of all occurrences of the second
+ argument in the array given as first argument.
+ The array must be one-dimensional.
+ Comparisons are done using IS NOT DISTINCT FROM
+ semantics, so it is possible to search for NULL.
+ NULL is returned only if the array
+ is NULL; if the value is not found in the array, an
+ empty array is returned.
+
+ Removes all elements equal to the given value from the array.
+ The array must be one-dimensional.
+ Comparisons are done using IS NOT DISTINCT FROM
+ semantics, so it is possible to remove NULLs.
+
+ Returns an array of n items randomly selected
+ from array. n may not
+ exceed the length of array's first dimension.
+ If array is multi-dimensional,
+ an “item” is a slice having a given first subscript.
+
+ Converts each array element to its text representation, and
+ concatenates those separated by
+ the delimiter string.
+ If null_string is given and is
+ not NULL, then NULL array
+ entries are represented by that string; otherwise, they are omitted.
+ See also string_to_array.
+
+ Expands multiple arrays (possibly of different data types) into a set of
+ rows. If the arrays are not all the same length then the shorter ones
+ are padded with NULLs. This form is only allowed
+ in a query's FROM clause; see Section 7.2.1.4.
+
+
+ select * from unnest(ARRAY[1,2], ARRAY['foo','bar','baz']) as x(a,b)
+ →
+
+ a | b
+---+-----
+ 1 | foo
+ 2 | bar
+ | baz
+
+
+ See also Section 9.21 about the aggregate
+ function array_agg for use with arrays.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-binarystring.html b/pgsql/doc/postgresql/html/functions-binarystring.html
new file mode 100644
index 0000000000000000000000000000000000000000..d701235380c6c05b48467a5440c53cb5b5849044
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-binarystring.html
@@ -0,0 +1,510 @@
+
+9.5. Binary String Functions and Operators
+ This section describes functions and operators for examining and
+ manipulating binary strings, that is values of type bytea.
+ Many of these are equivalent, in purpose and syntax, to the
+ text-string functions described in the previous section.
+
+ SQL defines some string functions that use
+ key words, rather than commas, to separate
+ arguments. Details are in
+ Table 9.11.
+ PostgreSQL also provides versions of these functions
+ that use the regular function invocation syntax
+ (see Table 9.12).
+
Table 9.11. SQL Binary String Functions and Operators
+ Replaces the substring of bytes that starts at
+ the start'th byte and extends
+ for count bytes
+ with newsubstring.
+ If count is omitted, it defaults to the length
+ of newsubstring.
+
+
+ overlay('\x1234567890'::bytea placing '\002\003'::bytea from 2 for 3)
+ → \x12020390
+
+
+ position ( substringbyteaINbytesbytea )
+ → integer
+
+
+ Returns first starting index of the specified
+ substring within
+ bytes, or zero if it's not present.
+
+
+ position('\x5678'::bytea in '\x1234567890'::bytea)
+ → 3
+
+ Extracts the substring of bytes starting at
+ the start'th byte if that is specified,
+ and stopping after count bytes if that is
+ specified. Provide at least one of start
+ and count.
+
+
+ substring('\x1234567890'::bytea from 3 for 2)
+ → \x5678
+
+ trim(both from '\x1234567890'::bytea, '\x9012'::bytea)
+ → \x345678
+
+ Additional binary string manipulation functions are available and
+ are listed in Table 9.12. Some
+ of them are used internally to implement the
+ SQL-standard string functions listed in Table 9.11.
+
Table 9.12. Other Binary String Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+
+ bit_count ( bytesbytea )
+ → bigint
+
+
+ Returns the number of bits set in the binary string (also known as
+ “popcount”).
+
+ Extracts the substring of bytes starting at
+ the start'th byte,
+ and extending for count bytes if that is
+ specified. (Same
+ as substring(bytes
+ from start
+ for count).)
+
+ Functions get_byte and set_byte
+ number the first byte of a binary string as byte 0.
+ Functions get_bit and set_bit
+ number bits from the right within each byte; for example bit 0 is the least
+ significant bit of the first byte, and bit 15 is the most significant bit
+ of the second byte.
+
+ For historical reasons, the function md5
+ returns a hex-encoded value of type text whereas the SHA-2
+ functions return type bytea. Use the functions
+ encode
+ and decode to
+ convert between the two. For example write encode(sha256('abc'),
+ 'hex') to get a hex-encoded text representation,
+ or decode(md5('abc'), 'hex') to get
+ a bytea value.
+
+
+
+ Functions for converting strings between different character sets
+ (encodings), and for representing arbitrary binary data in textual
+ form, are shown in
+ Table 9.13. For these
+ functions, an argument or result of type text is expressed
+ in the database's default encoding, while arguments or results of
+ type bytea are in an encoding named by another argument.
+
+ Converts a binary string representing text in
+ encoding src_encoding
+ to a binary string in encoding dest_encoding
+ (see Section 24.3.4 for
+ available conversions).
+
+ Converts a binary string representing text in
+ encoding src_encoding
+ to text in the database encoding
+ (see Section 24.3.4 for
+ available conversions).
+
+ Converts a text string (in the database encoding) to a
+ binary string encoded in encoding dest_encoding
+ (see Section 24.3.4 for
+ available conversions).
+
+ The base64 format is that
+ of RFC
+ 2045 Section 6.8. As per the RFC, encoded lines are
+ broken at 76 characters. However instead of the MIME CRLF
+ end-of-line marker, only a newline is used for end-of-line.
+ The decode function ignores carriage-return,
+ newline, space, and tab characters. Otherwise, an error is
+ raised when decode is supplied invalid
+ base64 data — including when trailing padding is incorrect.
+
+ The escape format converts zero bytes and
+ bytes with the high bit set into octal escape sequences
+ (\nnn), and it doubles
+ backslashes. Other byte values are represented literally.
+ The decode function will raise an error if a
+ backslash is not followed by either a second backslash or three
+ octal digits; it accepts other byte values unchanged.
+
+ The hex format represents each 4 bits of
+ data as one hexadecimal digit, 0
+ through f, writing the higher-order digit of
+ each byte first. The encode function outputs
+ the a-f hex digits in lower
+ case. Because the smallest unit of data is 8 bits, there are
+ always an even number of characters returned
+ by encode.
+ The decode function
+ accepts the a-f characters in
+ either upper or lower case. An error is raised
+ when decode is given invalid hex data
+ — including when given an odd number of characters.
+
+
+ See also the aggregate function string_agg in
+ Section 9.21 and the large object functions
+ in Section 35.4.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-bitstring.html b/pgsql/doc/postgresql/html/functions-bitstring.html
new file mode 100644
index 0000000000000000000000000000000000000000..88123814ec83cf9e98dec4a8ac923499953c836f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-bitstring.html
@@ -0,0 +1,235 @@
+
+9.6. Bit String Functions and Operators
+ This section describes functions and operators for examining and
+ manipulating bit strings, that is values of the types
+ bit and bit varying. (While only
+ type bit is mentioned in these tables, values of
+ type bit varying can be used interchangeably.)
+ Bit strings support the usual comparison operators shown in
+ Table 9.1, as well as the
+ operators shown in Table 9.14.
+
Table 9.14. Bit String Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ bit||bit
+ → bit
+
+
+ Concatenation
+
+
+ B'10001' || B'011'
+ → 10001011
+
+ bit&bit
+ → bit
+
+
+ Bitwise AND (inputs must be of equal length)
+
+
+ B'10001' & B'01101'
+ → 00001
+
+ bit|bit
+ → bit
+
+
+ Bitwise OR (inputs must be of equal length)
+
+
+ B'10001' | B'01101'
+ → 11101
+
+ bit#bit
+ → bit
+
+
+ Bitwise exclusive OR (inputs must be of equal length)
+
+
+ B'10001' # B'01101'
+ → 11100
+
+ ~bit
+ → bit
+
+
+ Bitwise NOT
+
+
+ ~ B'10001'
+ → 01110
+
+ bit<<integer
+ → bit
+
+
+ Bitwise shift left
+ (string length is preserved)
+
+
+ B'10001' << 3
+ → 01000
+
+ bit>>integer
+ → bit
+
+
+ Bitwise shift right
+ (string length is preserved)
+
+
+ B'10001' >> 2
+ → 00100
+
+ Some of the functions available for binary strings are also available
+ for bit strings, as shown in Table 9.15.
+
Table 9.15. Bit String Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ bit_count ( bit )
+ → bigint
+
+
+ Returns the number of bits set in the bit string (also known as
+ “popcount”).
+
+ Replaces the substring of bits that starts at
+ the start'th bit and extends
+ for count bits
+ with newsubstring.
+ If count is omitted, it defaults to the length
+ of newsubstring.
+
+
+ overlay(B'01010101010101010' placing B'11111' from 2 for 3)
+ → 0111110101010101010
+
+
+ position ( substringbitINbitsbit )
+ → integer
+
+
+ Returns first starting index of the specified substring
+ within bits, or zero if it's not present.
+
+ Extracts the substring of bits starting at
+ the start'th bit if that is specified,
+ and stopping after count bits if that is
+ specified. Provide at least one of start
+ and count.
+
+
+ substring(B'110010111111' from 3 for 2)
+ → 00
+
+
+ get_bit ( bitsbit,
+ ninteger )
+ → integer
+
+
+ Extracts n'th bit
+ from bit string; the first (leftmost) bit is bit 0.
+
+ In addition, it is possible to cast integral values to and from type
+ bit.
+ Casting an integer to bit(n) copies the rightmost
+ n bits. Casting an integer to a bit string width wider
+ than the integer itself will sign-extend on the left.
+ Some examples:
+
+ Note that casting to just “bit” means casting to
+ bit(1), and so will deliver only the least significant
+ bit of the integer.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-comparison.html b/pgsql/doc/postgresql/html/functions-comparison.html
new file mode 100644
index 0000000000000000000000000000000000000000..67ccfc7861328a2c9f159e9386768409149cb06b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-comparison.html
@@ -0,0 +1,400 @@
+
+9.2. Comparison Functions and Operators
+ The usual comparison operators are available, as shown in Table 9.1.
+
Table 9.1. Comparison Operators
Operator
Description
+ datatype<datatype
+ → boolean
+
Less than
+ datatype>datatype
+ → boolean
+
Greater than
+ datatype<=datatype
+ → boolean
+
Less than or equal to
+ datatype>=datatype
+ → boolean
+
Greater than or equal to
+ datatype=datatype
+ → boolean
+
Equal
+ datatype<>datatype
+ → boolean
+
Not equal
+ datatype!=datatype
+ → boolean
+
Not equal
Note
+ <> is the standard SQL notation for “not
+ equal”. != is an alias, which is converted
+ to <> at a very early stage of parsing.
+ Hence, it is not possible to implement !=
+ and <> operators that do different things.
+
+ These comparison operators are available for all built-in data types
+ that have a natural ordering, including numeric, string, and date/time
+ types. In addition, arrays, composite types, and ranges can be compared
+ if their component data types are comparable.
+
+ It is usually possible to compare values of related data
+ types as well; for example integer>
+ bigint will work. Some cases of this sort are implemented
+ directly by “cross-type” comparison operators, but if no
+ such operator is available, the parser will coerce the less-general type
+ to the more-general type and apply the latter's comparison operator.
+
+ As shown above, all comparison operators are binary operators that
+ return values of type boolean. Thus, expressions like
+ 1 < 2 < 3 are not valid (because there is
+ no < operator to compare a Boolean value with
+ 3). Use the BETWEEN predicates
+ shown below to perform range tests.
+
+ There are also some comparison predicates, as shown in Table 9.2. These behave much like
+ operators, but have special syntax mandated by the SQL standard.
+
+ Between, after sorting the two endpoint values.
+
+
+ 2 BETWEEN SYMMETRIC 3 AND 1
+ → t
+
+ datatypeNOT BETWEEN SYMMETRICdatatypeANDdatatype
+ → boolean
+
+
+ Not between, after sorting the two endpoint values.
+
+
+ 2 NOT BETWEEN SYMMETRIC 3 AND 1
+ → f
+
+ datatypeIS DISTINCT FROMdatatype
+ → boolean
+
+
+ Not equal, treating null as a comparable value.
+
+
+ 1 IS DISTINCT FROM NULL
+ → t (rather than NULL)
+
+
+ NULL IS DISTINCT FROM NULL
+ → f (rather than NULL)
+
+ datatypeIS NOT DISTINCT FROMdatatype
+ → boolean
+
+
+ Equal, treating null as a comparable value.
+
+
+ 1 IS NOT DISTINCT FROM NULL
+ → f (rather than NULL)
+
+
+ NULL IS NOT DISTINCT FROM NULL
+ → t (rather than NULL)
+
+ datatypeIS NULL
+ → boolean
+
+
+ Test whether value is null.
+
+
+ 1.5 IS NULL
+ → f
+
+ datatypeIS NOT NULL
+ → boolean
+
+
+ Test whether value is not null.
+
+
+ 'null' IS NOT NULL
+ → t
+
+ datatypeISNULL
+ → boolean
+
+
+ Test whether value is null (nonstandard syntax).
+
+ datatypeNOTNULL
+ → boolean
+
+
+ Test whether value is not null (nonstandard syntax).
+
+ booleanIS TRUE
+ → boolean
+
+
+ Test whether boolean expression yields true.
+
+
+ true IS TRUE
+ → t
+
+
+ NULL::boolean IS TRUE
+ → f (rather than NULL)
+
+ booleanIS NOT TRUE
+ → boolean
+
+
+ Test whether boolean expression yields false or unknown.
+
+
+ true IS NOT TRUE
+ → f
+
+
+ NULL::boolean IS NOT TRUE
+ → t (rather than NULL)
+
+ booleanIS FALSE
+ → boolean
+
+
+ Test whether boolean expression yields false.
+
+
+ true IS FALSE
+ → f
+
+
+ NULL::boolean IS FALSE
+ → f (rather than NULL)
+
+ booleanIS NOT FALSE
+ → boolean
+
+
+ Test whether boolean expression yields true or unknown.
+
+
+ true IS NOT FALSE
+ → t
+
+
+ NULL::boolean IS NOT FALSE
+ → t (rather than NULL)
+
+ booleanIS UNKNOWN
+ → boolean
+
+
+ Test whether boolean expression yields unknown.
+
+
+ true IS UNKNOWN
+ → f
+
+
+ NULL::boolean IS UNKNOWN
+ → t (rather than NULL)
+
+ booleanIS NOT UNKNOWN
+ → boolean
+
+
+ Test whether boolean expression yields true or false.
+
+
+ true IS NOT UNKNOWN
+ → t
+
+
+ NULL::boolean IS NOT UNKNOWN
+ → f (rather than NULL)
+
+
+
+ The BETWEEN predicate simplifies range tests:
+
+a BETWEEN x AND y
+
+ is equivalent to
+
+a >= x AND a <= y
+
+ Notice that BETWEEN treats the endpoint values as included
+ in the range.
+ BETWEEN SYMMETRIC is like BETWEEN
+ except there is no requirement that the argument to the left of
+ AND be less than or equal to the argument on the right.
+ If it is not, those two arguments are automatically swapped, so that
+ a nonempty range is always implied.
+
+ The various variants of BETWEEN are implemented in
+ terms of the ordinary comparison operators, and therefore will work for
+ any data type(s) that can be compared.
+
Note
+ The use of AND in the BETWEEN
+ syntax creates an ambiguity with the use of AND as a
+ logical operator. To resolve this, only a limited set of expression
+ types are allowed as the second argument of a BETWEEN
+ clause. If you need to write a more complex sub-expression
+ in BETWEEN, write parentheses around the
+ sub-expression.
+
+
+
+ Ordinary comparison operators yield null (signifying “unknown”),
+ not true or false, when either input is null. For example,
+ 7 = NULL yields null, as does 7 <> NULL. When
+ this behavior is not suitable, use the
+ IS [ NOT ] DISTINCT FROM predicates:
+
+a IS DISTINCT FROM b
+a IS NOT DISTINCT FROM b
+
+ For non-null inputs, IS DISTINCT FROM is
+ the same as the <> operator. However, if both
+ inputs are null it returns false, and if only one input is
+ null it returns true. Similarly, IS NOT DISTINCT
+ FROM is identical to = for non-null
+ inputs, but it returns true when both inputs are null, and false when only
+ one input is null. Thus, these predicates effectively act as though null
+ were a normal data value, rather than “unknown”.
+
+
+
+
+
+ To check whether a value is or is not null, use the predicates:
+
+expression IS NULL
+expression IS NOT NULL
+
+ or the equivalent, but nonstandard, predicates:
+
+expression ISNULL
+expression NOTNULL
+
+
+
+ Do not write
+ expression = NULL
+ because NULL is not “equal to”
+ NULL. (The null value represents an unknown value,
+ and it is not known whether two unknown values are equal.)
+
Tip
+ Some applications might expect that
+ expression = NULL
+ returns true if expression evaluates to
+ the null value. It is highly recommended that these applications
+ be modified to comply with the SQL standard. However, if that
+ cannot be done the transform_null_equals
+ configuration variable is available. If it is enabled,
+ PostgreSQL will convert x =
+ NULL clauses to x IS NULL.
+
+ If the expression is row-valued, then
+ IS NULL is true when the row expression itself is null
+ or when all the row's fields are null, while
+ IS NOT NULL is true when the row expression itself is non-null
+ and all the row's fields are non-null. Because of this behavior,
+ IS NULL and IS NOT NULL do not always return
+ inverse results for row-valued expressions; in particular, a row-valued
+ expression that contains both null and non-null fields will return false
+ for both tests. In some cases, it may be preferable to
+ write rowIS DISTINCT FROM NULL
+ or rowIS NOT DISTINCT FROM NULL,
+ which will simply check whether the overall row value is null without any
+ additional tests on the row fields.
+
+
+
+
+
+
+
+ Boolean values can also be tested using the predicates
+
+boolean_expression IS TRUE
+boolean_expression IS NOT TRUE
+boolean_expression IS FALSE
+boolean_expression IS NOT FALSE
+boolean_expression IS UNKNOWN
+boolean_expression IS NOT UNKNOWN
+
+ These will always return true or false, never a null value, even when the
+ operand is null.
+ A null input is treated as the logical value “unknown”.
+ Notice that IS UNKNOWN and IS NOT UNKNOWN are
+ effectively the same as IS NULL and
+ IS NOT NULL, respectively, except that the input
+ expression must be of Boolean type.
+
+ Some comparison-related functions are also available, as shown in Table 9.3.
+
Table 9.3. Comparison Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ num_nonnulls ( VARIADIC"any" )
+ → integer
+
+
+ Returns the number of non-null arguments.
+
+
+ num_nonnulls(1, NULL, 2)
+ → 2
+
+
+ num_nulls ( VARIADIC"any" )
+ → integer
+
+
+ Returns the number of null arguments.
+
+
+ num_nulls(1, NULL, 2)
+ → 1
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-comparisons.html b/pgsql/doc/postgresql/html/functions-comparisons.html
new file mode 100644
index 0000000000000000000000000000000000000000..5d94fd675b2e59b30ea8f55bd78b794b174582c0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-comparisons.html
@@ -0,0 +1,206 @@
+
+9.24. Row and Array Comparisons
+ This section describes several specialized constructs for making
+ multiple comparisons between groups of values. These forms are
+ syntactically related to the subquery forms of the previous section,
+ but do not involve subqueries.
+ The forms involving array subexpressions are
+ PostgreSQL extensions; the rest are
+ SQL-compliant.
+ All of the expression forms documented in this section return
+ Boolean (true/false) results.
+
+ The right-hand side is a parenthesized list
+ of expressions. The result is “true” if the left-hand expression's
+ result is equal to any of the right-hand expressions. This is a shorthand
+ notation for
+
+
+ Note that if the left-hand expression yields null, or if there are
+ no equal right-hand values and at least one right-hand expression yields
+ null, the result of the IN construct will be null, not false.
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
+ The right-hand side is a parenthesized list
+ of expressions. The result is “true” if the left-hand expression's
+ result is unequal to all of the right-hand expressions. This is a shorthand
+ notation for
+
+
+ Note that if the left-hand expression yields null, or if there are
+ no equal right-hand values and at least one right-hand expression yields
+ null, the result of the NOT IN construct will be null, not true
+ as one might naively expect.
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
Tip
+ x NOT IN y is equivalent to NOT (x IN y) in all
+ cases. However, null values are much more likely to trip up the novice when
+ working with NOT IN than when working with IN.
+ It is best to express your condition positively if possible.
+
+expressionoperator ANY (array expression)
+expressionoperator SOME (array expression)
+
+ The right-hand side is a parenthesized expression, which must yield an
+ array value.
+ The left-hand expression
+ is evaluated and compared to each element of the array using the
+ given operator, which must yield a Boolean
+ result.
+ The result of ANY is “true” if any true result is obtained.
+ The result is “false” if no true result is found (including the
+ case where the array has zero elements).
+
+ If the array expression yields a null array, the result of
+ ANY will be null. If the left-hand expression yields null,
+ the result of ANY is ordinarily null (though a non-strict
+ comparison operator could possibly yield a different result).
+ Also, if the right-hand array contains any null elements and no true
+ comparison result is obtained, the result of ANY
+ will be null, not false (again, assuming a strict comparison operator).
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
+ The right-hand side is a parenthesized expression, which must yield an
+ array value.
+ The left-hand expression
+ is evaluated and compared to each element of the array using the
+ given operator, which must yield a Boolean
+ result.
+ The result of ALL is “true” if all comparisons yield true
+ (including the case where the array has zero elements).
+ The result is “false” if any false result is found.
+
+ If the array expression yields a null array, the result of
+ ALL will be null. If the left-hand expression yields null,
+ the result of ALL is ordinarily null (though a non-strict
+ comparison operator could possibly yield a different result).
+ Also, if the right-hand array contains any null elements and no false
+ comparison result is obtained, the result of ALL
+ will be null, not true (again, assuming a strict comparison operator).
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
+ Each side is a row constructor,
+ as described in Section 4.2.13.
+ The two row constructors must have the same number of fields.
+ The given operator is applied to each pair
+ of corresponding fields. (Since the fields could be of different
+ types, this means that a different specific operator could be selected
+ for each pair.)
+ All the selected operators must be members of some B-tree operator
+ class, or be the negator of an = member of a B-tree
+ operator class, meaning that row constructor comparison is only
+ possible when the operator is
+ =,
+ <>,
+ <,
+ <=,
+ >, or
+ >=,
+ or has semantics similar to one of these.
+
+ The = and <> cases work slightly differently
+ from the others. Two rows are considered
+ equal if all their corresponding members are non-null and equal; the rows
+ are unequal if any corresponding members are non-null and unequal;
+ otherwise the result of the row comparison is unknown (null).
+
+ For the <, <=, > and
+ >= cases, the row elements are compared left-to-right,
+ stopping as soon as an unequal or null pair of elements is found.
+ If either of this pair of elements is null, the result of the
+ row comparison is unknown (null); otherwise comparison of this pair
+ of elements determines the result. For example,
+ ROW(1,2,NULL) < ROW(1,3,0)
+ yields true, not null, because the third pair of elements are not
+ considered.
+
+row_constructor IS DISTINCT FROM row_constructor
+
+ This construct is similar to a <> row comparison,
+ but it does not yield null for null inputs. Instead, any null value is
+ considered unequal to (distinct from) any non-null value, and any two
+ nulls are considered equal (not distinct). Thus the result will
+ either be true or false, never null.
+
+row_constructor IS NOT DISTINCT FROM row_constructor
+
+ This construct is similar to a = row comparison,
+ but it does not yield null for null inputs. Instead, any null value is
+ considered unequal to (distinct from) any non-null value, and any two
+ nulls are considered equal (not distinct). Thus the result will always
+ be either true or false, never null.
+
+ The SQL specification requires row-wise comparison to return NULL if the
+ result depends on comparing two NULL values or a NULL and a non-NULL.
+ PostgreSQL does this only when comparing the
+ results of two row constructors (as in
+ Section 9.24.5) or comparing a row constructor
+ to the output of a subquery (as in Section 9.23).
+ In other contexts where two composite-type values are compared, two
+ NULL field values are considered equal, and a NULL is considered larger
+ than a non-NULL. This is necessary in order to have consistent sorting
+ and indexing behavior for composite types.
+
+ Each side is evaluated and they are compared row-wise. Composite type
+ comparisons are allowed when the operator is
+ =,
+ <>,
+ <,
+ <=,
+ > or
+ >=,
+ or has semantics similar to one of these. (To be specific, an operator
+ can be a row comparison operator if it is a member of a B-tree operator
+ class, or is the negator of the = member of a B-tree operator
+ class.) The default behavior of the above operators is the same as for
+ IS [ NOT ] DISTINCT FROM for row constructors (see
+ Section 9.24.5).
+
+ To support matching of rows which include elements without a default
+ B-tree operator class, the following operators are defined for composite
+ type comparison:
+ *=,
+ *<>,
+ *<,
+ *<=,
+ *>, and
+ *>=.
+ These operators compare the internal binary representation of the two
+ rows. Two rows might have a different binary representation even
+ though comparisons of the two rows with the equality operator is true.
+ The ordering of rows under these comparison operators is deterministic
+ but not otherwise meaningful. These operators are used internally
+ for materialized views and might be useful for other specialized
+ purposes such as replication and B-Tree deduplication (see Section 67.4.3). They are not intended to be
+ generally useful for writing queries, though.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-conditional.html b/pgsql/doc/postgresql/html/functions-conditional.html
new file mode 100644
index 0000000000000000000000000000000000000000..f7ff9aefe4410ca9f3777bb57c49459184e1b41c
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-conditional.html
@@ -0,0 +1,185 @@
+
+9.18. Conditional Expressions
+ This section describes the SQL-compliant conditional expressions
+ available in PostgreSQL.
+
Tip
+ If your needs go beyond the capabilities of these conditional
+ expressions, you might want to consider writing a server-side function
+ in a more expressive programming language.
+
Note
+ Although COALESCE, GREATEST, and
+ LEAST are syntactically similar to functions, they are
+ not ordinary functions, and thus cannot be used with explicit
+ VARIADIC array arguments.
+
+ The SQL CASE expression is a
+ generic conditional expression, similar to if/else statements in
+ other programming languages:
+
+
+CASE WHEN condition THEN result
+ [WHEN ...]
+ [ELSE result]
+END
+
+
+ CASE clauses can be used wherever
+ an expression is valid. Each condition is an
+ expression that returns a boolean result. If the condition's
+ result is true, the value of the CASE expression is the
+ result that follows the condition, and the
+ remainder of the CASE expression is not processed. If the
+ condition's result is not true, any subsequent WHEN clauses
+ are examined in the same manner. If no WHEN
+ condition yields true, the value of the
+ CASE expression is the result of the
+ ELSE clause. If the ELSE clause is
+ omitted and no condition is true, the result is null.
+
+ An example:
+
+SELECT * FROM test;
+
+ a
+---
+ 1
+ 2
+ 3
+
+
+SELECT a,
+ CASE WHEN a=1 THEN 'one'
+ WHEN a=2 THEN 'two'
+ ELSE 'other'
+ END
+ FROM test;
+
+ a | case
+---+-------
+ 1 | one
+ 2 | two
+ 3 | other
+
+
+ The data types of all the result
+ expressions must be convertible to a single output type.
+ See Section 10.5 for more details.
+
+ There is a “simple” form of CASE expression
+ that is a variant of the general form above:
+
+
+CASE expression
+ WHEN value THEN result
+ [WHEN ...]
+ [ELSE result]
+END
+
+
+ The first
+ expression is computed, then compared to
+ each of the value expressions in the
+ WHEN clauses until one is found that is equal to it. If
+ no match is found, the result of the
+ ELSE clause (or a null value) is returned. This is similar
+ to the switch statement in C.
+
+ The example above can be written using the simple
+ CASE syntax:
+
+SELECT a,
+ CASE a WHEN 1 THEN 'one'
+ WHEN 2 THEN 'two'
+ ELSE 'other'
+ END
+ FROM test;
+
+ a | case
+---+-------
+ 1 | one
+ 2 | two
+ 3 | other
+
+
+ A CASE expression does not evaluate any subexpressions
+ that are not needed to determine the result. For example, this is a
+ possible way of avoiding a division-by-zero failure:
+
+SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
+
+
Note
+ As described in Section 4.2.14, there are various
+ situations in which subexpressions of an expression are evaluated at
+ different times, so that the principle that “CASE
+ evaluates only necessary subexpressions” is not ironclad. For
+ example a constant 1/0 subexpression will usually result in
+ a division-by-zero failure at planning time, even if it's within
+ a CASE arm that would never be entered at run time.
+
+ The COALESCE function returns the first of its
+ arguments that is not null. Null is returned only if all arguments
+ are null. It is often used to substitute a default value for
+ null values when data is retrieved for display, for example:
+
+ This returns description if it is not null, otherwise
+ short_description if it is not null, otherwise (none).
+
+ The arguments must all be convertible to a common data type, which
+ will be the type of the result (see
+ Section 10.5 for details).
+
+ Like a CASE expression, COALESCE only
+ evaluates the arguments that are needed to determine the result;
+ that is, arguments to the right of the first non-null argument are
+ not evaluated. This SQL-standard function provides capabilities similar
+ to NVL and IFNULL, which are used in some other
+ database systems.
+
+ The NULLIF function returns a null value if
+ value1 equals value2;
+ otherwise it returns value1.
+ This can be used to perform the inverse operation of the
+ COALESCE example given above:
+
+SELECT NULLIF(value, '(none)') ...
+
+ In this example, if value is (none),
+ null is returned, otherwise the value of value
+ is returned.
+
+ The two arguments must be of comparable types.
+ To be specific, they are compared exactly as if you had
+ written value1
+ = value2, so there must be a
+ suitable = operator available.
+
+ The result has the same type as the first argument — but there is
+ a subtlety. What is actually returned is the first argument of the
+ implied = operator, and in some cases that will have
+ been promoted to match the second argument's type. For
+ example, NULLIF(1, 2.2) yields numeric,
+ because there is no integer=
+ numeric operator,
+ only numeric=numeric.
+
+ The GREATEST and LEAST functions select the
+ largest or smallest value from a list of any number of expressions.
+ The expressions must all be convertible to a common data type, which
+ will be the type of the result
+ (see Section 10.5 for details).
+
+ NULL values in the argument list are ignored. The result will be NULL
+ only if all the expressions evaluate to NULL. (This is a deviation from
+ the SQL standard. According to the standard, the return value is NULL if
+ any argument is NULL. Some other databases behave this way.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-datetime.html b/pgsql/doc/postgresql/html/functions-datetime.html
new file mode 100644
index 0000000000000000000000000000000000000000..467291eb8c2f7ecc141d5779944686fd1852d2a1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-datetime.html
@@ -0,0 +1,1357 @@
+
+9.9. Date/Time Functions and Operators
+ Table 9.33 shows the available
+ functions for date/time value processing, with details appearing in
+ the following subsections. Table 9.32 illustrates the behaviors of
+ the basic arithmetic operators (+,
+ *, etc.). For formatting functions, refer to
+ Section 9.8. You should be familiar with
+ the background information on date/time data types from Section 8.5.
+
+ In addition, the usual comparison operators shown in
+ Table 9.1 are available for the
+ date/time types. Dates and timestamps (with or without time zone) are
+ all comparable, while times (with or without time zone) and intervals
+ can only be compared to other values of the same data type. When
+ comparing a timestamp without time zone to a timestamp with time zone,
+ the former value is assumed to be given in the time zone specified by
+ the TimeZone configuration parameter, and is
+ rotated to UTC for comparison to the latter value (which is already
+ in UTC internally). Similarly, a date value is assumed to represent
+ midnight in the TimeZone zone when comparing it
+ to a timestamp.
+
+ All the functions and operators described below that take time or timestamp
+ inputs actually come in two variants: one that takes time with time zone or timestamp
+ with time zone, and one that takes time without time zone or timestamp without time zone.
+ For brevity, these variants are not shown separately. Also, the
+ + and * operators come in commutative pairs (for
+ example both date+integer
+ and integer+date); we show
+ only one of each such pair.
+
+
+ date_add ( timestamp with time zone, interval [, text] )
+ → timestamp with time zone
+
+
+ Add an interval to a timestamp with time
+ zone, computing times of day and daylight-savings adjustments
+ according to the time zone named by the third argument, or the
+ current TimeZone setting if that is omitted.
+ The form with two arguments is equivalent to the timestamp with
+ time zone+interval operator.
+
+
+ date_subtract ( timestamp with time zone, interval [, text] )
+ → timestamp with time zone
+
+
+ Subtract an interval from a timestamp with time
+ zone, computing times of day and daylight-savings adjustments
+ according to the time zone named by the third argument, or the
+ current TimeZone setting if that is omitted.
+ The form with two arguments is equivalent to the timestamp with
+ time zone-interval operator.
+
+
+ make_timestamptz ( yearint,
+ monthint,
+ dayint,
+ hourint,
+ minint,
+ secdouble precision
+ [, timezonetext] )
+ → timestamp with time zone
+
+
+ Create timestamp with time zone from year, month, day, hour, minute
+ and seconds fields (negative years signify BC).
+ If timezone is not
+ specified, the current time zone is used; the examples assume the
+ session time zone is Europe/London
+
+ This expression yields true when two time periods (defined by their
+ endpoints) overlap, false when they do not overlap. The endpoints
+ can be specified as pairs of dates, times, or time stamps; or as
+ a date, time, or time stamp followed by an interval. When a pair
+ of values is provided, either the start or the end can be written
+ first; OVERLAPS automatically takes the earlier value
+ of the pair as the start. Each time period is considered to
+ represent the half-open interval start<=
+ time<end, unless
+ start and end are equal in which case it
+ represents that single time instant. This means for instance that two
+ time periods with only an endpoint in common do not overlap.
+
+SELECT (DATE '2001-02-16', DATE '2001-12-21') OVERLAPS
+ (DATE '2001-10-30', DATE '2002-10-30');
+Result: true
+SELECT (DATE '2001-02-16', INTERVAL '100 days') OVERLAPS
+ (DATE '2001-10-30', DATE '2002-10-30');
+Result: false
+SELECT (DATE '2001-10-29', DATE '2001-10-30') OVERLAPS
+ (DATE '2001-10-30', DATE '2001-10-31');
+Result: false
+SELECT (DATE '2001-10-30', DATE '2001-10-30') OVERLAPS
+ (DATE '2001-10-30', DATE '2001-10-31');
+Result: true
+
+ When adding an interval value to (or subtracting an
+ interval value from) a timestamp
+ or timestamp with time zone value, the months, days, and
+ microseconds fields of the interval value are handled in turn.
+ First, a nonzero months field advances or decrements the date of the
+ timestamp by the indicated number of months, keeping the day of month the
+ same unless it would be past the end of the new month, in which case the
+ last day of that month is used. (For example, March 31 plus 1 month
+ becomes April 30, but March 31 plus 2 months becomes May 31.)
+ Then the days field advances or decrements the date of the timestamp by
+ the indicated number of days. In both these steps the local time of day
+ is kept the same. Finally, if there is a nonzero microseconds field, it
+ is added or subtracted literally.
+ When doing arithmetic on a timestamp with time zone value in
+ a time zone that recognizes DST, this means that adding or subtracting
+ (say) interval '1 day' does not necessarily have the
+ same result as adding or subtracting interval '24
+ hours'.
+ For example, with the session time zone set
+ to America/Denver:
+
+SELECT timestamp with time zone '2005-04-02 12:00:00-07' + interval '1 day';
+Result: 2005-04-03 12:00:00-06
+SELECT timestamp with time zone '2005-04-02 12:00:00-07' + interval '24 hours';
+Result: 2005-04-03 13:00:00-06
+
+ This happens because an hour was skipped due to a change in daylight saving
+ time at 2005-04-03 02:00:00 in time zone
+ America/Denver.
+
+ Note there can be ambiguity in the months field returned by
+ age because different months have different numbers of
+ days. PostgreSQL's approach uses the month from the
+ earlier of the two dates when calculating partial months. For example,
+ age('2004-06-01', '2004-04-30') uses April to yield
+ 1 mon 1 day, while using May would yield 1 mon 2
+ days because May has 31 days, while April has only 30.
+
+ Subtraction of dates and timestamps can also be complex. One conceptually
+ simple way to perform subtraction is to convert each value to a number
+ of seconds using EXTRACT(EPOCH FROM ...), then subtract the
+ results; this produces the
+ number of seconds between the two values. This will adjust
+ for the number of days in each month, timezone changes, and daylight
+ saving time adjustments. Subtraction of date or timestamp
+ values with the “-” operator
+ returns the number of days (24-hours) and hours/minutes/seconds
+ between the values, making the same adjustments. The age
+ function returns years, months, days, and hours/minutes/seconds,
+ performing field-by-field subtraction and then adjusting for negative
+ field values. The following queries illustrate the differences in these
+ approaches. The sample results were produced with timezone
+ = 'US/Eastern'; there is a daylight saving time change between the
+ two dates used:
+
+SELECT EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
+ EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00');
+Result: 10537200.000000
+SELECT (EXTRACT(EPOCH FROM timestamptz '2013-07-01 12:00:00') -
+ EXTRACT(EPOCH FROM timestamptz '2013-03-01 12:00:00'))
+ / 60 / 60 / 24;
+Result: 121.9583333333333333
+SELECT timestamptz '2013-07-01 12:00:00' - timestamptz '2013-03-01 12:00:00';
+Result: 121 days 23:00:00
+SELECT age(timestamptz '2013-07-01 12:00:00', timestamptz '2013-03-01 12:00:00');
+Result: 4 mons
+
+ The extract function retrieves subfields
+ such as year or hour from date/time values.
+ source must be a value expression of
+ type timestamp, date, time,
+ or interval. (Timestamps and times can be with or
+ without time zone.)
+ field is an identifier or
+ string that selects what field to extract from the source value.
+ Not all fields are valid for every input data type; for example, fields
+ smaller than a day cannot be extracted from a date, while
+ fields of a day or more cannot be extracted from a time.
+ The extract function returns values of type
+ numeric.
+
+ The following are valid field names:
+
+
+
century
+ The century; for interval values, the year field
+ divided by 100
+
+SELECT EXTRACT(CENTURY FROM TIMESTAMP '2000-12-16 12:21:13');
+Result: 20
+SELECT EXTRACT(CENTURY FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 21
+SELECT EXTRACT(CENTURY FROM DATE '0001-01-01 AD');
+Result: 1
+SELECT EXTRACT(CENTURY FROM DATE '0001-12-31 BC');
+Result: -1
+SELECT EXTRACT(CENTURY FROM INTERVAL '2001 years');
+Result: 20
+
day
+ The day of the month (1–31); for interval
+ values, the number of days
+
+SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 16
+SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
+Result: 40
+
decade
+ The year field divided by 10
+
+SELECT EXTRACT(DECADE FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 200
+
dow
+ The day of the week as Sunday (0) to
+ Saturday (6)
+
+SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 5
+
+ Note that extract's day of the week numbering
+ differs from that of the to_char(...,
+ 'D') function.
+
doy
+ The day of the year (1–365/366)
+
+SELECT EXTRACT(DOY FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 47
+
epoch
+ For timestamp with time zone values, the
+ number of seconds since 1970-01-01 00:00:00 UTC (negative for
+ timestamps before that);
+ for date and timestamp values, the
+ nominal number of seconds since 1970-01-01 00:00:00,
+ without regard to timezone or daylight-savings rules;
+ for interval values, the total number
+ of seconds in the interval
+
+SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
+Result: 982384720.120000
+SELECT EXTRACT(EPOCH FROM TIMESTAMP '2001-02-16 20:38:40.12');
+Result: 982355920.120000
+SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
+Result: 442800.000000
+
+ You can convert an epoch value back to a timestamp with time zone
+ with to_timestamp:
+
+ Beware that applying to_timestamp to an epoch
+ extracted from a date or timestamp value
+ could produce a misleading result: the result will effectively
+ assume that the original value had been given in UTC, which might
+ not be the case.
+
hour
+ The hour field (0–23 in timestamps, unrestricted in
+ intervals)
+
+SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 20
+
isodow
+ The day of the week as Monday (1) to
+ Sunday (7)
+
+SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
+Result: 7
+
+ This is identical to dow except for Sunday. This
+ matches the ISO 8601 day of the week numbering.
+
isoyear
+ The ISO 8601 week-numbering year that the date
+ falls in
+
+SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-01');
+Result: 2005
+SELECT EXTRACT(ISOYEAR FROM DATE '2006-01-02');
+Result: 2006
+
+ Each ISO 8601 week-numbering year begins with the
+ Monday of the week containing the 4th of January, so in early
+ January or late December the ISO year may be
+ different from the Gregorian year. See the week
+ field for more information.
+
julian
+ The Julian Date corresponding to the
+ date or timestamp. Timestamps
+ that are not local midnight result in a fractional value. See
+ Section B.7 for more information.
+
+SELECT EXTRACT(JULIAN FROM DATE '2006-01-01');
+Result: 2453737
+SELECT EXTRACT(JULIAN FROM TIMESTAMP '2006-01-01 12:00');
+Result: 2453737.50000000000000000000
+
microseconds
+ The seconds field, including fractional parts, multiplied by 1
+ 000 000; note that this includes full seconds
+
+SELECT EXTRACT(MICROSECONDS FROM TIME '17:12:28.5');
+Result: 28500000
+
millennium
+ The millennium; for interval values, the year field
+ divided by 1000
+
+SELECT EXTRACT(MILLENNIUM FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 3
+SELECT EXTRACT(MILLENNIUM FROM INTERVAL '2001 years');
+Result: 2
+
+ Years in the 1900s are in the second millennium.
+ The third millennium started January 1, 2001.
+
milliseconds
+ The seconds field, including fractional parts, multiplied by
+ 1000. Note that this includes full seconds.
+
+SELECT EXTRACT(MILLISECONDS FROM TIME '17:12:28.5');
+Result: 28500.000
+
minute
+ The minutes field (0–59)
+
+SELECT EXTRACT(MINUTE FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 38
+
month
+ The number of the month within the year (1–12);
+ for interval values, the number of months modulo 12
+ (0–11)
+
+SELECT EXTRACT(MONTH FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 2
+SELECT EXTRACT(MONTH FROM INTERVAL '2 years 3 months');
+Result: 3
+SELECT EXTRACT(MONTH FROM INTERVAL '2 years 13 months');
+Result: 1
+
quarter
+ The quarter of the year (1–4) that the date is in
+
+SELECT EXTRACT(QUARTER FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 1
+
second
+ The seconds field, including any fractional seconds
+
+SELECT EXTRACT(SECOND FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 40.000000
+SELECT EXTRACT(SECOND FROM TIME '17:12:28.5');
+Result: 28.500000
+
timezone
+ The time zone offset from UTC, measured in seconds. Positive values
+ correspond to time zones east of UTC, negative values to
+ zones west of UTC. (Technically,
+ PostgreSQL does not use UTC because
+ leap seconds are not handled.)
+
timezone_hour
+ The hour component of the time zone offset
+
timezone_minute
+ The minute component of the time zone offset
+
week
+ The number of the ISO 8601 week-numbering week of
+ the year. By definition, ISO weeks start on Mondays and the first
+ week of a year contains January 4 of that year. In other words, the
+ first Thursday of a year is in week 1 of that year.
+
+ In the ISO week-numbering system, it is possible for early-January
+ dates to be part of the 52nd or 53rd week of the previous year, and for
+ late-December dates to be part of the first week of the next year.
+ For example, 2005-01-01 is part of the 53rd week of year
+ 2004, and 2006-01-01 is part of the 52nd week of year
+ 2005, while 2012-12-31 is part of the first week of 2013.
+ It's recommended to use the isoyear field together with
+ week to get consistent results.
+
+SELECT EXTRACT(WEEK FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 7
+
year
+ The year field. Keep in mind there is no 0 AD, so subtracting
+ BC years from AD years should be done with care.
+
+SELECT EXTRACT(YEAR FROM TIMESTAMP '2001-02-16 20:38:40');
+Result: 2001
+
+
+ When processing an interval value,
+ the extract function produces field values that
+ match the interpretation used by the interval output function. This
+ can produce surprising results if one starts with a non-normalized
+ interval representation, for example:
+
+ When the input value is +/-Infinity, extract returns
+ +/-Infinity for monotonically-increasing fields (epoch,
+ julian, year, isoyear,
+ decade, century, and millennium).
+ For other fields, NULL is returned. PostgreSQL
+ versions before 9.6 returned zero for all cases of infinite input.
+
+ The extract function is primarily intended
+ for computational processing. For formatting date/time values for
+ display, see Section 9.8.
+
+ The date_part function is modeled on the traditional
+ Ingres equivalent to the
+ SQL-standard function extract:
+
+date_part('field', source)
+
+ Note that here the field parameter needs to
+ be a string value, not a name. The valid field names for
+ date_part are the same as for
+ extract.
+ For historical reasons, the date_part function
+ returns values of type double precision. This can result in
+ a loss of precision in certain uses. Using extract
+ is recommended instead.
+
+ The function date_trunc is conceptually
+ similar to the trunc function for numbers.
+
+
+date_trunc(field, source [, time_zone ])
+
+ source is a value expression of type
+ timestamp, timestamp with time zone,
+ or interval.
+ (Values of type date and
+ time are cast automatically to timestamp or
+ interval, respectively.)
+ field selects to which precision to
+ truncate the input value. The return value is likewise of type
+ timestamp, timestamp with time zone,
+ or interval,
+ and it has all fields that are less significant than the
+ selected one set to zero (or one, for day and month).
+
+ Valid values for field are:
+
microseconds
milliseconds
second
minute
hour
day
week
month
quarter
year
decade
century
millennium
+
+ When the input value is of type timestamp with time zone,
+ the truncation is performed with respect to a particular time zone;
+ for example, truncation to day produces a value that
+ is midnight in that zone. By default, truncation is done with respect
+ to the current TimeZone setting, but the
+ optional time_zone argument can be provided
+ to specify a different time zone. The time zone name can be specified
+ in any of the ways described in Section 8.5.3.
+
+ A time zone cannot be specified when processing timestamp without
+ time zone or interval inputs. These are always
+ taken at face value.
+
+ Examples (assuming the local time zone is America/New_York):
+
+SELECT date_trunc('hour', TIMESTAMP '2001-02-16 20:38:40');
+Result: 2001-02-16 20:00:00
+SELECT date_trunc('year', TIMESTAMP '2001-02-16 20:38:40');
+Result: 2001-01-01 00:00:00
+SELECT date_trunc('day', TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40+00');
+Result: 2001-02-16 00:00:00-05
+SELECT date_trunc('day', TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40+00', 'Australia/Sydney');
+Result: 2001-02-16 08:00:00-05
+SELECT date_trunc('hour', INTERVAL '3 days 02:47:33');
+Result: 3 days 02:00:00
+
+ The function date_bin“bins” the input
+ timestamp into the specified interval (the stride)
+ aligned with a specified origin.
+
+
+date_bin(stride, source, origin)
+
+ source is a value expression of type
+ timestamp or timestamp with time zone. (Values
+ of type date are cast automatically to
+ timestamp.) stride is a value
+ expression of type interval. The return value is likewise
+ of type timestamp or timestamp with time zone,
+ and it marks the beginning of the bin into which the
+ source is placed.
+
+ In the case of full units (1 minute, 1 hour, etc.), it gives the same result as
+ the analogous date_trunc call, but the difference is
+ that date_bin can truncate to an arbitrary interval.
+
+ The stride interval must be greater than zero and
+ cannot contain units of month or larger.
+
+ The AT TIME ZONE operator converts time
+ stamp without time zone to/from
+ time stamp with time zone, and
+ time with time zone values to different time
+ zones. Table 9.34 shows its
+ variants.
+
Table 9.34. AT TIME ZONE Variants
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ timestamp without time zoneAT TIME ZONEzone
+ → timestamp with time zone
+
+
+ Converts given time stamp without time zone to
+ time stamp with time zone, assuming the given
+ value is in the named time zone.
+
+
+ timestamp '2001-02-16 20:38:40' at time zone 'America/Denver'
+ → 2001-02-17 03:38:40+00
+
+ timestamp with time zoneAT TIME ZONEzone
+ → timestamp without time zone
+
+
+ Converts given time stamp with time zone to
+ time stamp without time zone, as the time would
+ appear in that zone.
+
+
+ timestamp with time zone '2001-02-16 20:38:40-05' at time zone 'America/Denver'
+ → 2001-02-16 18:38:40
+
+ time with time zoneAT TIME ZONEzone
+ → time with time zone
+
+
+ Converts given time with time zone to a new time
+ zone. Since no date is supplied, this uses the currently active UTC
+ offset for the named destination zone.
+
+
+ time with time zone '05:34:17-05' at time zone 'UTC'
+ → 10:34:17+00
+
+ In these expressions, the desired time zone zone can be
+ specified either as a text value (e.g., 'America/Los_Angeles')
+ or as an interval (e.g., INTERVAL '-08:00').
+ In the text case, a time zone name can be specified in any of the ways
+ described in Section 8.5.3.
+ The interval case is only useful for zones that have fixed offsets from
+ UTC, so it is not very common in practice.
+
+ Examples (assuming the current TimeZone setting
+ is America/Los_Angeles):
+
+SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'America/Denver';
+Result: 2001-02-16 19:38:40-08
+SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'America/Denver';
+Result: 2001-02-16 18:38:40
+SELECT TIMESTAMP '2001-02-16 20:38:40' AT TIME ZONE 'Asia/Tokyo' AT TIME ZONE 'America/Chicago';
+Result: 2001-02-16 05:38:40
+
+ The first example adds a time zone to a value that lacks it, and
+ displays the value using the current TimeZone
+ setting. The second example shifts the time stamp with time zone value
+ to the specified time zone, and returns the value without a time zone.
+ This allows storage and display of values different from the current
+ TimeZone setting. The third example converts
+ Tokyo time to Chicago time.
+
+ The function timezone(zone,
+ timestamp) is equivalent to the SQL-conforming construct
+ timestamp AT TIME ZONE
+ zone.
+
+ PostgreSQL provides a number of functions
+ that return values related to the current date and time. These
+ SQL-standard functions all return values based on the start time of
+ the current transaction:
+
+ CURRENT_TIME and
+ CURRENT_TIMESTAMP deliver values with time zone;
+ LOCALTIME and
+ LOCALTIMESTAMP deliver values without time zone.
+
+ CURRENT_TIME,
+ CURRENT_TIMESTAMP,
+ LOCALTIME, and
+ LOCALTIMESTAMP
+ can optionally take
+ a precision parameter, which causes the result to be rounded
+ to that many fractional digits in the seconds field. Without a precision parameter,
+ the result is given to the full available precision.
+
+ Since these functions return
+ the start time of the current transaction, their values do not
+ change during the transaction. This is considered a feature:
+ the intent is to allow a single transaction to have a consistent
+ notion of the “current” time, so that multiple
+ modifications within the same transaction bear the same
+ time stamp.
+
Note
+ Other database systems might advance these values more
+ frequently.
+
+ PostgreSQL also provides functions that
+ return the start time of the current statement, as well as the actual
+ current time at the instant the function is called. The complete list
+ of non-SQL-standard time functions is:
+
+ transaction_timestamp() is equivalent to
+ CURRENT_TIMESTAMP, but is named to clearly reflect
+ what it returns.
+ statement_timestamp() returns the start time of the current
+ statement (more specifically, the time of receipt of the latest command
+ message from the client).
+ statement_timestamp() and transaction_timestamp()
+ return the same value during the first command of a transaction, but might
+ differ during subsequent commands.
+ clock_timestamp() returns the actual current time, and
+ therefore its value changes even within a single SQL command.
+ timeofday() is a historical
+ PostgreSQL function. Like
+ clock_timestamp(), it returns the actual current time,
+ but as a formatted text string rather than a timestamp
+ with time zone value.
+ now() is a traditional PostgreSQL
+ equivalent to transaction_timestamp().
+
+ All the date/time data types also accept the special literal value
+ now to specify the current date and time (again,
+ interpreted as the transaction start time). Thus,
+ the following three all return the same result:
+
+SELECT CURRENT_TIMESTAMP;
+SELECT now();
+SELECT TIMESTAMP 'now'; -- but see tip below
+
+
Tip
+ Do not use the third form when specifying a value to be evaluated later,
+ for example in a DEFAULT clause for a table column.
+ The system will convert now
+ to a timestamp as soon as the constant is parsed, so that when
+ the default value is needed,
+ the time of the table creation would be used! The first two
+ forms will not be evaluated until the default value is used,
+ because they are function calls. Thus they will give the desired
+ behavior of defaulting to the time of row insertion.
+ (See also Section 8.5.1.4.)
+
+ The following functions are available to delay execution of the server
+ process:
+
+pg_sleep ( double precision )
+pg_sleep_for ( interval )
+pg_sleep_until ( timestamp with time zone )
+
+
+ pg_sleep makes the current session's process
+ sleep until the given number of seconds have
+ elapsed. Fractional-second delays can be specified.
+ pg_sleep_for is a convenience function to
+ allow the sleep time to be specified as an interval.
+ pg_sleep_until is a convenience function for when
+ a specific wake-up time is desired.
+ For example:
+
+
+ The effective resolution of the sleep interval is platform-specific;
+ 0.01 seconds is a common value. The sleep delay will be at least as long
+ as specified. It might be longer depending on factors such as server load.
+ In particular, pg_sleep_until is not guaranteed to
+ wake up exactly at the specified time, but it will not wake up any earlier.
+
Warning
+ Make sure that your session does not hold more locks than necessary
+ when calling pg_sleep or its variants. Otherwise
+ other sessions might have to wait for your sleeping process, slowing down
+ the entire system.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-enum.html b/pgsql/doc/postgresql/html/functions-enum.html
new file mode 100644
index 0000000000000000000000000000000000000000..f993d1dd94cb846410a57f6323eefa590be2a9aa
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-enum.html
@@ -0,0 +1,84 @@
+
+9.10. Enum Support Functions
+ For enum types (described in Section 8.7),
+ there are several functions that allow cleaner programming without
+ hard-coding particular values of an enum type.
+ These are listed in Table 9.35. The examples
+ assume an enum type created as:
+
+
+CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple');
+
+
+
Table 9.35. Enum Support Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ enum_first ( anyenum )
+ → anyenum
+
+
+ Returns the first value of the input enum type.
+
+
+ enum_first(null::rainbow)
+ → red
+
+
+ enum_last ( anyenum )
+ → anyenum
+
+
+ Returns the last value of the input enum type.
+
+
+ enum_last(null::rainbow)
+ → purple
+
+
+ enum_range ( anyenum )
+ → anyarray
+
+
+ Returns all values of the input enum type in an ordered array.
+
+ Returns the range between the two given enum values, as an ordered
+ array. The values must be from the same enum type. If the first
+ parameter is null, the result will start with the first value of
+ the enum type.
+ If the second parameter is null, the result will end with the last
+ value of the enum type.
+
+ Notice that except for the two-argument form of enum_range,
+ these functions disregard the specific value passed to them; they care
+ only about its declared data type. Either null or a specific value of
+ the type can be passed, with the same result. It is more common to
+ apply these functions to a table column or function argument than to
+ a hardwired type name as used in the examples.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-event-triggers.html b/pgsql/doc/postgresql/html/functions-event-triggers.html
new file mode 100644
index 0000000000000000000000000000000000000000..c5bba8d9c1c9ee479f6584af28fde98cb776927d
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-event-triggers.html
@@ -0,0 +1,133 @@
+
+9.29. Event Trigger Functions
+pg_event_trigger_ddl_commands () → setof record
+
+ pg_event_trigger_ddl_commands returns a list of
+ DDL commands executed by each user action,
+ when invoked in a function attached to a
+ ddl_command_end event trigger. If called in any other
+ context, an error is raised.
+ pg_event_trigger_ddl_commands returns one row for each
+ base command executed; some commands that are a single SQL sentence
+ may return more than one row. This function returns the following
+ columns:
+
+
Name
Type
Description
classid
oid
OID of catalog the object belongs in
objid
oid
OID of the object itself
objsubid
integer
Sub-object ID (e.g., attribute number for a column)
command_tag
text
Command tag
object_type
text
Type of the object
schema_name
text
+ Name of the schema the object belongs in, if any; otherwise NULL.
+ No quoting is applied.
+
object_identity
text
+ Text rendering of the object identity, schema-qualified. Each
+ identifier included in the identity is quoted if necessary.
+
in_extension
boolean
True if the command is part of an extension script
command
pg_ddl_command
+ A complete representation of the command, in internal format.
+ This cannot be output directly, but it can be passed to other
+ functions to obtain different pieces of information about the
+ command.
+
+
9.29.2. Processing Objects Dropped by a DDL Command #
+pg_event_trigger_dropped_objects () → setof record
+
+ pg_event_trigger_dropped_objects returns a list of all objects
+ dropped by the command in whose sql_drop event it is called.
+ If called in any other context, an error is raised.
+ This function returns the following columns:
+
+
Name
Type
Description
classid
oid
OID of catalog the object belonged in
objid
oid
OID of the object itself
objsubid
integer
Sub-object ID (e.g., attribute number for a column)
original
boolean
True if this was one of the root object(s) of the deletion
normal
boolean
+ True if there was a normal dependency relationship
+ in the dependency graph leading to this object
+
is_temporary
boolean
+ True if this was a temporary object
+
object_type
text
Type of the object
schema_name
text
+ Name of the schema the object belonged in, if any; otherwise NULL.
+ No quoting is applied.
+
object_name
text
+ Name of the object, if the combination of schema and name can be
+ used as a unique identifier for the object; otherwise NULL.
+ No quoting is applied, and name is never schema-qualified.
+
object_identity
text
+ Text rendering of the object identity, schema-qualified. Each
+ identifier included in the identity is quoted if necessary.
+
address_names
text[]
+ An array that, together with object_type and
+ address_args, can be used by
+ the pg_get_object_address function to
+ recreate the object address in a remote server containing an
+ identically named object of the same kind.
+
address_args
text[]
+ Complement for address_names
+
+
+ The pg_event_trigger_dropped_objects function can be used
+ in an event trigger like this:
+
+CREATE FUNCTION test_event_trigger_for_drops()
+ RETURNS event_trigger LANGUAGE plpgsql AS $$
+DECLARE
+ obj record;
+BEGIN
+ FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects()
+ LOOP
+ RAISE NOTICE '% dropped object: % %.% %',
+ tg_tag,
+ obj.object_type,
+ obj.schema_name,
+ obj.object_name,
+ obj.object_identity;
+ END LOOP;
+END;
+$$;
+CREATE EVENT TRIGGER test_event_trigger_for_drops
+ ON sql_drop
+ EXECUTE FUNCTION test_event_trigger_for_drops();
+
+ The functions shown in
+ Table 9.104
+ provide information about a table for which a
+ table_rewrite event has just been called.
+ If called in any other context, an error is raised.
+
Table 9.104. Table Rewrite Information Functions
+ Function
+
+
+ Description
+
+
+ pg_event_trigger_table_rewrite_oid ()
+ → oid
+
+
+ Returns the OID of the table about to be rewritten.
+
+ Returns a code explaining the reason(s) for rewriting. The exact
+ meaning of the codes is release dependent.
+
+ These functions can be used in an event trigger like this:
+
+CREATE FUNCTION test_event_trigger_table_rewrite_oid()
+ RETURNS event_trigger
+ LANGUAGE plpgsql AS
+$$
+BEGIN
+ RAISE NOTICE 'rewriting table % for reason %',
+ pg_event_trigger_table_rewrite_oid()::regclass,
+ pg_event_trigger_table_rewrite_reason();
+END;
+$$;
+
+CREATE EVENT TRIGGER test_table_rewrite_oid
+ ON table_rewrite
+ EXECUTE FUNCTION test_event_trigger_table_rewrite_oid();
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-formatting.html b/pgsql/doc/postgresql/html/functions-formatting.html
new file mode 100644
index 0000000000000000000000000000000000000000..840b05a9da9af23d55af325f8136dfe4af749344
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-formatting.html
@@ -0,0 +1,410 @@
+
+9.8. Data Type Formatting Functions
+ The PostgreSQL formatting functions
+ provide a powerful set of tools for converting various data types
+ (date/time, integer, floating point, numeric) to formatted strings
+ and for converting from formatted strings to specific data types.
+ Table 9.26 lists them.
+ These functions all follow a common calling convention: the first
+ argument is the value to be formatted and the second argument is a
+ template that defines the output or input format.
+
Table 9.26. Formatting Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ to_char ( timestamp, text )
+ → text
+
+
+ to_char ( timestamp with time zone, text )
+ → text
+
+
+ Converts time stamp to string according to the given format.
+
+ to_timestamp and to_date
+ exist to handle input formats that cannot be converted by
+ simple casting. For most standard date/time formats, simply casting the
+ source string to the required data type works, and is much easier.
+ Similarly, to_number is unnecessary for standard numeric
+ representations.
+
+ In a to_char output template string, there are certain
+ patterns that are recognized and replaced with appropriately-formatted
+ data based on the given value. Any text that is not a template pattern is
+ simply copied verbatim. Similarly, in an input template string (for the
+ other functions), template patterns identify the values to be supplied by
+ the input data string. If there are characters in the template string
+ that are not template patterns, the corresponding characters in the input
+ data string are simply skipped over (whether or not they are equal to the
+ template string characters).
+
+ Table 9.27 shows the
+ template patterns available for formatting date and time values.
+
Table 9.27. Template Patterns for Date/Time Formatting
Pattern
Description
HH
hour of day (01–12)
HH12
hour of day (01–12)
HH24
hour of day (00–23)
MI
minute (00–59)
SS
second (00–59)
MS
millisecond (000–999)
US
microsecond (000000–999999)
FF1
tenth of second (0–9)
FF2
hundredth of second (00–99)
FF3
millisecond (000–999)
FF4
tenth of a millisecond (0000–9999)
FF5
hundredth of a millisecond (00000–99999)
FF6
microsecond (000000–999999)
SSSS, SSSSS
seconds past midnight (0–86399)
AM, am,
+ PM or pm
meridiem indicator (without periods)
A.M., a.m.,
+ P.M. or p.m.
meridiem indicator (with periods)
Y,YYY
year (4 or more digits) with comma
YYYY
year (4 or more digits)
YYY
last 3 digits of year
YY
last 2 digits of year
Y
last digit of year
IYYY
ISO 8601 week-numbering year (4 or more digits)
IYY
last 3 digits of ISO 8601 week-numbering year
IY
last 2 digits of ISO 8601 week-numbering year
I
last digit of ISO 8601 week-numbering year
BC, bc,
+ AD or ad
era indicator (without periods)
B.C., b.c.,
+ A.D. or a.d.
era indicator (with periods)
MONTH
full upper case month name (blank-padded to 9 chars)
Month
full capitalized month name (blank-padded to 9 chars)
month
full lower case month name (blank-padded to 9 chars)
MON
abbreviated upper case month name (3 chars in English, localized lengths vary)
Mon
abbreviated capitalized month name (3 chars in English, localized lengths vary)
mon
abbreviated lower case month name (3 chars in English, localized lengths vary)
MM
month number (01–12)
DAY
full upper case day name (blank-padded to 9 chars)
Day
full capitalized day name (blank-padded to 9 chars)
day
full lower case day name (blank-padded to 9 chars)
DY
abbreviated upper case day name (3 chars in English, localized lengths vary)
Dy
abbreviated capitalized day name (3 chars in English, localized lengths vary)
dy
abbreviated lower case day name (3 chars in English, localized lengths vary)
DDD
day of year (001–366)
IDDD
day of ISO 8601 week-numbering year (001–371; day 1 of the year is Monday of the first ISO week)
DD
day of month (01–31)
D
day of the week, Sunday (1) to Saturday (7)
ID
ISO 8601 day of the week, Monday (1) to Sunday (7)
W
week of month (1–5) (the first week starts on the first day of the month)
WW
week number of year (1–53) (the first week starts on the first day of the year)
IW
week number of ISO 8601 week-numbering year (01–53; the first Thursday of the year is in week 1)
CC
century (2 digits) (the twenty-first century starts on 2001-01-01)
J
Julian Date (integer days since November 24, 4714 BC at local
+ midnight; see Section B.7)
Q
quarter
RM
month in upper case Roman numerals (I–XII; I=January)
rm
month in lower case Roman numerals (i–xii; i=January)
TZ
upper case time-zone abbreviation
+ (only supported in to_char)
tz
lower case time-zone abbreviation
+ (only supported in to_char)
TZH
time-zone hours
TZM
time-zone minutes
OF
time-zone offset from UTC
+ (only supported in to_char)
+ Modifiers can be applied to any template pattern to alter its
+ behavior. For example, FMMonth
+ is the Month pattern with the
+ FM modifier.
+ Table 9.28 shows the
+ modifier patterns for date/time formatting.
+
Table 9.28. Template Pattern Modifiers for Date/Time Formatting
Modifier
Description
Example
FM prefix
fill mode (suppress leading zeroes and padding blanks)
FMMonth
TH suffix
upper case ordinal number suffix
DDTH, e.g., 12TH
th suffix
lower case ordinal number suffix
DDth, e.g., 12th
FX prefix
fixed format global option (see usage notes)
FX Month DD Day
TM prefix
translation mode (use localized day and month names based on
+ lc_time)
TMMonth
SP suffix
spell mode (not implemented)
DDSP
+ Usage notes for date/time formatting:
+
+
+ FM suppresses leading zeroes and trailing blanks
+ that would otherwise be added to make the output of a pattern be
+ fixed-width. In PostgreSQL,
+ FM modifies only the next specification, while in
+ Oracle FM affects all subsequent
+ specifications, and repeated FM modifiers
+ toggle fill mode on and off.
+
+ TM suppresses trailing blanks whether or
+ not FM is specified.
+
+ to_timestamp and to_date
+ ignore letter case in the input; so for
+ example MON, Mon,
+ and mon all accept the same strings. When using
+ the TM modifier, case-folding is done according to
+ the rules of the function's input collation (see
+ Section 24.2).
+
+ to_timestamp and to_date
+ skip multiple blank spaces at the beginning of the input string and
+ around date and time values unless the FX option is used. For example,
+ to_timestamp(' 2000 JUN', 'YYYY MON') and
+ to_timestamp('2000 - JUN', 'YYYY-MON') work, but
+ to_timestamp('2000 JUN', 'FXYYYY MON') returns an error
+ because to_timestamp expects only a single space.
+ FX must be specified as the first item in
+ the template.
+
+ A separator (a space or non-letter/non-digit character) in the template string of
+ to_timestamp and to_date
+ matches any single separator in the input string or is skipped,
+ unless the FX option is used.
+ For example, to_timestamp('2000JUN', 'YYYY///MON') and
+ to_timestamp('2000/JUN', 'YYYY MON') work, but
+ to_timestamp('2000//JUN', 'YYYY/MON')
+ returns an error because the number of separators in the input string
+ exceeds the number of separators in the template.
+
+ If FX is specified, a separator in the template string
+ matches exactly one character in the input string. But note that the
+ input string character is not required to be the same as the separator from the template string.
+ For example, to_timestamp('2000/JUN', 'FXYYYY MON')
+ works, but to_timestamp('2000/JUN', 'FXYYYY MON')
+ returns an error because the second space in the template string consumes
+ the letter J from the input string.
+
+ A TZH template pattern can match a signed number.
+ Without the FX option, minus signs may be ambiguous,
+ and could be interpreted as a separator.
+ This ambiguity is resolved as follows: If the number of separators before
+ TZH in the template string is less than the number of
+ separators before the minus sign in the input string, the minus sign
+ is interpreted as part of TZH.
+ Otherwise, the minus sign is considered to be a separator between values.
+ For example, to_timestamp('2000 -10', 'YYYY TZH') matches
+ -10 to TZH, but
+ to_timestamp('2000 -10', 'YYYY TZH')
+ matches 10 to TZH.
+
+ Ordinary text is allowed in to_char
+ templates and will be output literally. You can put a substring
+ in double quotes to force it to be interpreted as literal text
+ even if it contains template patterns. For example, in
+ '"Hello Year "YYYY', the YYYY
+ will be replaced by the year data, but the single Y in Year
+ will not be.
+ In to_date, to_number,
+ and to_timestamp, literal text and double-quoted
+ strings result in skipping the number of characters contained in the
+ string; for example "XX" skips two input characters
+ (whether or not they are XX).
+
Tip
+ Prior to PostgreSQL 12, it was possible to
+ skip arbitrary text in the input string using non-letter or non-digit
+ characters. For example,
+ to_timestamp('2000y6m1d', 'yyyy-MM-DD') used to
+ work. Now you can only use letter characters for this purpose. For example,
+ to_timestamp('2000y6m1d', 'yyyytMMtDDt') and
+ to_timestamp('2000y6m1d', 'yyyy"y"MM"m"DD"d"')
+ skip y, m, and
+ d.
+
+ If you want to have a double quote in the output you must
+ precede it with a backslash, for example '\"YYYY
+ Month\"'.
+ Backslashes are not otherwise special outside of double-quoted
+ strings. Within a double-quoted string, a backslash causes the
+ next character to be taken literally, whatever it is (but this
+ has no special effect unless the next character is a double quote
+ or another backslash).
+
+ In to_timestamp and to_date,
+ if the year format specification is less than four digits, e.g.,
+ YYY, and the supplied year is less than four digits,
+ the year will be adjusted to be nearest to the year 2020, e.g.,
+ 95 becomes 1995.
+
+ In to_timestamp and to_date,
+ negative years are treated as signifying BC. If you write both a
+ negative year and an explicit BC field, you get AD
+ again. An input of year zero is treated as 1 BC.
+
+ In to_timestamp and to_date,
+ the YYYY conversion has a restriction when
+ processing years with more than 4 digits. You must
+ use some non-digit character or template after YYYY,
+ otherwise the year is always interpreted as 4 digits. For example
+ (with the year 20000):
+ to_date('200001130', 'YYYYMMDD') will be
+ interpreted as a 4-digit year; instead use a non-digit
+ separator after the year, like
+ to_date('20000-1130', 'YYYY-MMDD') or
+ to_date('20000Nov30', 'YYYYMonDD').
+
+ In to_timestamp and to_date,
+ the CC (century) field is accepted but ignored
+ if there is a YYY, YYYY or
+ Y,YYY field. If CC is used with
+ YY or Y then the result is
+ computed as that year in the specified century. If the century is
+ specified but the year is not, the first year of the century
+ is assumed.
+
+ In to_timestamp and to_date,
+ weekday names or numbers (DAY, D,
+ and related field types) are accepted but are ignored for purposes of
+ computing the result. The same is true for quarter
+ (Q) fields.
+
+ In to_timestamp and to_date,
+ an ISO 8601 week-numbering date (as distinct from a Gregorian date)
+ can be specified in one of two ways:
+
+ Year, week number, and weekday: for
+ example to_date('2006-42-4', 'IYYY-IW-ID')
+ returns the date 2006-10-19.
+ If you omit the weekday it is assumed to be 1 (Monday).
+
+ Year and day of year: for example to_date('2006-291',
+ 'IYYY-IDDD') also returns 2006-10-19.
+
+
+ Attempting to enter a date using a mixture of ISO 8601 week-numbering
+ fields and Gregorian date fields is nonsensical, and will cause an
+ error. In the context of an ISO 8601 week-numbering year, the
+ concept of a “month” or “day of month” has no
+ meaning. In the context of a Gregorian year, the ISO week has no
+ meaning.
+
Caution
+ While to_date will reject a mixture of
+ Gregorian and ISO week-numbering date
+ fields, to_char will not, since output format
+ specifications like YYYY-MM-DD (IYYY-IDDD) can be
+ useful. But avoid writing something like IYYY-MM-DD;
+ that would yield surprising results near the start of the year.
+ (See Section 9.9.1 for more
+ information.)
+
+ In to_timestamp, millisecond
+ (MS) or microsecond (US)
+ fields are used as the
+ seconds digits after the decimal point. For example
+ to_timestamp('12.3', 'SS.MS') is not 3 milliseconds,
+ but 300, because the conversion treats it as 12 + 0.3 seconds.
+ So, for the format SS.MS, the input values
+ 12.3, 12.30,
+ and 12.300 specify the
+ same number of milliseconds. To get three milliseconds, one must write
+ 12.003, which the conversion treats as
+ 12 + 0.003 = 12.003 seconds.
+
+ Here is a more
+ complex example:
+ to_timestamp('15:12:02.020.001230', 'HH24:MI:SS.MS.US')
+ is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds +
+ 1230 microseconds = 2.021230 seconds.
+
+ to_char(..., 'ID')'s day of the week numbering
+ matches the extract(isodow from ...) function, but
+ to_char(..., 'D')'s does not match
+ extract(dow from ...)'s day numbering.
+
+ to_char(interval) formats HH and
+ HH12 as shown on a 12-hour clock, for example zero hours
+ and 36 hours both output as 12, while HH24
+ outputs the full hour value, which can exceed 23 in
+ an interval value.
+
+
+ Table 9.29 shows the
+ template patterns available for formatting numeric values.
+
Table 9.29. Template Patterns for Numeric Formatting
Pattern
Description
9
digit position (can be dropped if insignificant)
0
digit position (will not be dropped, even if insignificant)
. (period)
decimal point
, (comma)
group (thousands) separator
PR
negative value in angle brackets
S
sign anchored to number (uses locale)
L
currency symbol (uses locale)
D
decimal point (uses locale)
G
group separator (uses locale)
MI
minus sign in specified position (if number < 0)
PL
plus sign in specified position (if number > 0)
SG
plus/minus sign in specified position
RN
Roman numeral (input between 1 and 3999)
TH or th
ordinal number suffix
V
shift specified number of digits (see notes)
EEEE
exponent for scientific notation
+ Usage notes for numeric formatting:
+
+
+ 0 specifies a digit position that will always be printed,
+ even if it contains a leading/trailing zero. 9 also
+ specifies a digit position, but if it is a leading zero then it will
+ be replaced by a space, while if it is a trailing zero and fill mode
+ is specified then it will be deleted. (For to_number(),
+ these two pattern characters are equivalent.)
+
+ If the format provides fewer fractional digits than the number being
+ formatted, to_char() will round the number to
+ the specified number of fractional digits.
+
+ The pattern characters S, L, D,
+ and G represent the sign, currency symbol, decimal point,
+ and thousands separator characters defined by the current locale
+ (see lc_monetary
+ and lc_numeric). The pattern characters period
+ and comma represent those exact characters, with the meanings of
+ decimal point and thousands separator, regardless of locale.
+
+ If no explicit provision is made for a sign
+ in to_char()'s pattern, one column will be reserved for
+ the sign, and it will be anchored to (appear just left of) the
+ number. If S appears just left of some 9's,
+ it will likewise be anchored to the number.
+
+ A sign formatted using SG, PL, or
+ MI is not anchored to
+ the number; for example,
+ to_char(-12, 'MI9999') produces '- 12'
+ but to_char(-12, 'S9999') produces ' -12'.
+ (The Oracle implementation does not allow the use of
+ MI before 9, but rather
+ requires that 9 precede
+ MI.)
+
+ TH does not convert values less than zero
+ and does not convert fractional numbers.
+
+ PL, SG, and
+ TH are PostgreSQL
+ extensions.
+
+ In to_number, if non-data template patterns such
+ as L or TH are used, the
+ corresponding number of input characters are skipped, whether or not
+ they match the template pattern, unless they are data characters
+ (that is, digits, sign, decimal point, or comma). For
+ example, TH would skip two non-data characters.
+
+ V with to_char
+ multiplies the input values by
+ 10^n, where
+ n is the number of digits following
+ V. V with
+ to_number divides in a similar manner.
+ to_char and to_number
+ do not support the use of
+ V combined with a decimal point
+ (e.g., 99.9V99 is not allowed).
+
+ EEEE (scientific notation) cannot be used in
+ combination with any of the other formatting patterns or
+ modifiers other than digit and decimal point patterns, and must be at the end of the format string
+ (e.g., 9.99EEEE is a valid pattern).
+
+
+ Certain modifiers can be applied to any template pattern to alter its
+ behavior. For example, FM99.99
+ is the 99.99 pattern with the
+ FM modifier.
+ Table 9.30 shows the
+ modifier patterns for numeric formatting.
+
Table 9.30. Template Pattern Modifiers for Numeric Formatting
Modifier
Description
Example
FM prefix
fill mode (suppress trailing zeroes and padding blanks)
FM99.99
TH suffix
upper case ordinal number suffix
999TH
th suffix
lower case ordinal number suffix
999th
+ Table 9.31 shows some
+ examples of the use of the to_char function.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-geometry.html b/pgsql/doc/postgresql/html/functions-geometry.html
new file mode 100644
index 0000000000000000000000000000000000000000..a0f7cbc232ddcf275e22cd2eba9781b6ffde6340
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-geometry.html
@@ -0,0 +1,886 @@
+
+9.11. Geometric Functions and Operators
+ The geometric types point, box,
+ lseg, line, path,
+ polygon, and circle have a large set of
+ native support functions and operators, shown in Table 9.36, Table 9.37, and Table 9.38.
+
Table 9.36. Geometric Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ geometric_type+point
+ → geometric_type
+
+
+ Adds the coordinates of the second point to those of each
+ point of the first argument, thus performing translation.
+ Available for point, box, path,
+ circle.
+
+
+ box '(1,1),(0,0)' + point '(2,0)'
+ → (3,1),(2,0)
+
+ path+path
+ → path
+
+
+ Concatenates two open paths (returns NULL if either path is closed).
+
+ Subtracts the coordinates of the second point from those
+ of each point of the first argument, thus performing translation.
+ Available for point, box, path,
+ circle.
+
+
+ box '(1,1),(0,0)' - point '(2,0)'
+ → (-1,1),(-2,0)
+
+ geometric_type*point
+ → geometric_type
+
+
+ Multiplies each point of the first argument by the second
+ point (treating a point as being a complex number
+ represented by real and imaginary parts, and performing standard
+ complex multiplication). If one interprets
+ the second point as a vector, this is equivalent to
+ scaling the object's size and distance from the origin by the length
+ of the vector, and rotating it counterclockwise around the origin by
+ the vector's angle from the x axis.
+ Available for point, box,[a]
+ path, circle.
+
+
+ path '((0,0),(1,0),(1,1))' * point '(3.0,0)'
+ → ((0,0),(3,0),(3,3))
+
+ Divides each point of the first argument by the second
+ point (treating a point as being a complex number
+ represented by real and imaginary parts, and performing standard
+ complex division). If one interprets
+ the second point as a vector, this is equivalent to
+ scaling the object's size and distance from the origin down by the
+ length of the vector, and rotating it clockwise around the origin by
+ the vector's angle from the x axis.
+ Available for point, box,[a]path,
+ circle.
+
+
+ path '((0,0),(1,0),(1,1))' / point '(2.0,0)'
+ → ((0,0),(0.5,0),(0.5,0.5))
+
+ Computes the closest point to the first object on the second object.
+ Available for these pairs of types:
+ (point, box),
+ (point, lseg),
+ (point, line),
+ (lseg, box),
+ (lseg, lseg),
+ (line, lseg).
+
+
+ point '(0,0)' ## lseg '[(2,0),(0,2)]'
+ → (1,1)
+
+ Computes the distance between the objects.
+ Available for all seven geometric types, for all combinations
+ of point with another geometric type, and for
+ these additional pairs of types:
+ (box, lseg),
+ (lseg, line),
+ (polygon, circle)
+ (and the commutator cases).
+
+
+ circle '<(0,0),1>' <-> circle '<(5,0),1>'
+ → 3
+
+ geometric_type@>geometric_type
+ → boolean
+
+
+ Does first object contain second?
+ Available for these pairs of types:
+ (box, point),
+ (box, box),
+ (path, point),
+ (polygon, point),
+ (polygon, polygon),
+ (circle, point),
+ (circle, circle).
+
+
+ circle '<(0,0),2>' @> point '(1,1)'
+ → t
+
+ geometric_type<@geometric_type
+ → boolean
+
+
+ Is first object contained in or on second?
+ Available for these pairs of types:
+ (point, box),
+ (point, lseg),
+ (point, line),
+ (point, path),
+ (point, polygon),
+ (point, circle),
+ (box, box),
+ (lseg, box),
+ (lseg, line),
+ (polygon, polygon),
+ (circle, circle).
+
+
+ point '(1,1)' <@ circle '<(0,0),2>'
+ → t
+
+ geometric_type&&geometric_type
+ → boolean
+
+
+ Do these objects overlap? (One point in common makes this true.)
+ Available for box, polygon,
+ circle.
+
+
+ box '(1,1),(0,0)' && box '(2,2),(0,0)'
+ → t
+
+ geometric_type<<geometric_type
+ → boolean
+
+
+ Is first object strictly left of second?
+ Available for point, box,
+ polygon, circle.
+
+
+ circle '<(0,0),1>' << circle '<(5,0),1>'
+ → t
+
+ geometric_type>>geometric_type
+ → boolean
+
+
+ Is first object strictly right of second?
+ Available for point, box,
+ polygon, circle.
+
+
+ circle '<(5,0),1>' >> circle '<(0,0),1>'
+ → t
+
+ geometric_type&<geometric_type
+ → boolean
+
+
+ Does first object not extend to the right of second?
+ Available for box, polygon,
+ circle.
+
+
+ box '(1,1),(0,0)' &< box '(2,2),(0,0)'
+ → t
+
+ geometric_type&>geometric_type
+ → boolean
+
+
+ Does first object not extend to the left of second?
+ Available for box, polygon,
+ circle.
+
+
+ box '(3,3),(0,0)' &> box '(2,2),(0,0)'
+ → t
+
+ geometric_type<<|geometric_type
+ → boolean
+
+
+ Is first object strictly below second?
+ Available for point, box, polygon,
+ circle.
+
+
+ box '(3,3),(0,0)' <<| box '(5,5),(3,4)'
+ → t
+
+ geometric_type|>>geometric_type
+ → boolean
+
+
+ Is first object strictly above second?
+ Available for point, box, polygon,
+ circle.
+
+
+ box '(5,5),(3,4)' |>> box '(3,3),(0,0)'
+ → t
+
+ geometric_type&<|geometric_type
+ → boolean
+
+
+ Does first object not extend above second?
+ Available for box, polygon,
+ circle.
+
+
+ box '(1,1),(0,0)' &<| box '(2,2),(0,0)'
+ → t
+
+ geometric_type|&>geometric_type
+ → boolean
+
+
+ Does first object not extend below second?
+ Available for box, polygon,
+ circle.
+
+
+ box '(3,3),(0,0)' |&> box '(2,2),(0,0)'
+ → t
+
+ box<^box
+ → boolean
+
+
+ Is first object below second (allows edges to touch)?
+
+
+ box '((1,1),(0,0))' <^ box '((2,2),(1,1))'
+ → t
+
+ box>^box
+ → boolean
+
+
+ Is first object above second (allows edges to touch)?
+
+
+ box '((2,2),(1,1))' >^ box '((1,1),(0,0))'
+ → t
+
+ geometric_type?#geometric_type
+ → boolean
+
+
+ Do these objects intersect?
+ Available for these pairs of types:
+ (box, box),
+ (lseg, box),
+ (lseg, lseg),
+ (lseg, line),
+ (line, box),
+ (line, line),
+ (path, path).
+
+
+ lseg '[(-1,0),(1,0)]' ?# box '(2,2),(-2,-2)'
+ → t
+
+ ?-line
+ → boolean
+
+
+ ?-lseg
+ → boolean
+
+
+ Is line horizontal?
+
+
+ ?- lseg '[(-1,0),(1,0)]'
+ → t
+
+ point?-point
+ → boolean
+
+
+ Are points horizontally aligned (that is, have same y coordinate)?
+
+
+ point '(1,0)' ?- point '(0,0)'
+ → t
+
+ ?|line
+ → boolean
+
+
+ ?|lseg
+ → boolean
+
+
+ Is line vertical?
+
+
+ ?| lseg '[(-1,0),(1,0)]'
+ → f
+
+ point?|point
+ → boolean
+
+
+ Are points vertically aligned (that is, have same x coordinate)?
+
+
+ point '(0,1)' ?| point '(0,0)'
+ → t
+
+ line?-|line
+ → boolean
+
+
+ lseg?-|lseg
+ → boolean
+
+
+ Are lines perpendicular?
+
+
+ lseg '[(0,0),(0,1)]' ?-| lseg '[(0,0),(1,0)]'
+ → t
+
+ line?||line
+ → boolean
+
+
+ lseg?||lseg
+ → boolean
+
+
+ Are lines parallel?
+
+
+ lseg '[(-1,0),(1,0)]' ?|| lseg '[(-1,2),(1,2)]'
+ → t
+
+ geometric_type~=geometric_type
+ → boolean
+
+
+ Are these objects the same?
+ Available for point, box,
+ polygon, circle.
+
+
+ polygon '((0,0),(1,1))' ~= polygon '((1,1),(0,0))'
+ → t
+
[a] “Rotating” a
+ box with these operators only moves its corner points: the box is
+ still considered to have sides parallel to the axes. Hence the box's
+ size is not preserved, as a true rotation would do.
Caution
+ Note that the “same as” operator, ~=,
+ represents the usual notion of equality for the point,
+ box, polygon, and circle types.
+ Some of the geometric types also have an = operator, but
+ = compares for equal areas only.
+ The other scalar comparison operators (<= and so
+ on), where available for these types, likewise compare areas.
+
Note
+ Before PostgreSQL 14, the point
+ is strictly below/above comparison operators point
+ <<|point and point
+ |>>point were respectively
+ called <^ and >^. These
+ names are still available, but are deprecated and will eventually be
+ removed.
+
+ Computes area.
+ Available for box, path, circle.
+ A path input must be closed, else NULL is returned.
+ Also, if the path is self-intersecting, the result may be
+ meaningless.
+
+
+ area(box '(2,2),(0,0)')
+ → 4
+
+
+ center ( geometric_type )
+ → point
+
+
+ Computes center point.
+ Available for box, circle.
+
+
+ center(box '(1,2),(0,0)')
+ → (0.5,1)
+
+
+ diagonal ( box )
+ → lseg
+
+
+ Extracts box's diagonal as a line segment
+ (same as lseg(box)).
+
+ Converts polygon to circle. The circle's center is the mean of the
+ positions of the polygon's points, and the radius is the average
+ distance of the polygon's points from that center.
+
+ It is possible to access the two component numbers of a point
+ as though the point were an array with indexes 0 and 1. For example, if
+ t.p is a point column then
+ SELECT p[0] FROM t retrieves the X coordinate and
+ UPDATE t SET p[1] = ... changes the Y coordinate.
+ In the same way, a value of type box or lseg can be treated
+ as an array of two point values.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-info.html b/pgsql/doc/postgresql/html/functions-info.html
new file mode 100644
index 0000000000000000000000000000000000000000..b62e418c9df6f71c51f425b0c9371cee4705c878
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-info.html
@@ -0,0 +1,1914 @@
+
+9.26. System Information Functions and Operators
+ Table 9.67 shows several
+ functions that extract session and system information.
+
+ In addition to the functions listed in this section, there are a number of
+ functions related to the statistics system that also provide system
+ information. See Section 28.2.25 for more
+ information.
+
Table 9.67. Session Information Functions
+ Function
+
+
+ Description
+
+
+ current_catalog
+ → name
+
+
+
+ current_database ()
+ → name
+
+
+ Returns the name of the current database. (Databases are
+ called “catalogs” in the SQL standard,
+ so current_catalog is the standard's
+ spelling.)
+
+
+ current_query ()
+ → text
+
+
+ Returns the text of the currently executing query, as submitted
+ by the client (which might contain more than one statement).
+
+
+ current_role
+ → name
+
+
+ This is equivalent to current_user.
+
+
+
+ current_schema
+ → name
+
+
+ current_schema ()
+ → name
+
+
+ Returns the name of the schema that is first in the search path (or a
+ null value if the search path is empty). This is the schema that will
+ be used for any tables or other named objects that are created without
+ specifying a target schema.
+
+ Returns an array of the names of all schemas presently in the
+ effective search path, in their priority order. (Items in the current
+ search_path setting that do not correspond to
+ existing, searchable schemas are omitted.) If the Boolean argument
+ is true, then implicitly-searched system schemas
+ such as pg_catalog are included in the result.
+
+
+
+ current_user
+ → name
+
+
+ Returns the user name of the current execution context.
+
+
+ inet_client_addr ()
+ → inet
+
+
+ Returns the IP address of the current client,
+ or NULL if the current connection is via a
+ Unix-domain socket.
+
+
+ inet_client_port ()
+ → integer
+
+
+ Returns the IP port number of the current client,
+ or NULL if the current connection is via a
+ Unix-domain socket.
+
+
+ inet_server_addr ()
+ → inet
+
+
+ Returns the IP address on which the server accepted the current
+ connection,
+ or NULL if the current connection is via a
+ Unix-domain socket.
+
+
+ inet_server_port ()
+ → integer
+
+
+ Returns the IP port number on which the server accepted the current
+ connection,
+ or NULL if the current connection is via a
+ Unix-domain socket.
+
+
+ pg_backend_pid ()
+ → integer
+
+
+ Returns the process ID of the server process attached to the current
+ session.
+
+
+ pg_blocking_pids ( integer )
+ → integer[]
+
+
+ Returns an array of the process ID(s) of the sessions that are
+ blocking the server process with the specified process ID from
+ acquiring a lock, or an empty array if there is no such server process
+ or it is not blocked.
+
+
+ One server process blocks another if it either holds a lock that
+ conflicts with the blocked process's lock request (hard block), or is
+ waiting for a lock that would conflict with the blocked process's lock
+ request and is ahead of it in the wait queue (soft block). When using
+ parallel queries the result always lists client-visible process IDs
+ (that is, pg_backend_pid results) even if the
+ actual lock is held or awaited by a child worker process. As a result
+ of that, there may be duplicated PIDs in the result. Also note that
+ when a prepared transaction holds a conflicting lock, it will be
+ represented by a zero process ID.
+
+
+ Frequent calls to this function could have some impact on database
+ performance, because it needs exclusive access to the lock manager's
+ shared state for a short time.
+
+
+ pg_conf_load_time ()
+ → timestamp with time zone
+
+
+ Returns the time when the server configuration files were last loaded.
+ If the current session was alive at the time, this will be the time
+ when the session itself re-read the configuration files (so the
+ reading will vary a little in different sessions). Otherwise it is
+ the time when the postmaster process re-read the configuration files.
+
+ Returns the path name of the log file currently in use by the logging
+ collector. The path includes the log_directory
+ directory and the individual log file name. The result
+ is NULL if the logging collector is disabled.
+ When multiple log files exist, each in a different
+ format, pg_current_logfile without an argument
+ returns the path of the file having the first format found in the
+ ordered list: stderr,
+ csvlog, jsonlog.
+ NULL is returned if no log file has any of these
+ formats.
+ To request information about a specific log file format, supply
+ either csvlog, jsonlog or
+ stderr as the
+ value of the optional parameter. The result is NULL
+ if the log format requested is not configured in
+ log_destination.
+ The result reflects the contents of
+ the current_logfiles file.
+
+
+ pg_my_temp_schema ()
+ → oid
+
+
+ Returns the OID of the current session's temporary schema, or zero if
+ it has none (because it has not created any temporary tables).
+
+
+ pg_is_other_temp_schema ( oid )
+ → boolean
+
+
+ Returns true if the given OID is the OID of another session's
+ temporary schema. (This can be useful, for example, to exclude other
+ sessions' temporary tables from a catalog display.)
+
+
+ pg_jit_available ()
+ → boolean
+
+
+ Returns true if a JIT compiler extension is
+ available (see Chapter 32) and the
+ jit configuration parameter is set to
+ on.
+
+
+ pg_listening_channels ()
+ → setof text
+
+
+ Returns the set of names of asynchronous notification channels that
+ the current session is listening to.
+
+ Returns the fraction (0–1) of the asynchronous notification
+ queue's maximum size that is currently occupied by notifications that
+ are waiting to be processed.
+ See LISTEN and NOTIFY
+ for more information.
+
+
+ pg_postmaster_start_time ()
+ → timestamp with time zone
+
+ Returns an array of the process ID(s) of the sessions that are blocking
+ the server process with the specified process ID from acquiring a safe
+ snapshot, or an empty array if there is no such server process or it
+ is not blocked.
+
+
+ A session running a SERIALIZABLE transaction blocks
+ a SERIALIZABLE READ ONLY DEFERRABLE transaction
+ from acquiring a snapshot until the latter determines that it is safe
+ to avoid taking any predicate locks. See
+ Section 13.2.3 for more information about
+ serializable and deferrable transactions.
+
+
+ Frequent calls to this function could have some impact on database
+ performance, because it needs access to the predicate lock manager's
+ shared state for a short time.
+
+
+ pg_trigger_depth ()
+ → integer
+
+
+ Returns the current nesting level
+ of PostgreSQL triggers (0 if not called,
+ directly or indirectly, from inside a trigger).
+
+
+ session_user
+ → name
+
+
+ Returns the session user's name.
+
+
+ system_user
+ → text
+
+
+ Returns the authentication method and the identity (if any) that the
+ user presented during the authentication cycle before they were
+ assigned a database role. It is represented as
+ auth_method:identity or
+ NULL if the user has not been authenticated (for
+ example if Trust authentication has
+ been used).
+
+
+ user
+ → name
+
+
+ This is equivalent to current_user.
+
+
+ version ()
+ → text
+
+
+ Returns a string describing the PostgreSQL
+ server's version. You can also get this information from
+ server_version, or for a machine-readable
+ version use server_version_num. Software
+ developers should use server_version_num (available
+ since 8.2) or PQserverVersion instead of
+ parsing the text version.
+
Note
+ current_catalog,
+ current_role,
+ current_schema,
+ current_user,
+ session_user,
+ and user have special syntactic status
+ in SQL: they must be called without trailing
+ parentheses. In PostgreSQL, parentheses can optionally be used with
+ current_schema, but not with the others.
+
+ The session_user is normally the user who initiated
+ the current database connection; but superusers can change this setting
+ with SET SESSION AUTHORIZATION.
+ The current_user is the user identifier
+ that is applicable for permission checking. Normally it is equal
+ to the session user, but it can be changed with
+ SET ROLE.
+ It also changes during the execution of
+ functions with the attribute SECURITY DEFINER.
+ In Unix parlance, the session user is the “real user” and
+ the current user is the “effective user”.
+ current_role and user are
+ synonyms for current_user. (The SQL standard draws
+ a distinction between current_role
+ and current_user, but PostgreSQL
+ does not, since it unifies users and roles into a single kind of entity.)
+
+ Table 9.68 lists functions that
+ allow querying object access privileges programmatically.
+ (See Section 5.7 for more information about
+ privileges.)
+ In these functions, the user whose privileges are being inquired about
+ can be specified by name or by OID
+ (pg_authid.oid), or if
+ the name is given as public then the privileges of the
+ PUBLIC pseudo-role are checked. Also, the user
+ argument can be omitted entirely, in which case
+ the current_user is assumed.
+ The object that is being inquired about can be specified either by name or
+ by OID, too. When specifying by name, a schema name can be included if
+ relevant.
+ The access privilege of interest is specified by a text string, which must
+ evaluate to one of the appropriate privilege keywords for the object's type
+ (e.g., SELECT). Optionally, WITH GRANT
+ OPTION can be added to a privilege type to test whether the
+ privilege is held with grant option. Also, multiple privilege types can be
+ listed separated by commas, in which case the result will be true if any of
+ the listed privileges is held. (Case of the privilege string is not
+ significant, and extra whitespace is allowed between but not within
+ privilege names.)
+ Some examples:
+
+SELECT has_table_privilege('myschema.mytable', 'select');
+SELECT has_table_privilege('joe', 'mytable', 'INSERT, SELECT WITH GRANT OPTION');
+
+
Table 9.68. Access Privilege Inquiry Functions
+ Function
+
+
+ Description
+
+
+ has_any_column_privilege (
+ [username or oid, ]
+ tabletext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for any column of table?
+ This succeeds either if the privilege is held for the whole table, or
+ if there is a column-level grant of the privilege for at least one
+ column.
+ Allowable privilege types are
+ SELECT, INSERT,
+ UPDATE, and REFERENCES.
+
+
+ has_column_privilege (
+ [username or oid, ]
+ tabletext or oid,
+ columntext or smallint,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for the specified table column?
+ This succeeds either if the privilege is held for the whole table, or
+ if there is a column-level grant of the privilege for the column.
+ The column can be specified by name or by attribute number
+ (pg_attribute.attnum).
+ Allowable privilege types are
+ SELECT, INSERT,
+ UPDATE, and REFERENCES.
+
+
+ has_database_privilege (
+ [username or oid, ]
+ databasetext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for database?
+ Allowable privilege types are
+ CREATE,
+ CONNECT,
+ TEMPORARY, and
+ TEMP (which is equivalent to
+ TEMPORARY).
+
+
+ has_foreign_data_wrapper_privilege (
+ [username or oid, ]
+ fdwtext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for foreign-data wrapper?
+ The only allowable privilege type is USAGE.
+
+
+ has_function_privilege (
+ [username or oid, ]
+ functiontext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for function?
+ The only allowable privilege type is EXECUTE.
+
+
+ When specifying a function by name rather than by OID, the allowed
+ input is the same as for the regprocedure data type (see
+ Section 8.19).
+ An example is:
+
+ Does user have privilege for configuration parameter?
+ The parameter name is case-insensitive.
+ Allowable privilege types are SET
+ and ALTER SYSTEM.
+
+
+ has_schema_privilege (
+ [username or oid, ]
+ schematext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for schema?
+ Allowable privilege types are
+ CREATE and
+ USAGE.
+
+
+ has_sequence_privilege (
+ [username or oid, ]
+ sequencetext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for sequence?
+ Allowable privilege types are
+ USAGE,
+ SELECT, and
+ UPDATE.
+
+
+ has_server_privilege (
+ [username or oid, ]
+ servertext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for foreign server?
+ The only allowable privilege type is USAGE.
+
+
+ has_table_privilege (
+ [username or oid, ]
+ tabletext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for table?
+ Allowable privilege types
+ are SELECT, INSERT,
+ UPDATE, DELETE,
+ TRUNCATE, REFERENCES,
+ and TRIGGER.
+
+
+ has_tablespace_privilege (
+ [username or oid, ]
+ tablespacetext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for tablespace?
+ The only allowable privilege type is CREATE.
+
+
+ has_type_privilege (
+ [username or oid, ]
+ typetext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for data type?
+ The only allowable privilege type is USAGE.
+ When specifying a type by name rather than by OID, the allowed input
+ is the same as for the regtype data type (see
+ Section 8.19).
+
+
+ pg_has_role (
+ [username or oid, ]
+ roletext or oid,
+ privilegetext )
+ → boolean
+
+
+ Does user have privilege for role?
+ Allowable privilege types are
+ MEMBER, USAGE,
+ and SET.
+ MEMBER denotes direct or indirect membership in
+ the role without regard to what specific privileges may be conferred.
+ USAGE denotes whether the privileges of the role
+ are immediately available without doing SET ROLE,
+ while SET denotes whether it is possible to change
+ to the role using the SET ROLE command.
+ This function does not allow the special case of
+ setting user to public,
+ because the PUBLIC pseudo-role can never be a member of real roles.
+
+
+ row_security_active (
+ tabletext or oid )
+ → boolean
+
+
+ Is row-level security active for the specified table in the context of
+ the current user and current environment?
+
+ Table 9.69 shows the operators
+ available for the aclitem type, which is the catalog
+ representation of access privileges. See Section 5.7
+ for information about how to read access privilege values.
+
Table 9.69. aclitem Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+
+ aclitem=aclitem
+ → boolean
+
+
+ Are aclitems equal? (Notice that
+ type aclitem lacks the usual set of comparison
+ operators; it has only equality. In turn, aclitem
+ arrays can only be compared for equality.)
+
+
+ 'calvin=r*w/hobbes'::aclitem = 'calvin=r*w*/hobbes'::aclitem
+ → f
+
+
+ aclitem[]@>aclitem
+ → boolean
+
+
+ Does array contain the specified privileges? (This is true if there
+ is an array entry that matches the aclitem's grantee and
+ grantor, and has at least the specified set of privileges.)
+
+
+ '{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] @> 'calvin=r*/hobbes'::aclitem
+ → t
+
+ aclitem[]~aclitem
+ → boolean
+
+
+ This is a deprecated alias for @>.
+
+
+ '{calvin=r*w/hobbes,hobbes=r*w*/postgres}'::aclitem[] ~ 'calvin=r*/hobbes'::aclitem
+ → t
+
+ Table 9.70 shows some additional
+ functions to manage the aclitem type.
+
+ Constructs an aclitem array holding the default access
+ privileges for an object of type type belonging
+ to the role with OID ownerId. This represents
+ the access privileges that will be assumed when an object's ACL entry
+ is null. (The default access privileges are described in
+ Section 5.7.)
+ The type parameter must be one of
+ 'c' for COLUMN,
+ 'r' for TABLE and table-like objects,
+ 's' for SEQUENCE,
+ 'd' for DATABASE,
+ 'f' for FUNCTION or PROCEDURE,
+ 'l' for LANGUAGE,
+ 'L' for LARGE OBJECT,
+ 'n' for SCHEMA,
+ 'p' for PARAMETER,
+ 't' for TABLESPACE,
+ 'F' for FOREIGN DATA WRAPPER,
+ 'S' for FOREIGN SERVER,
+ or
+ 'T' for TYPE or DOMAIN.
+
+ Returns the aclitem array as a set of rows.
+ If the grantee is the pseudo-role PUBLIC, it is represented by zero in
+ the grantee column. Each granted privilege is
+ represented as SELECT, INSERT,
+ etc (see Table 5.1 for a full list).
+ Note that each privilege is broken out as a separate row, so
+ only one keyword appears in the privilege_type
+ column.
+
+ Constructs an aclitem with the given properties.
+ privileges is a comma-separated list of
+ privilege names such as SELECT,
+ INSERT, etc, all of which are set in the
+ result. (Case of the privilege string is not significant, and
+ extra whitespace is allowed between but not within privilege
+ names.)
+
+ Table 9.71 shows functions that
+ determine whether a certain object is visible in the
+ current schema search path.
+ For example, a table is said to be visible if its
+ containing schema is in the search path and no table of the same
+ name appears earlier in the search path. This is equivalent to the
+ statement that the table can be referenced by name without explicit
+ schema qualification. Thus, to list the names of all visible tables:
+
+SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
+
+ For functions and operators, an object in the search path is said to be
+ visible if there is no object of the same name and argument data
+ type(s) earlier in the path. For operator classes and families,
+ both the name and the associated index access method are considered.
+
+ Is table visible in search path?
+ (This works for all types of relations, including views, materialized
+ views, indexes, sequences and foreign tables.)
+
+ Is text search template visible in search path?
+
+
+ pg_type_is_visible ( typeoid )
+ → boolean
+
+
+ Is type (or domain) visible in search path?
+
+ All these functions require object OIDs to identify the object to be
+ checked. If you want to test an object by name, it is convenient to use
+ the OID alias types (regclass, regtype,
+ regprocedure, regoperator, regconfig,
+ or regdictionary),
+ for example:
+
+ Note that it would not make much sense to test a non-schema-qualified
+ type name in this way — if the name can be recognized at all, it must be visible.
+
+ Returns the SQL name for a data type that is identified by its type
+ OID and possibly a type modifier. Pass NULL for the type modifier if
+ no specific modifier is known.
+
+ Converts the supplied encoding name into an integer representing the
+ internal identifier used in some system catalog tables.
+ Returns -1 if an unknown encoding name is provided.
+
+
+ pg_encoding_to_char ( encodinginteger )
+ → name
+
+
+ Converts the integer used as the internal identifier of an encoding in some
+ system catalog tables into a human-readable string.
+ Returns an empty string if an invalid encoding number is provided.
+
+ Returns a set of records describing the foreign key relationships
+ that exist within the PostgreSQL system
+ catalogs.
+ The fktable column contains the name of the
+ referencing catalog, and the fkcols column
+ contains the name(s) of the referencing column(s). Similarly,
+ the pktable column contains the name of the
+ referenced catalog, and the pkcols column
+ contains the name(s) of the referenced column(s).
+ If is_array is true, the last referencing
+ column is an array, each of whose elements should match some entry
+ in the referenced catalog.
+ If is_opt is true, the referencing column(s)
+ are allowed to contain zeroes instead of a valid reference.
+
+ Decompiles the internal form of an expression stored in the system
+ catalogs, such as the default value for a column. If the expression
+ might contain Vars, specify the OID of the relation they refer to as
+ the second parameter; if no Vars are expected, passing zero is
+ sufficient.
+
+
+ pg_get_functiondef ( funcoid )
+ → text
+
+
+ Reconstructs the creating command for a function or procedure.
+ (This is a decompiled reconstruction, not the original text
+ of the command.)
+ The result is a complete CREATE OR REPLACE FUNCTION
+ or CREATE OR REPLACE PROCEDURE statement.
+
+
+ pg_get_function_arguments ( funcoid )
+ → text
+
+
+ Reconstructs the argument list of a function or procedure, in the form
+ it would need to appear in within CREATE FUNCTION
+ (including default values).
+
+
+ pg_get_function_identity_arguments ( funcoid )
+ → text
+
+
+ Reconstructs the argument list necessary to identify a function or
+ procedure, in the form it would need to appear in within commands such
+ as ALTER FUNCTION. This form omits default values.
+
+
+ pg_get_function_result ( funcoid )
+ → text
+
+
+ Reconstructs the RETURNS clause of a function, in
+ the form it would need to appear in within CREATE
+ FUNCTION. Returns NULL for a procedure.
+
+ Reconstructs the creating command for an index.
+ (This is a decompiled reconstruction, not the original text
+ of the command.) If column is supplied and is
+ not zero, only the definition of that column is reconstructed.
+
+ Returns a set of records describing the SQL keywords recognized by the
+ server. The word column contains the
+ keyword. The catcode column contains a
+ category code: U for an unreserved
+ keyword, C for a keyword that can be a column
+ name, T for a keyword that can be a type or
+ function name, or R for a fully reserved keyword.
+ The barelabel column
+ contains true if the keyword can be used as
+ a “bare” column label in SELECT lists,
+ or false if it can only be used
+ after AS.
+ The catdesc column contains a
+ possibly-localized string describing the keyword's category.
+ The baredesc column contains a
+ possibly-localized string describing the keyword's column label status.
+
+
+ pg_get_partkeydef ( tableoid )
+ → text
+
+
+ Reconstructs the definition of a partitioned table's partition
+ key, in the form it would have in the PARTITION
+ BY clause of CREATE TABLE.
+ (This is a decompiled reconstruction, not the original text
+ of the command.)
+
+ Returns the name of the sequence associated with a column,
+ or NULL if no sequence is associated with the column.
+ If the column is an identity column, the associated sequence is the
+ sequence internally created for that column.
+ For columns created using one of the serial types
+ (serial, smallserial, bigserial),
+ it is the sequence created for that serial column definition.
+ In the latter case, the association can be modified or removed
+ with ALTER SEQUENCE OWNED BY.
+ (This function probably should have been
+ called pg_get_owned_sequence; its current name
+ reflects the fact that it has historically been used with serial-type
+ columns.) The first parameter is a table name with optional
+ schema, and the second parameter is a column name. Because the first
+ parameter potentially contains both schema and table names, it is
+ parsed per usual SQL rules, meaning it is lower-cased by default.
+ The second parameter, being just a column name, is treated literally
+ and so has its case preserved. The result is suitably formatted
+ for passing to the sequence functions (see
+ Section 9.17).
+
+
+ A typical use is in reading the current value of the sequence for an
+ identity or serial column, for example:
+
+
+ pg_get_statisticsobjdef ( statobjoid )
+ → text
+
+
+ Reconstructs the creating command for an extended statistics object.
+ (This is a decompiled reconstruction, not the original text
+ of the command.)
+
+ Reconstructs the underlying SELECT command for a
+ view or materialized view. (This is a decompiled reconstruction, not
+ the original text of the command.)
+
+ pg_get_viewdef ( viewoid, wrap_columninteger )
+ → text
+
+
+ Reconstructs the underlying SELECT command for a
+ view or materialized view. (This is a decompiled reconstruction, not
+ the original text of the command.) In this form of the function,
+ pretty-printing is always enabled, and long lines are wrapped to try
+ to keep them shorter than the specified number of columns.
+
+ Reconstructs the underlying SELECT command for a
+ view or materialized view, working from a textual name for the view
+ rather than its OID. (This is deprecated; use the OID variant
+ instead.)
+
+ Tests whether an index column has the named property.
+ Common index column properties are listed in
+ Table 9.73.
+ (Note that extension access methods can define additional property
+ names for their indexes.)
+ NULL is returned if the property name is not known
+ or does not apply to the particular object, or if the OID or column
+ number does not identify a valid object.
+
+ Tests whether an index has the named property.
+ Common index properties are listed in
+ Table 9.74.
+ (Note that extension access methods can define additional property
+ names for their indexes.)
+ NULL is returned if the property name is not known
+ or does not apply to the particular object, or if the OID does not
+ identify a valid object.
+
+ Tests whether an index access method has the named property.
+ Access method properties are listed in
+ Table 9.75.
+ NULL is returned if the property name is not known
+ or does not apply to the particular object, or if the OID does not
+ identify a valid object.
+
+ Returns an array of the flags associated with the given GUC, or
+ NULL if it does not exist. The result is
+ an empty array if the GUC exists but there are no flags to show.
+ Only the most useful flags listed in
+ Table 9.76 are exposed.
+
+ Returns the set of OIDs of databases that have objects stored in the
+ specified tablespace. If this function returns any rows, the
+ tablespace is not empty and cannot be dropped. To identify the specific
+ objects populating the tablespace, you will need to connect to the
+ database(s) identified by pg_tablespace_databases
+ and query their pg_class catalogs.
+
+
+ pg_tablespace_location ( tablespaceoid )
+ → text
+
+
+ Returns the file system path that this tablespace is located in.
+
+
+ pg_typeof ( "any" )
+ → regtype
+
+
+ Returns the OID of the data type of the value that is passed to it.
+ This can be helpful for troubleshooting or dynamically constructing
+ SQL queries. The function is declared as
+ returning regtype, which is an OID alias type (see
+ Section 8.19); this means that it is the same as an
+ OID for comparison purposes but displays as a type name.
+
+
+ For example:
+
+SELECT pg_typeof(33);
+ pg_typeof
+-----------
+ integer
+
+SELECT typlen FROM pg_type WHERE oid = pg_typeof(33);
+ typlen
+--------
+ 4
+
+
+
+ COLLATION FOR ( "any" )
+ → text
+
+
+ Returns the name of the collation of the value that is passed to it.
+ The value is quoted and schema-qualified if necessary. If no
+ collation was derived for the argument expression,
+ then NULL is returned. If the argument is not of a
+ collatable data type, then an error is raised.
+
+
+ For example:
+
+SELECT collation for (description) FROM pg_description LIMIT 1;
+ pg_collation_for
+------------------
+ "default"
+
+SELECT collation for ('foo' COLLATE "de_DE");
+ pg_collation_for
+------------------
+ "de_DE"
+
+
+
+ to_regclass ( text )
+ → regclass
+
+
+ Translates a textual relation name to its OID. A similar result is
+ obtained by casting the string to type regclass (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+
+ to_regcollation ( text )
+ → regcollation
+
+
+ Translates a textual collation name to its OID. A similar result is
+ obtained by casting the string to type regcollation (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+
+ to_regnamespace ( text )
+ → regnamespace
+
+
+ Translates a textual schema name to its OID. A similar result is
+ obtained by casting the string to type regnamespace (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+
+ to_regoper ( text )
+ → regoper
+
+
+ Translates a textual operator name to its OID. A similar result is
+ obtained by casting the string to type regoper (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found or is ambiguous.
+
+
+ to_regoperator ( text )
+ → regoperator
+
+
+ Translates a textual operator name (with parameter types) to its OID. A similar result is
+ obtained by casting the string to type regoperator (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+
+ to_regproc ( text )
+ → regproc
+
+
+ Translates a textual function or procedure name to its OID. A similar result is
+ obtained by casting the string to type regproc (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found or is ambiguous.
+
+
+ to_regprocedure ( text )
+ → regprocedure
+
+
+ Translates a textual function or procedure name (with argument types) to its OID. A similar result is
+ obtained by casting the string to type regprocedure (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+
+ to_regrole ( text )
+ → regrole
+
+
+ Translates a textual role name to its OID. A similar result is
+ obtained by casting the string to type regrole (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+
+ to_regtype ( text )
+ → regtype
+
+
+ Translates a textual type name to its OID. A similar result is
+ obtained by casting the string to type regtype (see
+ Section 8.19); however, this function will return
+ NULL rather than throwing an error if the name is
+ not found.
+
+ Most of the functions that reconstruct (decompile) database objects
+ have an optional pretty flag, which
+ if true causes the result to
+ be “pretty-printed”. Pretty-printing suppresses unnecessary
+ parentheses and adds whitespace for legibility.
+ The pretty-printed format is more readable, but the default format
+ is more likely to be interpreted the same way by future versions of
+ PostgreSQL; so avoid using pretty-printed output
+ for dump purposes. Passing false for
+ the pretty parameter yields the same result as
+ omitting the parameter.
+
Table 9.73. Index Column Properties
Name
Description
asc
Does the column sort in ascending order on a forward scan?
+
desc
Does the column sort in descending order on a forward scan?
+
nulls_first
Does the column sort with nulls first on a forward scan?
+
nulls_last
Does the column sort with nulls last on a forward scan?
+
orderable
Does the column possess any defined sort ordering?
+
distance_orderable
Can the column be scanned in order by a “distance”
+ operator, for example ORDER BY col <-> constant ?
+
returnable
Can the column value be returned by an index-only scan?
+
search_array
Does the column natively support col = ANY(array)
+ searches?
+
search_nulls
Does the column support IS NULL and
+ IS NOT NULL searches?
+
Table 9.74. Index Properties
Name
Description
clusterable
Can the index be used in a CLUSTER command?
+
index_scan
Does the index support plain (non-bitmap) scans?
+
bitmap_scan
Does the index support bitmap scans?
+
backward_scan
Can the scan direction be changed in mid-scan (to
+ support FETCH BACKWARD on a cursor without
+ needing materialization)?
+
Table 9.75. Index Access Method Properties
Name
Description
can_order
Does the access method support ASC,
+ DESC and related keywords in
+ CREATE INDEX?
+
can_unique
Does the access method support unique indexes?
+
can_multi_col
Does the access method support indexes with multiple columns?
+
can_exclude
Does the access method support exclusion constraints?
+
can_include
Does the access method support the INCLUDE
+ clause of CREATE INDEX?
+
Table 9.76. GUC Flags
Flag
Description
EXPLAIN
Parameters with this flag are included in
+ EXPLAIN (SETTINGS) commands.
+
NO_SHOW_ALL
Parameters with this flag are excluded from
+ SHOW ALL commands.
+
NO_RESET
Parameters with this flag do not support
+ RESET commands.
+
NO_RESET_ALL
Parameters with this flag are excluded from
+ RESET ALL commands.
+
NOT_IN_SAMPLE
Parameters with this flag are not included in
+ postgresql.conf by default.
+
RUNTIME_COMPUTED
Parameters with this flag are runtime-computed ones.
+
9.26.5. Object Information and Addressing Functions #
+ Table 9.77 lists functions related to
+ database object identification and addressing.
+
Table 9.77. Object Information and Addressing Functions
+ Returns a textual description of a database object identified by
+ catalog OID, object OID, and sub-object ID (such as a column number
+ within a table; the sub-object ID is zero when referring to a whole
+ object). This description is intended to be human-readable, and might
+ be translated, depending on server configuration. This is especially
+ useful to determine the identity of an object referenced in the
+ pg_depend catalog. This function returns
+ NULL values for undefined objects.
+
+ Returns a row containing enough information to uniquely identify the
+ database object specified by catalog OID, object OID and sub-object
+ ID.
+ This information is intended to be machine-readable, and is never
+ translated.
+ type identifies the type of database object;
+ schema is the schema name that the object
+ belongs in, or NULL for object types that do not
+ belong to schemas;
+ name is the name of the object, quoted if
+ necessary, if the name (along with schema name, if pertinent) is
+ sufficient to uniquely identify the object,
+ otherwise NULL;
+ identity is the complete object identity, with
+ the precise format depending on object type, and each name within the
+ format being schema-qualified and quoted as necessary. Undefined
+ objects are identified with NULL values.
+
+ Returns a row containing enough information to uniquely identify the
+ database object specified by catalog OID, object OID and sub-object
+ ID.
+ The returned information is independent of the current server, that
+ is, it could be used to identify an identically named object in
+ another server.
+ type identifies the type of database object;
+ object_names and
+ object_args
+ are text arrays that together form a reference to the object.
+ These three values can be passed
+ to pg_get_object_address to obtain the internal
+ address of the object.
+
+ Returns a row containing enough information to uniquely identify the
+ database object specified by a type code and object name and argument
+ arrays.
+ The returned values are the ones that would be used in system catalogs
+ such as pg_depend; they can be passed to
+ other system functions such as pg_describe_object
+ or pg_identify_object.
+ classid is the OID of the system catalog
+ containing the object;
+ objid is the OID of the object itself, and
+ objsubid is the sub-object ID, or zero if none.
+ This function is the inverse
+ of pg_identify_object_as_address.
+ Undefined objects are identified with NULL values.
+
+ The functions shown in Table 9.78
+ extract comments previously stored with the COMMENT
+ command. A null value is returned if no
+ comment could be found for the specified parameters.
+
+ Returns the comment for a table column, which is specified by the OID
+ of its table and its column number.
+ (obj_description cannot be used for table
+ columns, since columns do not have OIDs of their own.)
+
+ Returns the comment for a database object specified by its OID and the
+ name of the containing system catalog. For
+ example, obj_description(123456, 'pg_class') would
+ retrieve the comment for the table with OID 123456.
+
+ obj_description ( objectoid )
+ → text
+
+
+ Returns the comment for a database object specified by its OID alone.
+ This is deprecated since there is no guarantee
+ that OIDs are unique across different system catalogs; therefore, the
+ wrong comment might be returned.
+
+ Returns the comment for a shared database object specified by its OID
+ and the name of the containing system catalog. This is just
+ like obj_description except that it is used for
+ retrieving comments on shared objects (that is, databases, roles, and
+ tablespaces). Some system catalogs are global to all databases within
+ each cluster, and the descriptions for objects in them are stored
+ globally as well.
+
+ Tests whether the given string is valid
+ input for the specified data type, returning true or false.
+
+
+ This function will only work as desired if the data type's input
+ function has been updated to report invalid input as
+ a “soft” error. Otherwise, invalid input will abort
+ the transaction, just as if the string had been cast to the type
+ directly.
+
+
+ pg_input_is_valid('42', 'integer')
+ → t
+
+
+ pg_input_is_valid('42000000000', 'integer')
+ → f
+
+
+ pg_input_is_valid('1234.567', 'numeric(7,4)')
+ → f
+
+ Tests whether the given string is valid
+ input for the specified data type; if not, return the details of
+ the error that would have been thrown. If the input is valid, the
+ results are NULL. The inputs are the same as
+ for pg_input_is_valid.
+
+
+ This function will only work as desired if the data type's input
+ function has been updated to report invalid input as
+ a “soft” error. Otherwise, invalid input will abort
+ the transaction, just as if the string had been cast to the type
+ directly.
+
+
+ select * from pg_input_error_info('42000000000', 'integer')
+ →
+
+ message | detail | hint | sql_error_code
+------------------------------------------------------+--------+------+----------------
+ value "42000000000" is out of range for type integer | | | 22003
+
+
+
+ select message, detail from pg_input_error_info('1234.567', 'numeric(7,4)')
+ →
+
+ message | detail
+------------------------+-----------------------------------------------------------------------------------
+ numeric field overflow | A field with precision 7, scale 4 must round to an absolute value less than 10^3.
+
+
9.26.8. Transaction ID and Snapshot Information Functions #
+ The functions shown in Table 9.80
+ provide server transaction information in an exportable form. The main
+ use of these functions is to determine which transactions were committed
+ between two snapshots.
+
Table 9.80. Transaction ID and Snapshot Information Functions
+ Function
+
+
+ Description
+
+
+ pg_current_xact_id ()
+ → xid8
+
+
+ Returns the current transaction's ID. It will assign a new one if the
+ current transaction does not have one already (because it has not
+ performed any database updates); see Section 74.1 for details. If executed in a
+ subtransaction, this will return the top-level transaction ID;
+ see Section 74.3 for details.
+
+
+ pg_current_xact_id_if_assigned ()
+ → xid8
+
+
+ Returns the current transaction's ID, or NULL if no
+ ID is assigned yet. (It's best to use this variant if the transaction
+ might otherwise be read-only, to avoid unnecessary consumption of an
+ XID.)
+ If executed in a subtransaction, this will return the top-level
+ transaction ID.
+
+
+ pg_xact_status ( xid8 )
+ → text
+
+
+ Reports the commit status of a recent transaction.
+ The result is one of in progress,
+ committed, or aborted,
+ provided that the transaction is recent enough that the system retains
+ the commit status of that transaction.
+ If it is old enough that no references to the transaction survive in
+ the system and the commit status information has been discarded, the
+ result is NULL.
+ Applications might use this function, for example, to determine
+ whether their transaction committed or aborted after the application
+ and database server become disconnected while
+ a COMMIT is in progress.
+ Note that prepared transactions are reported as in
+ progress; applications must check pg_prepared_xacts
+ if they need to determine whether a transaction ID belongs to a
+ prepared transaction.
+
+
+ pg_current_snapshot ()
+ → pg_snapshot
+
+
+ Returns a current snapshot, a data structure
+ showing which transaction IDs are now in-progress.
+ Only top-level transaction IDs are included in the snapshot;
+ subtransaction IDs are not shown; see Section 74.3
+ for details.
+
+ Is the given transaction ID visible according
+ to this snapshot (that is, was it completed before the snapshot was
+ taken)? Note that this function will not give the correct answer for
+ a subtransaction ID (subxid); see Section 74.3 for
+ details.
+
+ The internal transaction ID type xid is 32 bits wide and
+ wraps around every 4 billion transactions. However,
+ the functions shown in Table 9.80 use a
+ 64-bit type xid8 that does not wrap around during the life
+ of an installation and can be converted to xid by casting if
+ required; see Section 74.1 for details.
+ The data type pg_snapshot stores information about
+ transaction ID visibility at a particular moment in time. Its components
+ are described in Table 9.81.
+ pg_snapshot's textual representation is
+ xmin:xmax:xip_list.
+ For example 10:20:10,14,15 means
+ xmin=10, xmax=20, xip_list=10, 14, 15.
+
Table 9.81. Snapshot Components
Name
Description
xmin
+ Lowest transaction ID that was still active. All transaction IDs
+ less than xmin are either committed and visible,
+ or rolled back and dead.
+
xmax
+ One past the highest completed transaction ID. All transaction IDs
+ greater than or equal to xmax had not yet
+ completed as of the time of the snapshot, and thus are invisible.
+
xip_list
+ Transactions in progress at the time of the snapshot. A transaction
+ ID that is xmin <= X <
+ xmax and not in this list was already completed at the time
+ of the snapshot, and thus is either visible or dead according to its
+ commit status. This list does not include the transaction IDs of
+ subtransactions (subxids).
+
+ In releases of PostgreSQL before 13 there was
+ no xid8 type, so variants of these functions were provided
+ that used bigint to represent a 64-bit XID, with a
+ correspondingly distinct snapshot data type txid_snapshot.
+ These older functions have txid in their names. They
+ are still supported for backward compatibility, but may be removed from a
+ future release. See Table 9.82.
+
Table 9.82. Deprecated Transaction ID and Snapshot Information Functions
9.26.9. Committed Transaction Information Functions #
+ The functions shown in Table 9.83
+ provide information about when past transactions were committed.
+ They only provide useful data when the
+ track_commit_timestamp configuration option is
+ enabled, and only for transactions that were committed after it was
+ enabled. Commit timestamp information is routinely removed during
+ vacuum.
+
Table 9.83. Committed Transaction Information Functions
+ Function
+
+
+ Description
+
+
+ pg_xact_commit_timestamp ( xid )
+ → timestamp with time zone
+
+
+ Returns the commit timestamp of a transaction.
+
+
+ pg_xact_commit_timestamp_origin ( xid )
+ → record
+ ( timestamptimestamp with time zone,
+ roidentoid)
+
+
+ Returns the commit timestamp and replication origin of a transaction.
+
+
+ pg_last_committed_xact ()
+ → record
+ ( xidxid,
+ timestamptimestamp with time zone,
+ roidentoid )
+
+
+ Returns the transaction ID, commit timestamp and replication origin
+ of the latest committed transaction.
+
+ The functions shown in Table 9.84
+ print information initialized during initdb, such
+ as the catalog version. They also show information about write-ahead
+ logging and checkpoint processing. This information is cluster-wide,
+ not specific to any one database. These functions provide most of the same
+ information, from the same source, as the
+ pg_controldata application.
+
Table 9.84. Control Data Functions
+ Function
+
+
+ Description
+
+
+ age ( xid )
+ → integer
+
+
+ Returns the number of transactions between the supplied
+ transaction id and the current transaction counter.
+
+
+ mxid_age ( xid )
+ → integer
+
+
+ Returns the number of multixacts IDs between the supplied
+ multixact ID and the current multixacts counter.
+
+
+ pg_control_checkpoint ()
+ → record
+
+
+ Returns information about current checkpoint state, as shown in
+ Table 9.85.
+
+
+ pg_control_system ()
+ → record
+
+
+ Returns information about current control file state, as shown in
+ Table 9.86.
+
+
+ pg_control_init ()
+ → record
+
+
+ Returns information about cluster initialization state, as shown in
+ Table 9.87.
+
+
+ pg_control_recovery ()
+ → record
+
+
+ Returns information about recovery state, as shown in
+ Table 9.88.
+
Table 9.85. pg_control_checkpoint Output Columns
Column Name
Data Type
checkpoint_lsn
pg_lsn
redo_lsn
pg_lsn
redo_wal_file
text
timeline_id
integer
prev_timeline_id
integer
full_page_writes
boolean
next_xid
text
next_oid
oid
next_multixact_id
xid
next_multi_offset
xid
oldest_xid
xid
oldest_xid_dbid
oid
oldest_active_xid
xid
oldest_multi_xid
xid
oldest_multi_dbid
oid
oldest_commit_ts_xid
xid
newest_commit_ts_xid
xid
checkpoint_time
timestamp with time zone
Table 9.86. pg_control_system Output Columns
Column Name
Data Type
pg_control_version
integer
catalog_version_no
integer
system_identifier
bigint
pg_control_last_modified
timestamp with time zone
Table 9.87. pg_control_init Output Columns
Column Name
Data Type
max_data_alignment
integer
database_block_size
integer
blocks_per_segment
integer
wal_block_size
integer
bytes_per_wal_segment
integer
max_identifier_length
integer
max_index_columns
integer
max_toast_chunk_size
integer
large_object_chunk_size
integer
float8_pass_by_value
boolean
data_page_checksum_version
integer
Table 9.88. pg_control_recovery Output Columns
Column Name
Data Type
min_recovery_end_lsn
pg_lsn
min_recovery_end_timeline
integer
backup_start_lsn
pg_lsn
backup_end_lsn
pg_lsn
end_of_backup_record_required
boolean
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-json.html b/pgsql/doc/postgresql/html/functions-json.html
new file mode 100644
index 0000000000000000000000000000000000000000..28dab627b91ca65b0bbd5891336d2e42ea71dc9f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-json.html
@@ -0,0 +1,1927 @@
+
+9.16. JSON Functions and Operators
+ functions and operators for processing and creating JSON data
+
+ the SQL/JSON path language
+
+
+ To provide native support for JSON data types within the SQL environment,
+ PostgreSQL implements the
+ SQL/JSON data model.
+ This model comprises sequences of items. Each item can hold SQL scalar
+ values, with an additional SQL/JSON null value, and composite data structures
+ that use JSON arrays and objects. The model is a formalization of the implied
+ data model in the JSON specification
+ RFC 7159.
+
+ SQL/JSON allows you to handle JSON data alongside regular SQL data,
+ with transaction support, including:
+
+
+ Uploading JSON data into the database and storing it in
+ regular SQL columns as character or binary strings.
+
+ Generating JSON objects and arrays from relational data.
+
+ Querying JSON data using SQL/JSON query functions and
+ SQL/JSON path language expressions.
+
+
+ To learn more about the SQL/JSON standard, see
+ [sqltr-19075-6]. For details on JSON types
+ supported in PostgreSQL,
+ see Section 8.14.
+
+ Table 9.45 shows the operators that
+ are available for use with JSON data types (see Section 8.14).
+ In addition, the usual comparison operators shown in Table 9.1 are available for
+ jsonb, though not for json. The comparison
+ operators follow the ordering rules for B-tree operations outlined in
+ Section 8.14.4.
+ See also Section 9.21 for the aggregate
+ function json_agg which aggregates record
+ values as JSON, the aggregate function
+ json_object_agg which aggregates pairs of values
+ into a JSON object, and their jsonb equivalents,
+ jsonb_agg and jsonb_object_agg.
+
Table 9.45. json and jsonb Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ json->integer
+ → json
+
+
+ jsonb->integer
+ → jsonb
+
+
+ Extracts n'th element of JSON array
+ (array elements are indexed from zero, but negative integers count
+ from the end).
+
+ Extracts JSON sub-object at the specified path as text.
+
+
+ '{"a": {"b": ["foo","bar"]}}'::json #>> '{a,b,1}'
+ → bar
+
Note
+ The field/element/path extraction operators return NULL, rather than
+ failing, if the JSON input does not have the right structure to match
+ the request; for example if no such key or array element exists.
+
+ Some further operators exist only for jsonb, as shown
+ in Table 9.46.
+ Section 8.14.4
+ describes how these operators can be used to effectively search indexed
+ jsonb data.
+
Table 9.46. Additional jsonb Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ jsonb@>jsonb
+ → boolean
+
+
+ Does the first JSON value contain the second?
+ (See Section 8.14.3 for details about containment.)
+
+
+ '{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb
+ → t
+
+ jsonb<@jsonb
+ → boolean
+
+
+ Is the first JSON value contained in the second?
+
+
+ '{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb
+ → t
+
+ jsonb?text
+ → boolean
+
+
+ Does the text string exist as a top-level key or array element within
+ the JSON value?
+
+
+ '{"a":1, "b":2}'::jsonb ? 'b'
+ → t
+
+
+ '["a", "b", "c"]'::jsonb ? 'b'
+ → t
+
+ jsonb?|text[]
+ → boolean
+
+
+ Do any of the strings in the text array exist as top-level keys or
+ array elements?
+
+ Concatenates two jsonb values.
+ Concatenating two arrays generates an array containing all the
+ elements of each input. Concatenating two objects generates an
+ object containing the union of their
+ keys, taking the second object's value when there are duplicate keys.
+ All other cases are treated by converting a non-array input into a
+ single-element array, and then proceeding as for two arrays.
+ Does not operate recursively: only the top-level array or object
+ structure is merged.
+
+ Returns the result of a JSON path predicate check for the
+ specified JSON value. Only the first item of the result is taken into
+ account. If the result is not Boolean, then NULL
+ is returned.
+
+
+ '{"a":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'
+ → t
+
Note
+ The jsonpath operators @?
+ and @@ suppress the following errors: missing object
+ field or array element, unexpected JSON item type, datetime and numeric
+ errors. The jsonpath-related functions described below can
+ also be told to suppress these types of errors. This behavior might be
+ helpful when searching JSON document collections of varying structure.
+
+ Table 9.47 shows the functions that are
+ available for constructing json and jsonb values.
+ Some functions in this table have a RETURNING clause,
+ which specifies the data type returned. It must be one of json,
+ jsonb, bytea, a character string type (text,
+ char, or varchar), or a type
+ for which there is a cast from json to that type.
+ By default, the json type is returned.
+
Table 9.47. JSON Creation Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ to_json ( anyelement )
+ → json
+
+
+
+ to_jsonb ( anyelement )
+ → jsonb
+
+
+ Converts any SQL value to json or jsonb.
+ Arrays and composites are converted recursively to arrays and
+ objects (multidimensional arrays become arrays of arrays in JSON).
+ Otherwise, if there is a cast from the SQL data type
+ to json, the cast function will be used to perform the
+ conversion;[a]
+ otherwise, a scalar JSON value is produced. For any scalar other than
+ a number, a Boolean, or a null value, the text representation will be
+ used, with escaping as necessary to make it a valid JSON string value.
+
+
+ to_json('Fred said "Hi."'::text)
+ → "Fred said \"Hi.\""
+
+
+ to_jsonb(row(42, 'Fred said "Hi."'::text))
+ → {"f1": 42, "f2": "Fred said \"Hi.\""}
+
+ Converts an SQL array to a JSON array. The behavior is the same
+ as to_json except that line feeds will be added
+ between top-level array elements if the optional boolean parameter is
+ true.
+
+ Constructs a JSON array from either a series of
+ value_expression parameters or from the results
+ of query_expression,
+ which must be a SELECT query returning a single column. If
+ ABSENT ON NULL is specified, NULL values are ignored.
+ This is always the case if a
+ query_expression is used.
+
+ Converts an SQL composite value to a JSON object. The behavior is the
+ same as to_json except that line feeds will be
+ added between top-level elements if the optional boolean parameter is
+ true.
+
+ Builds a JSON object out of a variadic argument list. By convention,
+ the argument list consists of alternating keys and values. Key
+ arguments are coerced to text; value arguments are converted as
+ per to_json or to_jsonb.
+
+ Constructs a JSON object of all the key/value pairs given,
+ or an empty object if none are given.
+ key_expression is a scalar expression
+ defining the JSON key, which is
+ converted to the text type.
+ It cannot be NULL nor can it
+ belong to a type that has a cast to the json type.
+ If WITH UNIQUE KEYS is specified, there must not
+ be any duplicate key_expression.
+ Any pair for which the value_expression
+ evaluates to NULL is omitted from the output
+ if ABSENT ON NULL is specified;
+ if NULL ON NULL is specified or the clause
+ omitted, the key is included with value NULL.
+
+ Builds a JSON object out of a text array. The array must have either
+ exactly one dimension with an even number of members, in which case
+ they are taken as alternating key/value pairs, or two dimensions
+ such that each inner array has exactly two elements, which
+ are taken as a key/value pair. All values are converted to JSON
+ strings.
+
[a]
+ For example, the hstore extension has a cast
+ from hstore to json, so that
+ hstore values converted via the JSON creation functions
+ will be represented as JSON objects, not as primitive string values.
+
+
+ expressionIS [NOT] JSON
+ [ { VALUE | SCALAR | ARRAY | OBJECT } ]
+ [ { WITH | WITHOUT } UNIQUE [KEYS] ]
+
+
+ This predicate tests whether expression can be
+ parsed as JSON, possibly of a specified type.
+ If SCALAR or ARRAY or
+ OBJECT is specified, the
+ test is whether or not the JSON is of that particular type. If
+ WITH UNIQUE KEYS is specified, then any object in the
+ expression is also tested to see if it
+ has duplicate keys.
+
+
+
+SELECT js,
+ js IS JSON "json?",
+ js IS JSON SCALAR "scalar?",
+ js IS JSON OBJECT "object?",
+ js IS JSON ARRAY "array?"
+FROM (VALUES
+ ('123'), ('"abc"'), ('{"a": "b"}'), ('[1,2]'),('abc')) foo(js);
+ js | json? | scalar? | object? | array?
+------------+-------+---------+---------+--------
+ 123 | t | t | f | f
+ "abc" | t | t | f | f
+ {"a": "b"} | t | f | t | f
+ [1,2] | t | f | f | t
+ abc | f | f | f | f
+
+
+
+
+SELECT js,
+ js IS JSON OBJECT "object?",
+ js IS JSON ARRAY "array?",
+ js IS JSON ARRAY WITH UNIQUE KEYS "array w. UK?",
+ js IS JSON ARRAY WITHOUT UNIQUE KEYS "array w/o UK?"
+FROM (VALUES ('[{"a":"1"},
+ {"b":"2","b":"3"}]')) foo(js);
+-[ RECORD 1 ]-+--------------------
+js | [{"a":"1"}, +
+ | {"b":"2","b":"3"}]
+object? | f
+array? | t
+array w. UK? | f
+array w/o UK? | t
+
+
+ Table 9.49 shows the functions that
+ are available for processing json and jsonb values.
+
+ Extracts JSON sub-object at the specified path.
+ (This is functionally equivalent to the #>
+ operator, but writing the path out as a variadic list can be more
+ convenient in some cases.)
+
+ Expands the top-level JSON object to a row having the composite type
+ of the base argument. The JSON object
+ is scanned for fields whose names match column names of the output row
+ type, and their values are inserted into those columns of the output.
+ (Fields that do not correspond to any output column name are ignored.)
+ In typical use, the value of base is just
+ NULL, which means that any output columns that do
+ not match any object field will be filled with nulls. However,
+ if base isn't NULL then
+ the values it contains will be used for unmatched columns.
+
+
+ To convert a JSON value to the SQL type of an output column, the
+ following rules are applied in sequence:
+
+ A JSON null value is converted to an SQL null in all cases.
+
+ If the output column is of type json
+ or jsonb, the JSON value is just reproduced exactly.
+
+ If the output column is a composite (row) type, and the JSON value
+ is a JSON object, the fields of the object are converted to columns
+ of the output row type by recursive application of these rules.
+
+ Likewise, if the output column is an array type and the JSON value
+ is a JSON array, the elements of the JSON array are converted to
+ elements of the output array by recursive application of these
+ rules.
+
+ Otherwise, if the JSON value is a string, the contents of the
+ string are fed to the input conversion function for the column's
+ data type.
+
+ Otherwise, the ordinary text representation of the JSON value is
+ fed to the input conversion function for the column's data type.
+
+
+
+ While the example below uses a constant JSON value, typical use would
+ be to reference a json or jsonb column
+ laterally from another table in the query's FROM
+ clause. Writing json_populate_record in
+ the FROM clause is good practice, since all of the
+ extracted columns are available for use without duplicate function
+ calls.
+
+
+ create type subrowtype as (d int, e text);
+ create type myrowtype as (a int, b text[], c subrowtype);
+
+
+ select * from json_populate_record(null::myrowtype,
+ '{"a": 1, "b": ["2", "a b"], "c": {"d": 4, "e": "a b c"}, "x": "foo"}')
+ →
+
+ a | b | c
+---+-----------+-------------
+ 1 | {2,"a b"} | (4,"a b c")
+
+ Expands the top-level JSON array of objects to a set of rows having
+ the composite type of the base argument.
+ Each element of the JSON array is processed as described above
+ for json[b]_populate_record.
+
+
+ create type twoints as (a int, b int);
+
+
+ select * from json_populate_recordset(null::twoints, '[{"a":1,"b":2}, {"a":3,"b":4}]')
+ →
+
+ a | b
+---+---
+ 1 | 2
+ 3 | 4
+
+
+
+ json_to_record ( json )
+ → record
+
+
+
+ jsonb_to_record ( jsonb )
+ → record
+
+
+ Expands the top-level JSON object to a row having the composite type
+ defined by an AS clause. (As with all functions
+ returning record, the calling query must explicitly
+ define the structure of the record with an AS
+ clause.) The output record is filled from fields of the JSON object,
+ in the same way as described above
+ for json[b]_populate_record. Since there is no
+ input record value, unmatched columns are always filled with nulls.
+
+
+ create type myrowtype as (a int, b text);
+
+
+ select * from json_to_record('{"a":1,"b":[1,2,3],"c":[1,2,3],"e":"bar","r": {"a": 123, "b": "a b c"}}') as x(a int, b text, c int[], d text, r myrowtype)
+ →
+
+ a | b | c | d | r
+---+---------+---------+---+---------------
+ 1 | [1,2,3] | {1,2,3} | | (123,"a b c")
+
+ Expands the top-level JSON array of objects to a set of rows having
+ the composite type defined by an AS clause. (As
+ with all functions returning record, the calling query
+ must explicitly define the structure of the record with
+ an AS clause.) Each element of the JSON array is
+ processed as described above
+ for json[b]_populate_record.
+
+
+ select * from json_to_recordset('[{"a":1,"b":"foo"}, {"a":"2","c":"bar"}]') as x(a int, b text)
+ →
+
+ Returns target
+ with the item designated by path
+ replaced by new_value, or with
+ new_value added if
+ create_if_missing is true (which is the
+ default) and the item designated by path
+ does not exist.
+ All earlier steps in the path must exist, or
+ the target is returned unchanged.
+ As with the path oriented operators, negative integers that
+ appear in the path count from the end
+ of JSON arrays.
+ If the last path step is an array index that is out of range,
+ and create_if_missing is true, the new
+ value is added at the beginning of the array if the index is negative,
+ or at the end of the array if it is positive.
+
+ If new_value is not NULL,
+ behaves identically to jsonb_set. Otherwise behaves
+ according to the value
+ of null_value_treatment which must be one
+ of 'raise_exception',
+ 'use_json_null', 'delete_key', or
+ 'return_target'. The default is
+ 'use_json_null'.
+
+ Returns target
+ with new_value inserted. If the item
+ designated by the path is an array
+ element, new_value will be inserted before
+ that item if insert_after is false (which
+ is the default), or after it
+ if insert_after is true. If the item
+ designated by the path is an object
+ field, new_value will be inserted only if
+ the object does not already contain that key.
+ All earlier steps in the path must exist, or
+ the target is returned unchanged.
+ As with the path oriented operators, negative integers that
+ appear in the path count from the end
+ of JSON arrays.
+ If the last path step is an array index that is out of range, the new
+ value is added at the beginning of the array if the index is negative,
+ or at the end of the array if it is positive.
+
+ Checks whether the JSON path returns any item for the specified JSON
+ value.
+ If the vars argument is specified, it must
+ be a JSON object, and its fields provide named values to be
+ substituted into the jsonpath expression.
+ If the silent argument is specified and
+ is true, the function suppresses the same errors
+ as the @? and @@ operators do.
+
+ Returns the result of a JSON path predicate check for the specified
+ JSON value. Only the first item of the result is taken into account.
+ If the result is not Boolean, then NULL is returned.
+ The optional vars
+ and silent arguments act the same as
+ for jsonb_path_exists.
+
+ Returns all JSON items returned by the JSON path for the specified
+ JSON value.
+ The optional vars
+ and silent arguments act the same as
+ for jsonb_path_exists.
+
+ Returns all JSON items returned by the JSON path for the specified
+ JSON value, as a JSON array.
+ The optional vars
+ and silent arguments act the same as
+ for jsonb_path_exists.
+
+ Returns the first JSON item returned by the JSON path for the
+ specified JSON value. Returns NULL if there are no
+ results.
+ The optional vars
+ and silent arguments act the same as
+ for jsonb_path_exists.
+
+ These functions act like their counterparts described above without
+ the _tz suffix, except that these functions support
+ comparisons of date/time values that require timezone-aware
+ conversions. The example below requires interpretation of the
+ date-only value 2015-08-02 as a timestamp with time
+ zone, so the result depends on the current
+ TimeZone setting. Due to this dependency, these
+ functions are marked as stable, which means these functions cannot be
+ used in indexes. Their counterparts are immutable, and so can be used
+ in indexes; but they will throw errors if asked to make such
+ comparisons.
+
+ Converts the given JSON value to pretty-printed, indented text.
+
+
+ jsonb_pretty('[{"f1":1,"f2":null}, 2]')
+ →
+
+[
+ {
+ "f1": 1,
+ "f2": null
+ },
+ 2
+]
+
+
+
+ json_typeof ( json )
+ → text
+
+
+
+ jsonb_typeof ( jsonb )
+ → text
+
+
+ Returns the type of the top-level JSON value as a text string.
+ Possible types are
+ object, array,
+ string, number,
+ boolean, and null.
+ (The null result should not be confused
+ with an SQL NULL; see the examples.)
+
+ SQL/JSON path expressions specify the items to be retrieved
+ from the JSON data, similar to XPath expressions used
+ for SQL access to XML. In PostgreSQL,
+ path expressions are implemented as the jsonpath
+ data type and can use any elements described in
+ Section 8.14.7.
+
+ JSON query functions and operators
+ pass the provided path expression to the path engine
+ for evaluation. If the expression matches the queried JSON data,
+ the corresponding JSON item, or set of items, is returned.
+ Path expressions are written in the SQL/JSON path language
+ and can include arithmetic expressions and functions.
+
+ A path expression consists of a sequence of elements allowed
+ by the jsonpath data type.
+ The path expression is normally evaluated from left to right, but
+ you can use parentheses to change the order of operations.
+ If the evaluation is successful, a sequence of JSON items is produced,
+ and the evaluation result is returned to the JSON query function
+ that completes the specified computation.
+
+ To refer to the JSON value being queried (the
+ context item), use the $ variable
+ in the path expression. It can be followed by one or more
+ accessor operators,
+ which go down the JSON structure level by level to retrieve sub-items
+ of the context item. Each operator that follows deals with the
+ result of the previous evaluation step.
+
+ For example, suppose you have some JSON data from a GPS tracker that you
+ would like to parse, such as:
+
+ To retrieve the available track segments, you need to use the
+ .key accessor
+ operator to descend through surrounding JSON objects:
+
+$.track.segments
+
+
+ To retrieve the contents of an array, you typically use the
+ [*] operator. For example,
+ the following path will return the location coordinates for all
+ the available track segments:
+
+$.track.segments[*].location
+
+
+ To return the coordinates of the first segment only, you can
+ specify the corresponding subscript in the []
+ accessor operator. Recall that JSON array indexes are 0-relative:
+
+$.track.segments[0].location
+
+
+ The result of each path evaluation step can be processed
+ by one or more jsonpath operators and methods
+ listed in Section 9.16.2.2.
+ Each method name must be preceded by a dot. For example,
+ you can get the size of an array:
+
+$.track.segments.size()
+
+ More examples of using jsonpath operators
+ and methods within path expressions appear below in
+ Section 9.16.2.2.
+
+ When defining a path, you can also use one or more
+ filter expressions that work similarly to the
+ WHERE clause in SQL. A filter expression begins with
+ a question mark and provides a condition in parentheses:
+
+
+? (condition)
+
+
+ Filter expressions must be written just after the path evaluation step
+ to which they should apply. The result of that step is filtered to include
+ only those items that satisfy the provided condition. SQL/JSON defines
+ three-valued logic, so the condition can be true, false,
+ or unknown. The unknown value
+ plays the same role as SQL NULL and can be tested
+ for with the is unknown predicate. Further path
+ evaluation steps use only those items for which the filter expression
+ returned true.
+
+ The functions and operators that can be used in filter expressions are
+ listed in Table 9.51. Within a
+ filter expression, the @ variable denotes the value
+ being filtered (i.e., one result of the preceding path step). You can
+ write accessor operators after @ to retrieve component
+ items.
+
+ For example, suppose you would like to retrieve all heart rate values higher
+ than 130. You can achieve this using the following expression:
+
+$.track.segments[*].HR ? (@ > 130)
+
+
+ To get the start times of segments with such values, you have to
+ filter out irrelevant segments before returning the start times, so the
+ filter expression is applied to the previous step, and the path used
+ in the condition is different:
+
+ You can use several filter expressions in sequence, if required. For
+ example, the following expression selects start times of all segments that
+ contain locations with relevant coordinates and high heart rate values:
+
+ Using filter expressions at different nesting levels is also allowed.
+ The following example first filters all segments by location, and then
+ returns high heart rate values for these segments, if available:
+
+ This expression returns the size of the track if it contains any
+ segments with high heart rate values, or an empty sequence otherwise.
+
+ PostgreSQL's implementation of the SQL/JSON path
+ language has the following deviations from the SQL/JSON standard:
+
+ A path expression can be a Boolean predicate, although the SQL/JSON
+ standard allows predicates only in filters. This is necessary for
+ implementation of the @@ operator. For example,
+ the following jsonpath expression is valid in
+ PostgreSQL:
+
+$.track.segments[*].HR < 70
+
+
+ There are minor differences in the interpretation of regular
+ expression patterns used in like_regex filters, as
+ described in Section 9.16.2.3.
+
+ When you query JSON data, the path expression may not match the
+ actual JSON data structure. An attempt to access a non-existent
+ member of an object or element of an array results in a
+ structural error. SQL/JSON path expressions have two modes
+ of handling structural errors:
+
+ lax (default) — the path engine implicitly adapts
+ the queried data to the specified path.
+ Any remaining structural errors are suppressed and converted
+ to empty SQL/JSON sequences.
+
+ strict — if a structural error occurs, an error is raised.
+
+ The lax mode facilitates matching of a JSON document structure and path
+ expression if the JSON data does not conform to the expected schema.
+ If an operand does not match the requirements of a particular operation,
+ it can be automatically wrapped as an SQL/JSON array or unwrapped by
+ converting its elements into an SQL/JSON sequence before performing
+ this operation. Besides, comparison operators automatically unwrap their
+ operands in the lax mode, so you can compare SQL/JSON arrays
+ out-of-the-box. An array of size 1 is considered equal to its sole element.
+ Automatic unwrapping is not performed only when:
+
+ The path expression contains type() or
+ size() methods that return the type
+ and the number of elements in the array, respectively.
+
+ The queried JSON data contain nested arrays. In this case, only
+ the outermost array is unwrapped, while all the inner arrays
+ remain unchanged. Thus, implicit unwrapping can only go one
+ level down within each path evaluation step.
+
+
+ For example, when querying the GPS data listed above, you can
+ abstract from the fact that it stores an array of segments
+ when using the lax mode:
+
+lax $.track.segments.location
+
+
+ In the strict mode, the specified path must exactly match the structure of
+ the queried JSON document to return an SQL/JSON item, so using this
+ path expression will cause an error. To get the same result as in
+ the lax mode, you have to explicitly unwrap the
+ segments array:
+
+strict $.track.segments[*].location
+
+
+ The .** accessor can lead to surprising results
+ when using the lax mode. For instance, the following query selects every
+ HR value twice:
+
+lax $.**.HR
+
+ This happens because the .** accessor selects both
+ the segments array and each of its elements, while
+ the .HR accessor automatically unwraps arrays when
+ using the lax mode. To avoid surprising results, we recommend using
+ the .** accessor only in the strict mode. The
+ following query selects each HR value just once:
+
+ Table 9.50 shows the operators and
+ methods available in jsonpath. Note that while the unary
+ operators and methods can be applied to multiple values resulting from a
+ preceding path step, the binary operators (addition etc.) can only be
+ applied to single values.
+
Table 9.50. jsonpath Operators and Methods
+ Operator/Method
+
+
+ Description
+
+
+ Example(s)
+
+ number+number
+ → number
+
+
+ Addition
+
+
+ jsonb_path_query('[2]', '$[0] + 3')
+ → 5
+
+ +number
+ → number
+
+
+ Unary plus (no operation); unlike addition, this can iterate over
+ multiple values
+
+ The object's key-value pairs, represented as an array of objects
+ containing three fields: "key",
+ "value", and "id";
+ "id" is a unique identifier of the object the
+ key-value pair belongs to
+
+ The result type of the datetime() and
+ datetime(template)
+ methods can be date, timetz, time,
+ timestamptz, or timestamp.
+ Both methods determine their result type dynamically.
+
+ The datetime() method sequentially tries to
+ match its input string to the ISO formats
+ for date, timetz, time,
+ timestamptz, and timestamp. It stops on
+ the first matching format and emits the corresponding data type.
+
+ The datetime(template)
+ method determines the result type according to the fields used in the
+ provided template string.
+
+ The datetime() and
+ datetime(template) methods
+ use the same parsing rules as the to_timestamp SQL
+ function does (see Section 9.8), with three
+ exceptions. First, these methods don't allow unmatched template
+ patterns. Second, only the following separators are allowed in the
+ template string: minus sign, period, solidus (slash), comma, apostrophe,
+ semicolon, colon and space. Third, separators in the template string
+ must exactly match the input string.
+
+ If different date/time types need to be compared, an implicit cast is
+ applied. A date value can be cast to timestamp
+ or timestamptz, timestamp can be cast to
+ timestamptz, and time to timetz.
+ However, all but the first of these conversions depend on the current
+ TimeZone setting, and thus can only be performed
+ within timezone-aware jsonpath functions.
+
+ Table 9.51 shows the available
+ filter expression elements.
+
Table 9.51. jsonpath Filter Expression Elements
+ Predicate/Value
+
+
+ Description
+
+
+ Example(s)
+
+ value==value
+ → boolean
+
+
+ Equality comparison (this, and the other comparison operators, work on
+ all JSON scalar values)
+
+ Tests whether the first operand matches the regular expression
+ given by the second operand, optionally with modifications
+ described by a string of flag characters (see
+ Section 9.16.2.3).
+
+ Tests whether a path expression matches at least one SQL/JSON item.
+ Returns unknown if the path expression would result
+ in an error; the second example uses this to avoid a no-such-key error
+ in strict mode.
+
+ SQL/JSON path expressions allow matching text to a regular expression
+ with the like_regex filter. For example, the
+ following SQL/JSON path query would case-insensitively match all
+ strings in an array that start with an English vowel:
+
+$[*] ? (@ like_regex "^[aeiou]" flag "i")
+
+
+ The optional flag string may include one or more of
+ the characters
+ i for case-insensitive match,
+ m to allow ^
+ and $ to match at newlines,
+ s to allow . to match a newline,
+ and q to quote the whole pattern (reducing the
+ behavior to a simple substring match).
+
+ The SQL/JSON standard borrows its definition for regular expressions
+ from the LIKE_REGEX operator, which in turn uses the
+ XQuery standard. PostgreSQL does not currently support the
+ LIKE_REGEX operator. Therefore,
+ the like_regex filter is implemented using the
+ POSIX regular expression engine described in
+ Section 9.7.3. This leads to various minor
+ discrepancies from standard SQL/JSON behavior, which are cataloged in
+ Section 9.7.3.8.
+ Note, however, that the flag-letter incompatibilities described there
+ do not apply to SQL/JSON, as it translates the XQuery flag letters to
+ match what the POSIX engine expects.
+
+ Keep in mind that the pattern argument of like_regex
+ is a JSON path string literal, written according to the rules given in
+ Section 8.14.7. This means in particular that any
+ backslashes you want to use in the regular expression must be doubled.
+ For example, to match string values of the root document that contain
+ only digits:
+
+$.* ? (@ like_regex "^\\d+$")
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-logical.html b/pgsql/doc/postgresql/html/functions-logical.html
new file mode 100644
index 0000000000000000000000000000000000000000..71ed71daf6f71e28b7715c61de392b6d8723002a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-logical.html
@@ -0,0 +1,36 @@
+
+9.1. Logical Operators
+
+ SQL uses a three-valued logic system with true,
+ false, and null, which represents “unknown”.
+ Observe the following truth tables:
+
+
a
b
a AND b
a OR b
TRUE
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE
TRUE
TRUE
NULL
NULL
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
NULL
FALSE
NULL
NULL
NULL
NULL
NULL
+
+
a
NOT a
TRUE
FALSE
FALSE
TRUE
NULL
NULL
+
+ The operators AND and OR are
+ commutative, that is, you can switch the left and right operands
+ without affecting the result. (However, it is not guaranteed that
+ the left operand is evaluated before the right operand. See Section 4.2.14 for more information about the
+ order of evaluation of subexpressions.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-matching.html b/pgsql/doc/postgresql/html/functions-matching.html
new file mode 100644
index 0000000000000000000000000000000000000000..42814c748c8db643708bc56bbb9b047e1728941f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-matching.html
@@ -0,0 +1,1415 @@
+
+9.7. Pattern Matching
+ There are three separate approaches to pattern matching provided
+ by PostgreSQL: the traditional
+ SQL LIKE operator, the
+ more recent SIMILAR TO operator (added in
+ SQL:1999), and POSIX-style regular
+ expressions. Aside from the basic “does this string match
+ this pattern?” operators, functions are available to extract
+ or replace matching substrings and to split a string at matching
+ locations.
+
Tip
+ If you have pattern matching needs that go beyond this,
+ consider writing a user-defined function in Perl or Tcl.
+
Caution
+ While most regular-expression searches can be executed very quickly,
+ regular expressions can be contrived that take arbitrary amounts of
+ time and memory to process. Be wary of accepting regular-expression
+ search patterns from hostile sources. If you must do so, it is
+ advisable to impose a statement timeout.
+
+ Searches using SIMILAR TO patterns have the same
+ security hazards, since SIMILAR TO provides many
+ of the same capabilities as POSIX-style regular
+ expressions.
+
+ LIKE searches, being much simpler than the other
+ two options, are safer to use with possibly-hostile pattern sources.
+
+ The pattern matching operators of all three kinds do not support
+ nondeterministic collations. If required, apply a different collation to
+ the expression to work around this limitation.
+
+string LIKE pattern [ESCAPE escape-character]
+string NOT LIKE pattern [ESCAPE escape-character]
+
+ The LIKE expression returns true if the
+ string matches the supplied
+ pattern. (As
+ expected, the NOT LIKE expression returns
+ false if LIKE returns true, and vice versa.
+ An equivalent expression is
+ NOT (string LIKE
+ pattern).)
+
+ If pattern does not contain percent
+ signs or underscores, then the pattern only represents the string
+ itself; in that case LIKE acts like the
+ equals operator. An underscore (_) in
+ pattern stands for (matches) any single
+ character; a percent sign (%) matches any sequence
+ of zero or more characters.
+
+ Some examples:
+
+'abc' LIKE 'abc' true
+'abc' LIKE 'a%' true
+'abc' LIKE '_b_' true
+'abc' LIKE 'c' false
+
+
+ LIKE pattern matching always covers the entire
+ string. Therefore, if it's desired to match a sequence anywhere within
+ a string, the pattern must start and end with a percent sign.
+
+ To match a literal underscore or percent sign without matching
+ other characters, the respective character in
+ pattern must be
+ preceded by the escape character. The default escape
+ character is the backslash but a different one can be selected by
+ using the ESCAPE clause. To match the escape
+ character itself, write two escape characters.
+
Note
+ If you have standard_conforming_strings turned off,
+ any backslashes you write in literal string constants will need to be
+ doubled. See Section 4.1.2.1 for more information.
+
+ It's also possible to select no escape character by writing
+ ESCAPE ''. This effectively disables the
+ escape mechanism, which makes it impossible to turn off the
+ special meaning of underscore and percent signs in the pattern.
+
+ According to the SQL standard, omitting ESCAPE
+ means there is no escape character (rather than defaulting to a
+ backslash), and a zero-length ESCAPE value is
+ disallowed. PostgreSQL's behavior in
+ this regard is therefore slightly nonstandard.
+
+ The key word ILIKE can be used instead of
+ LIKE to make the match case-insensitive according
+ to the active locale. This is not in the SQL standard but is a
+ PostgreSQL extension.
+
+ The operator ~~ is equivalent to
+ LIKE, and ~~* corresponds to
+ ILIKE. There are also
+ !~~ and !~~* operators that
+ represent NOT LIKE and NOT
+ ILIKE, respectively. All of these operators are
+ PostgreSQL-specific. You may see these
+ operator names in EXPLAIN output and similar
+ places, since the parser actually translates LIKE
+ et al. to these operators.
+
+ The phrases LIKE, ILIKE,
+ NOT LIKE, and NOT ILIKE are
+ generally treated as operators
+ in PostgreSQL syntax; for example they can
+ be used in expression
+ operator ANY
+ (subquery) constructs, although
+ an ESCAPE clause cannot be included there. In some
+ obscure cases it may be necessary to use the underlying operator names
+ instead.
+
+ Also see the starts-with operator ^@ and the
+ corresponding starts_with() function, which are
+ useful in cases where simply matching the beginning of a string is
+ needed.
+
+string SIMILAR TO pattern [ESCAPE escape-character]
+string NOT SIMILAR TO pattern [ESCAPE escape-character]
+
+ The SIMILAR TO operator returns true or
+ false depending on whether its pattern matches the given string.
+ It is similar to LIKE, except that it
+ interprets the pattern using the SQL standard's definition of a
+ regular expression. SQL regular expressions are a curious cross
+ between LIKE notation and common (POSIX) regular
+ expression notation.
+
+ Like LIKE, the SIMILAR TO
+ operator succeeds only if its pattern matches the entire string;
+ this is unlike common regular expression behavior where the pattern
+ can match any part of the string.
+ Also like
+ LIKE, SIMILAR TO uses
+ _ and % as wildcard characters denoting
+ any single character and any string, respectively (these are
+ comparable to . and .* in POSIX regular
+ expressions).
+
+ In addition to these facilities borrowed from LIKE,
+ SIMILAR TO supports these pattern-matching
+ metacharacters borrowed from POSIX regular expressions:
+
+
+ | denotes alternation (either of two alternatives).
+
+ * denotes repetition of the previous item zero
+ or more times.
+
+ + denotes repetition of the previous item one
+ or more times.
+
+ ? denotes repetition of the previous item zero
+ or one time.
+
+ {m} denotes repetition
+ of the previous item exactly m times.
+
+ {m,} denotes repetition
+ of the previous item m or more times.
+
+ {m,n}
+ denotes repetition of the previous item at least m and
+ not more than n times.
+
+ Parentheses () can be used to group items into
+ a single logical item.
+
+ A bracket expression [...] specifies a character
+ class, just as in POSIX regular expressions.
+
+
+ Notice that the period (.) is not a metacharacter
+ for SIMILAR TO.
+
+ As with LIKE, a backslash disables the special
+ meaning of any of these metacharacters. A different escape character
+ can be specified with ESCAPE, or the escape
+ capability can be disabled by writing ESCAPE ''.
+
+ According to the SQL standard, omitting ESCAPE
+ means there is no escape character (rather than defaulting to a
+ backslash), and a zero-length ESCAPE value is
+ disallowed. PostgreSQL's behavior in
+ this regard is therefore slightly nonstandard.
+
+ Another nonstandard extension is that following the escape character
+ with a letter or digit provides access to the escape sequences
+ defined for POSIX regular expressions; see
+ Table 9.20,
+ Table 9.21, and
+ Table 9.22 below.
+
+ Some examples:
+
+'abc' SIMILAR TO 'abc' true
+'abc' SIMILAR TO 'a' false
+'abc' SIMILAR TO '%(b|d)%' true
+'abc' SIMILAR TO '(b|c)%' false
+'-abc-' SIMILAR TO '%\mabc\M%' true
+'xabcy' SIMILAR TO '%\mabc\M%' false
+
+
+ The substring function with three parameters
+ provides extraction of a substring that matches an SQL
+ regular expression pattern. The function can be written according
+ to standard SQL syntax:
+
+substring(string similar pattern escape escape-character)
+
+ or using the now obsolete SQL:1999 syntax:
+
+substring(string from pattern for escape-character)
+
+ or as a plain three-argument function:
+
+substring(string, pattern, escape-character)
+
+ As with SIMILAR TO, the
+ specified pattern must match the entire data string, or else the
+ function fails and returns null. To indicate the part of the
+ pattern for which the matching data sub-string is of interest,
+ the pattern should contain
+ two occurrences of the escape character followed by a double quote
+ (").
+ The text matching the portion of the pattern
+ between these separators is returned when the match is successful.
+
+ The escape-double-quote separators actually
+ divide substring's pattern into three independent
+ regular expressions; for example, a vertical bar (|)
+ in any of the three sections affects only that section. Also, the first
+ and third of these regular expressions are defined to match the smallest
+ possible amount of text, not the largest, when there is any ambiguity
+ about how much of the data string matches which pattern. (In POSIX
+ parlance, the first and third regular expressions are forced to be
+ non-greedy.)
+
+ As an extension to the SQL standard, PostgreSQL
+ allows there to be just one escape-double-quote separator, in which case
+ the third regular expression is taken as empty; or no separators, in which
+ case the first and third regular expressions are taken as empty.
+
+ Some examples, with #" delimiting the return string:
+
+substring('foobar' similar '%#"o_b#"%' escape '#') oob
+substring('foobar' similar '#"o_b#"%' escape '#') NULL
+
+ String does not match regular expression, case sensitively
+
+
+ 'thomas' !~ 't.*max'
+ → t
+
+ text!~*text
+ → boolean
+
+
+ String does not match regular expression, case-insensitively
+
+
+ 'thomas' !~* 'T.*ma'
+ → f
+
+ POSIX regular expressions provide a more
+ powerful means for pattern matching than the LIKE and
+ SIMILAR TO operators.
+ Many Unix tools such as egrep,
+ sed, or awk use a pattern
+ matching language that is similar to the one described here.
+
+ A regular expression is a character sequence that is an
+ abbreviated definition of a set of strings (a regular
+ set). A string is said to match a regular expression
+ if it is a member of the regular set described by the regular
+ expression. As with LIKE, pattern characters
+ match string characters exactly unless they are special characters
+ in the regular expression language — but regular expressions use
+ different special characters than LIKE does.
+ Unlike LIKE patterns, a
+ regular expression is allowed to match anywhere within a string, unless
+ the regular expression is explicitly anchored to the beginning or
+ end of the string.
+
+ Some examples:
+
+'abcd' ~ 'bc' true
+'abcd' ~ 'a.c' true — dot matches any character
+'abcd' ~ 'a.*d' true — * repeats the preceding pattern item
+'abcd' ~ '(b|x)' true — | means OR, parentheses group
+'abcd' ~ '^a' true — ^ anchors to start of string
+'abcd' ~ '^(b|c)' false — would match except for anchoring
+
+
+ The POSIX pattern language is described in much
+ greater detail below.
+
+ The substring function with two parameters,
+ substring(string from
+ pattern), provides extraction of a
+ substring
+ that matches a POSIX regular expression pattern. It returns null if
+ there is no match, otherwise the first portion of the text that matched the
+ pattern. But if the pattern contains any parentheses, the portion
+ of the text that matched the first parenthesized subexpression (the
+ one whose left parenthesis comes first) is
+ returned. You can put parentheses around the whole expression
+ if you want to use parentheses within it without triggering this
+ exception. If you need parentheses in the pattern before the
+ subexpression you want to extract, see the non-capturing parentheses
+ described below.
+
+ Some examples:
+
+substring('foobar' from 'o.b') oob
+substring('foobar' from 'o(.)b') o
+
+
+ The regexp_count function counts the number of
+ places where a POSIX regular expression pattern matches a string.
+ It has the syntax
+ regexp_count(string,
+ pattern
+ [, start
+ [, flags
+ ]]).
+ pattern is searched for
+ in string, normally from the beginning of
+ the string, but if the start parameter is
+ provided then beginning from that character index.
+ The flags parameter is an optional text
+ string containing zero or more single-letter flags that change the
+ function's behavior. For example, including i in
+ flags specifies case-insensitive matching.
+ Supported flags are described in
+ Table 9.24.
+
+ The regexp_instr function returns the starting or
+ ending position of the N'th match of a
+ POSIX regular expression pattern to a string, or zero if there is no
+ such match. It has the syntax
+ regexp_instr(string,
+ pattern
+ [, start
+ [, N
+ [, endoption
+ [, flags
+ [, subexpr
+ ]]]]]).
+ pattern is searched for
+ in string, normally from the beginning of
+ the string, but if the start parameter is
+ provided then beginning from that character index.
+ If N is specified
+ then the N'th match of the pattern
+ is located, otherwise the first match is located.
+ If the endoption parameter is omitted or
+ specified as zero, the function returns the position of the first
+ character of the match. Otherwise, endoption
+ must be one, and the function returns the position of the character
+ following the match.
+ The flags parameter is an optional text
+ string containing zero or more single-letter flags that change the
+ function's behavior. Supported flags are described
+ in Table 9.24.
+ For a pattern containing parenthesized
+ subexpressions, subexpr is an integer
+ indicating which subexpression is of interest: the result identifies
+ the position of the substring matching that subexpression.
+ Subexpressions are numbered in the order of their leading parentheses.
+ When subexpr is omitted or zero, the result
+ identifies the position of the whole match regardless of
+ parenthesized subexpressions.
+
+ Some examples:
+
+regexp_instr('number of your street, town zip, FR', '[^,]+', 1, 2)
+ 23
+regexp_instr('ABCDEFGHI', '(c..)(...)', 1, 1, 0, 'i', 2)
+ 6
+
+
+ The regexp_like function checks whether a match
+ of a POSIX regular expression pattern occurs within a string,
+ returning boolean true or false. It has the syntax
+ regexp_like(string,
+ pattern
+ [, flags]).
+ The flags parameter is an optional text
+ string containing zero or more single-letter flags that change the
+ function's behavior. Supported flags are described
+ in Table 9.24.
+ This function has the same results as the ~
+ operator if no flags are specified. If only the i
+ flag is specified, it has the same results as
+ the ~* operator.
+
+ The regexp_match function returns a text array of
+ matching substring(s) within the first match of a POSIX
+ regular expression pattern to a string. It has the syntax
+ regexp_match(string,
+ pattern [, flags]).
+ If there is no match, the result is NULL.
+ If a match is found, and the pattern contains no
+ parenthesized subexpressions, then the result is a single-element text
+ array containing the substring matching the whole pattern.
+ If a match is found, and the pattern contains
+ parenthesized subexpressions, then the result is a text array
+ whose n'th element is the substring matching
+ the n'th parenthesized subexpression of
+ the pattern (not counting “non-capturing”
+ parentheses; see below for details).
+ The flags parameter is an optional text string
+ containing zero or more single-letter flags that change the function's
+ behavior. Supported flags are described
+ in Table 9.24.
+
+ In the common case where you just want the whole matching substring
+ or NULL for no match, the best solution is to
+ use regexp_substr().
+ However, regexp_substr() only exists
+ in PostgreSQL version 15 and up. When
+ working in older versions, you can extract the first element
+ of regexp_match()'s result, for example:
+
+ The regexp_matches function returns a set of text arrays
+ of matching substring(s) within matches of a POSIX regular
+ expression pattern to a string. It has the same syntax as
+ regexp_match.
+ This function returns no rows if there is no match, one row if there is
+ a match and the g flag is not given, or N
+ rows if there are N matches and the g flag
+ is given. Each returned row is a text array containing the whole
+ matched substring or the substrings matching parenthesized
+ subexpressions of the pattern, just as described above
+ for regexp_match.
+ regexp_matches accepts all the flags shown
+ in Table 9.24, plus
+ the g flag which commands it to return all matches, not
+ just the first one.
+
+ In most cases regexp_matches() should be used with
+ the g flag, since if you only want the first match, it's
+ easier and more efficient to use regexp_match().
+ However, regexp_match() only exists
+ in PostgreSQL version 10 and up. When working in older
+ versions, a common trick is to place a regexp_matches()
+ call in a sub-select, for example:
+
+SELECT col1, (SELECT regexp_matches(col2, '(bar)(beque)')) FROM tab;
+
+ This produces a text array if there's a match, or NULL if
+ not, the same as regexp_match() would do. Without the
+ sub-select, this query would produce no output at all for table rows
+ without a match, which is typically not the desired behavior.
+
+ The regexp_replace function provides substitution of
+ new text for substrings that match POSIX regular expression patterns.
+ It has the syntax
+ regexp_replace(source,
+ pattern, replacement
+ [, start
+ [, N
+ ]]
+ [, flags]).
+ (Notice that N cannot be specified
+ unless start is,
+ but flags can be given in any case.)
+ The source string is returned unchanged if
+ there is no match to the pattern. If there is a
+ match, the source string is returned with the
+ replacement string substituted for the matching
+ substring. The replacement string can contain
+ \n, where n is 1
+ through 9, to indicate that the source substring matching the
+ n'th parenthesized subexpression of the pattern should be
+ inserted, and it can contain \& to indicate that the
+ substring matching the entire pattern should be inserted. Write
+ \\ if you need to put a literal backslash in the replacement
+ text.
+ pattern is searched for
+ in string, normally from the beginning of
+ the string, but if the start parameter is
+ provided then beginning from that character index.
+ By default, only the first match of the pattern is replaced.
+ If N is specified and is greater than zero,
+ then the N'th match of the pattern
+ is replaced.
+ If the g flag is given, or
+ if N is specified and is zero, then all
+ matches at or after the start position are
+ replaced. (The g flag is ignored
+ when N is specified.)
+ The flags parameter is an optional text
+ string containing zero or more single-letter flags that change the
+ function's behavior. Supported flags (though
+ not g) are
+ described in Table 9.24.
+
+ The regexp_split_to_table function splits a string using a POSIX
+ regular expression pattern as a delimiter. It has the syntax
+ regexp_split_to_table(string, pattern
+ [, flags]).
+ If there is no match to the pattern, the function returns the
+ string. If there is at least one match, for each match it returns
+ the text from the end of the last match (or the beginning of the string)
+ to the beginning of the match. When there are no more matches, it
+ returns the text from the end of the last match to the end of the string.
+ The flags parameter is an optional text string containing
+ zero or more single-letter flags that change the function's behavior.
+ regexp_split_to_table supports the flags described in
+ Table 9.24.
+
+ The regexp_split_to_array function behaves the same as
+ regexp_split_to_table, except that regexp_split_to_array
+ returns its result as an array of text. It has the syntax
+ regexp_split_to_array(string, pattern
+ [, flags]).
+ The parameters are the same as for regexp_split_to_table.
+
+ Some examples:
+
+SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', '\s+') AS foo;
+ foo
+-------
+ the
+ quick
+ brown
+ fox
+ jumps
+ over
+ the
+ lazy
+ dog
+(9 rows)
+
+SELECT regexp_split_to_array('the quick brown fox jumps over the lazy dog', '\s+');
+ regexp_split_to_array
+-----------------------------------------------
+ {the,quick,brown,fox,jumps,over,the,lazy,dog}
+(1 row)
+
+SELECT foo FROM regexp_split_to_table('the quick brown fox', '\s*') AS foo;
+ foo
+-----
+ t
+ h
+ e
+ q
+ u
+ i
+ c
+ k
+ b
+ r
+ o
+ w
+ n
+ f
+ o
+ x
+(16 rows)
+
+
+ As the last example demonstrates, the regexp split functions ignore
+ zero-length matches that occur at the start or end of the string
+ or immediately after a previous match. This is contrary to the strict
+ definition of regexp matching that is implemented by
+ the other regexp functions, but is usually the most convenient behavior
+ in practice. Other software systems such as Perl use similar definitions.
+
+ The regexp_substr function returns the substring
+ that matches a POSIX regular expression pattern,
+ or NULL if there is no match. It has the syntax
+ regexp_substr(string,
+ pattern
+ [, start
+ [, N
+ [, flags
+ [, subexpr
+ ]]]]).
+ pattern is searched for
+ in string, normally from the beginning of
+ the string, but if the start parameter is
+ provided then beginning from that character index.
+ If N is specified
+ then the N'th match of the pattern
+ is returned, otherwise the first match is returned.
+ The flags parameter is an optional text
+ string containing zero or more single-letter flags that change the
+ function's behavior. Supported flags are described
+ in Table 9.24.
+ For a pattern containing parenthesized
+ subexpressions, subexpr is an integer
+ indicating which subexpression is of interest: the result is the
+ substring matching that subexpression.
+ Subexpressions are numbered in the order of their leading parentheses.
+ When subexpr is omitted or zero, the result
+ is the whole match regardless of parenthesized subexpressions.
+
+ Some examples:
+
+regexp_substr('number of your street, town zip, FR', '[^,]+', 1, 2)
+ town zip
+regexp_substr('ABCDEFGHI', '(c..)(...)', 1, 1, 'i', 2)
+ FGH
+
+ PostgreSQL's regular expressions are implemented
+ using a software package written by Henry Spencer. Much of
+ the description of regular expressions below is copied verbatim from his
+ manual.
+
+ Regular expressions (REs), as defined in
+ POSIX 1003.2, come in two forms:
+ extended REs or EREs
+ (roughly those of egrep), and
+ basic REs or BREs
+ (roughly those of ed).
+ PostgreSQL supports both forms, and
+ also implements some extensions
+ that are not in the POSIX standard, but have become widely used
+ due to their availability in programming languages such as Perl and Tcl.
+ REs using these non-POSIX extensions are called
+ advanced REs or AREs
+ in this documentation. AREs are almost an exact superset of EREs,
+ but BREs have several notational incompatibilities (as well as being
+ much more limited).
+ We first describe the ARE and ERE forms, noting features that apply
+ only to AREs, and then describe how BREs differ.
+
Note
+ PostgreSQL always initially presumes that a regular
+ expression follows the ARE rules. However, the more limited ERE or
+ BRE rules can be chosen by prepending an embedded option
+ to the RE pattern, as described in Section 9.7.3.4.
+ This can be useful for compatibility with applications that expect
+ exactly the POSIX 1003.2 rules.
+
+ A regular expression is defined as one or more
+ branches, separated by
+ |. It matches anything that matches one of the
+ branches.
+
+ A branch is zero or more quantified atoms or
+ constraints, concatenated.
+ It matches a match for the first, followed by a match for the second, etc.;
+ an empty branch matches the empty string.
+
+ A quantified atom is an atom possibly followed
+ by a single quantifier.
+ Without a quantifier, it matches a match for the atom.
+ With a quantifier, it can match some number of matches of the atom.
+ An atom can be any of the possibilities
+ shown in Table 9.17.
+ The possible quantifiers and their meanings are shown in
+ Table 9.18.
+
+ A constraint matches an empty string, but matches only when
+ specific conditions are met. A constraint can be used where an atom
+ could be used, except it cannot be followed by a quantifier.
+ The simple constraints are shown in
+ Table 9.19;
+ some more constraints are described later.
+
Table 9.17. Regular Expression Atoms
Atom
Description
(re)
(where re is any regular expression)
+ matches a match for
+ re, with the match noted for possible reporting
(?:re)
as above, but the match is not noted for reporting
+ (a “non-capturing” set of parentheses)
+ (AREs only)
.
matches any single character
[chars]
a bracket expression,
+ matching any one of the chars (see
+ Section 9.7.3.2 for more detail)
\k
(where k is a non-alphanumeric character)
+ matches that character taken as an ordinary character,
+ e.g., \\ matches a backslash character
\c
where c is alphanumeric
+ (possibly followed by other characters)
+ is an escape, see Section 9.7.3.3
+ (AREs only; in EREs and BREs, this matches c)
{
when followed by a character other than a digit,
+ matches the left-brace character {;
+ when followed by a digit, it is the beginning of a
+ bound (see below)
x
where x is a single character with no other
+ significance, matches that character
+ An RE cannot end with a backslash (\).
+
Note
+ If you have standard_conforming_strings turned off,
+ any backslashes you write in literal string constants will need to be
+ doubled. See Section 4.1.2.1 for more information.
+
Table 9.18. Regular Expression Quantifiers
Quantifier
Matches
*
a sequence of 0 or more matches of the atom
+
a sequence of 1 or more matches of the atom
?
a sequence of 0 or 1 matches of the atom
{m}
a sequence of exactly m matches of the atom
{m,}
a sequence of m or more matches of the atom
+ {m,n}
a sequence of m through n
+ (inclusive) matches of the atom; m cannot exceed
+ n
*?
non-greedy version of *
+?
non-greedy version of +
??
non-greedy version of ?
{m}?
non-greedy version of {m}
{m,}?
non-greedy version of {m,}
+ {m,n}?
non-greedy version of {m,n}
+ The forms using {...}
+ are known as bounds.
+ The numbers m and n within a bound are
+ unsigned decimal integers with permissible values from 0 to 255 inclusive.
+
+ Non-greedy quantifiers (available in AREs only) match the
+ same possibilities as their corresponding normal (greedy)
+ counterparts, but prefer the smallest number rather than the largest
+ number of matches.
+ See Section 9.7.3.5 for more detail.
+
Note
+ A quantifier cannot immediately follow another quantifier, e.g.,
+ ** is invalid.
+ A quantifier cannot
+ begin an expression or subexpression or follow
+ ^ or |.
+
Table 9.19. Regular Expression Constraints
Constraint
Description
^
matches at the beginning of the string
$
matches at the end of the string
(?=re)
positive lookahead matches at any point
+ where a substring matching re begins
+ (AREs only)
(?!re)
negative lookahead matches at any point
+ where no substring matching re begins
+ (AREs only)
(?<=re)
positive lookbehind matches at any point
+ where a substring matching re ends
+ (AREs only)
(?<!re)
negative lookbehind matches at any point
+ where no substring matching re ends
+ (AREs only)
+ Lookahead and lookbehind constraints cannot contain back
+ references (see Section 9.7.3.3),
+ and all parentheses within them are considered non-capturing.
+
+ A bracket expression is a list of
+ characters enclosed in []. It normally matches
+ any single character from the list (but see below). If the list
+ begins with ^, it matches any single character
+ not from the rest of the list.
+ If two characters
+ in the list are separated by -, this is
+ shorthand for the full range of characters between those two
+ (inclusive) in the collating sequence,
+ e.g., [0-9] in ASCII matches
+ any decimal digit. It is illegal for two ranges to share an
+ endpoint, e.g., a-c-e. Ranges are very
+ collating-sequence-dependent, so portable programs should avoid
+ relying on them.
+
+ To include a literal ] in the list, make it the
+ first character (after ^, if that is used). To
+ include a literal -, make it the first or last
+ character, or the second endpoint of a range. To use a literal
+ - as the first endpoint of a range, enclose it
+ in [. and .] to make it a
+ collating element (see below). With the exception of these characters,
+ some combinations using [
+ (see next paragraphs), and escapes (AREs only), all other special
+ characters lose their special significance within a bracket expression.
+ In particular, \ is not special when following
+ ERE or BRE rules, though it is special (as introducing an escape)
+ in AREs.
+
+ Within a bracket expression, a collating element (a character, a
+ multiple-character sequence that collates as if it were a single
+ character, or a collating-sequence name for either) enclosed in
+ [. and .] stands for the
+ sequence of characters of that collating element. The sequence is
+ treated as a single element of the bracket expression's list. This
+ allows a bracket
+ expression containing a multiple-character collating element to
+ match more than one character, e.g., if the collating sequence
+ includes a ch collating element, then the RE
+ [[.ch.]]*c matches the first five characters of
+ chchcc.
+
Note
+ PostgreSQL currently does not support multi-character collating
+ elements. This information describes possible future behavior.
+
+ Within a bracket expression, a collating element enclosed in
+ [= and =] is an equivalence
+ class, standing for the sequences of characters of all collating
+ elements equivalent to that one, including itself. (If there are
+ no other equivalent collating elements, the treatment is as if the
+ enclosing delimiters were [. and
+ .].) For example, if o and
+ ^ are the members of an equivalence class, then
+ [[=o=]], [[=^=]], and
+ [o^] are all synonymous. An equivalence class
+ cannot be an endpoint of a range.
+
+ Within a bracket expression, the name of a character class
+ enclosed in [: and :] stands
+ for the list of all characters belonging to that class. A character
+ class cannot be used as an endpoint of a range.
+ The POSIX standard defines these character class
+ names:
+ alnum (letters and numeric digits),
+ alpha (letters),
+ blank (space and tab),
+ cntrl (control characters),
+ digit (numeric digits),
+ graph (printable characters except space),
+ lower (lower-case letters),
+ print (printable characters including space),
+ punct (punctuation),
+ space (any white space),
+ upper (upper-case letters),
+ and xdigit (hexadecimal digits).
+ The behavior of these standard character classes is generally
+ consistent across platforms for characters in the 7-bit ASCII set.
+ Whether a given non-ASCII character is considered to belong to one
+ of these classes depends on the collation
+ that is used for the regular-expression function or operator
+ (see Section 24.2), or by default on the
+ database's LC_CTYPE locale setting (see
+ Section 24.1). The classification of non-ASCII
+ characters can vary across platforms even in similarly-named
+ locales. (But the C locale never considers any
+ non-ASCII characters to belong to any of these classes.)
+ In addition to these standard character
+ classes, PostgreSQL defines
+ the word character class, which is the same as
+ alnum plus the underscore (_)
+ character, and
+ the ascii character class, which contains exactly
+ the 7-bit ASCII set.
+
+ There are two special cases of bracket expressions: the bracket
+ expressions [[:<:]] and
+ [[:>:]] are constraints,
+ matching empty strings at the beginning
+ and end of a word respectively. A word is defined as a sequence
+ of word characters that is neither preceded nor followed by word
+ characters. A word character is any character belonging to the
+ word character class, that is, any letter, digit,
+ or underscore. This is an extension, compatible with but not
+ specified by POSIX 1003.2, and should be used with
+ caution in software intended to be portable to other systems.
+ The constraint escapes described below are usually preferable; they
+ are no more standard, but are easier to type.
+
+ Escapes are special sequences beginning with \
+ followed by an alphanumeric character. Escapes come in several varieties:
+ character entry, class shorthands, constraint escapes, and back references.
+ A \ followed by an alphanumeric character but not constituting
+ a valid escape is illegal in AREs.
+ In EREs, there are no escapes: outside a bracket expression,
+ a \ followed by an alphanumeric character merely stands for
+ that character as an ordinary character, and inside a bracket expression,
+ \ is an ordinary character.
+ (The latter is the one actual incompatibility between EREs and AREs.)
+
+ Character-entry escapes exist to make it easier to specify
+ non-printing and other inconvenient characters in REs. They are
+ shown in Table 9.20.
+
+ Class-shorthand escapes provide shorthands for certain
+ commonly-used character classes. They are
+ shown in Table 9.21.
+
+ A constraint escape is a constraint,
+ matching the empty string if specific conditions are met,
+ written as an escape. They are
+ shown in Table 9.22.
+
+ A back reference (\n) matches the
+ same string matched by the previous parenthesized subexpression specified
+ by the number n
+ (see Table 9.23). For example,
+ ([bc])\1 matches bb or cc
+ but not bc or cb.
+ The subexpression must entirely precede the back reference in the RE.
+ Subexpressions are numbered in the order of their leading parentheses.
+ Non-capturing parentheses do not define subexpressions.
+ The back reference considers only the string characters matched by the
+ referenced subexpression, not any constraints contained in it. For
+ example, (^\d)\1 will match 22.
+
synonym for backslash (\) to help reduce the need for backslash
+ doubling
\cX
(where X is any character) the character whose
+ low-order 5 bits are the same as those of
+ X, and whose other bits are all zero
\e
the character whose collating-sequence name
+ is ESC,
+ or failing that, the character with octal value 033
\f
form feed, as in C
\n
newline, as in C
\r
carriage return, as in C
\t
horizontal tab, as in C
\uwxyz
(where wxyz is exactly four hexadecimal digits)
+ the character whose hexadecimal value is
+ 0xwxyz
+
\Ustuvwxyz
(where stuvwxyz is exactly eight hexadecimal
+ digits)
+ the character whose hexadecimal value is
+ 0xstuvwxyz
+
\v
vertical tab, as in C
\xhhh
(where hhh is any sequence of hexadecimal
+ digits)
+ the character whose hexadecimal value is
+ 0xhhh
+ (a single character no matter how many hexadecimal digits are used)
+
\0
the character whose value is 0 (the null byte)
\xy
(where xy is exactly two octal digits,
+ and is not a back reference)
+ the character whose octal value is
+ 0xy
\xyz
(where xyz is exactly three octal digits,
+ and is not a back reference)
+ the character whose octal value is
+ 0xyz
+ Hexadecimal digits are 0-9,
+ a-f, and A-F.
+ Octal digits are 0-7.
+
+ Numeric character-entry escapes specifying values outside the ASCII range
+ (0–127) have meanings dependent on the database encoding. When the
+ encoding is UTF-8, escape values are equivalent to Unicode code points,
+ for example \u1234 means the character U+1234.
+ For other multibyte encodings, character-entry escapes usually just
+ specify the concatenation of the byte values for the character. If the
+ escape value does not correspond to any legal character in the database
+ encoding, no error will be raised, but it will never match any data.
+
+ The character-entry escapes are always taken as ordinary characters.
+ For example, \135 is ] in ASCII, but
+ \135 does not terminate a bracket expression.
+
matches any whitespace character, like
+ [[:space:]]
\w
matches any word character, like
+ [[:word:]]
\D
matches any non-digit, like
+ [^[:digit:]]
\S
matches any non-whitespace character, like
+ [^[:space:]]
\W
matches any non-word character, like
+ [^[:word:]]
+ The class-shorthand escapes also work within bracket expressions,
+ although the definitions shown above are not quite syntactically
+ valid in that context.
+ For example, [a-c\d] is equivalent to
+ [a-c[:digit:]].
+
Table 9.22. Regular Expression Constraint Escapes
Escape
Description
\A
matches only at the beginning of the string
+ (see Section 9.7.3.5 for how this differs from
+ ^)
\m
matches only at the beginning of a word
\M
matches only at the end of a word
\y
matches only at the beginning or end of a word
\Y
matches only at a point that is not the beginning or end of a
+ word
\Z
matches only at the end of the string
+ (see Section 9.7.3.5 for how this differs from
+ $)
+ A word is defined as in the specification of
+ [[:<:]] and [[:>:]] above.
+ Constraint escapes are illegal within bracket expressions.
+
Table 9.23. Regular Expression Back References
Escape
Description
\m
(where m is a nonzero digit)
+ a back reference to the m'th subexpression
\mnn
(where m is a nonzero digit, and
+ nn is some more digits, and the decimal value
+ mnn is not greater than the number of closing capturing
+ parentheses seen so far)
+ a back reference to the mnn'th subexpression
Note
+ There is an inherent ambiguity between octal character-entry
+ escapes and back references, which is resolved by the following heuristics,
+ as hinted at above.
+ A leading zero always indicates an octal escape.
+ A single non-zero digit, not followed by another digit,
+ is always taken as a back reference.
+ A multi-digit sequence not starting with a zero is taken as a back
+ reference if it comes after a suitable subexpression
+ (i.e., the number is in the legal range for a back reference),
+ and otherwise is taken as octal.
+
+ In addition to the main syntax described above, there are some special
+ forms and miscellaneous syntactic facilities available.
+
+ An RE can begin with one of two special director prefixes.
+ If an RE begins with ***:,
+ the rest of the RE is taken as an ARE. (This normally has no effect in
+ PostgreSQL, since REs are assumed to be AREs;
+ but it does have an effect if ERE or BRE mode had been specified by
+ the flags parameter to a regex function.)
+ If an RE begins with ***=,
+ the rest of the RE is taken to be a literal string,
+ with all characters considered ordinary characters.
+
+ An ARE can begin with embedded options:
+ a sequence (?xyz)
+ (where xyz is one or more alphabetic characters)
+ specifies options affecting the rest of the RE.
+ These options override any previously determined options —
+ in particular, they can override the case-sensitivity behavior implied by
+ a regex operator, or the flags parameter to a regex
+ function.
+ The available option letters are
+ shown in Table 9.24.
+ Note that these same option letters are used in the flags
+ parameters of regex functions.
+
Table 9.24. ARE Embedded-Option Letters
Option
Description
b
rest of RE is a BRE
c
case-sensitive matching (overrides operator type)
e
rest of RE is an ERE
i
case-insensitive matching (see
+ Section 9.7.3.5) (overrides operator type)
rest of RE is a literal (“quoted”) string, all ordinary
+ characters
s
non-newline-sensitive matching (default)
t
tight syntax (default; see below)
w
inverse partial newline-sensitive (“weird”) matching
+ (see Section 9.7.3.5)
x
expanded syntax (see below)
+ Embedded options take effect at the ) terminating the sequence.
+ They can appear only at the start of an ARE (after the
+ ***: director if any).
+
+ In addition to the usual (tight) RE syntax, in which all
+ characters are significant, there is an expanded syntax,
+ available by specifying the embedded x option.
+ In the expanded syntax,
+ white-space characters in the RE are ignored, as are
+ all characters between a #
+ and the following newline (or the end of the RE). This
+ permits paragraphing and commenting a complex RE.
+ There are three exceptions to that basic rule:
+
+
+ a white-space character or # preceded by \ is
+ retained
+
+ white space or # within a bracket expression is retained
+
+ white space and comments cannot appear within multi-character symbols,
+ such as (?:
+
+
+ For this purpose, white-space characters are blank, tab, newline, and
+ any character that belongs to the space character class.
+
+ Finally, in an ARE, outside bracket expressions, the sequence
+ (?#ttt)
+ (where ttt is any text not containing a ))
+ is a comment, completely ignored.
+ Again, this is not allowed between the characters of
+ multi-character symbols, like (?:.
+ Such comments are more a historical artifact than a useful facility,
+ and their use is deprecated; use the expanded syntax instead.
+
+ None of these metasyntax extensions is available if
+ an initial ***= director
+ has specified that the user's input be treated as a literal string
+ rather than as an RE.
+
+ In the event that an RE could match more than one substring of a given
+ string, the RE matches the one starting earliest in the string.
+ If the RE could match more than one substring starting at that point,
+ either the longest possible match or the shortest possible match will
+ be taken, depending on whether the RE is greedy or
+ non-greedy.
+
+ Whether an RE is greedy or not is determined by the following rules:
+
+ Most atoms, and all constraints, have no greediness attribute (because
+ they cannot match variable amounts of text anyway).
+
+ Adding parentheses around an RE does not change its greediness.
+
+ A quantified atom with a fixed-repetition quantifier
+ ({m}
+ or
+ {m}?)
+ has the same greediness (possibly none) as the atom itself.
+
+ A quantified atom with other normal quantifiers (including
+ {m,n}
+ with m equal to n)
+ is greedy (prefers longest match).
+
+ A quantified atom with a non-greedy quantifier (including
+ {m,n}?
+ with m equal to n)
+ is non-greedy (prefers shortest match).
+
+ A branch — that is, an RE that has no top-level
+ | operator — has the same greediness as the first
+ quantified atom in it that has a greediness attribute.
+
+ An RE consisting of two or more branches connected by the
+ | operator is always greedy.
+
+
+ The above rules associate greediness attributes not only with individual
+ quantified atoms, but with branches and entire REs that contain quantified
+ atoms. What that means is that the matching is done in such a way that
+ the branch, or whole RE, matches the longest or shortest possible
+ substring as a whole. Once the length of the entire match
+ is determined, the part of it that matches any particular subexpression
+ is determined on the basis of the greediness attribute of that
+ subexpression, with subexpressions starting earlier in the RE taking
+ priority over ones starting later.
+
+ In the first case, the RE as a whole is greedy because Y*
+ is greedy. It can match beginning at the Y, and it matches
+ the longest possible string starting there, i.e., Y123.
+ The output is the parenthesized part of that, or 123.
+ In the second case, the RE as a whole is non-greedy because Y*?
+ is non-greedy. It can match beginning at the Y, and it matches
+ the shortest possible string starting there, i.e., Y1.
+ The subexpression [0-9]{1,3} is greedy but it cannot change
+ the decision as to the overall match length; so it is forced to match
+ just 1.
+
+ In short, when an RE contains both greedy and non-greedy subexpressions,
+ the total match length is either as long as possible or as short as
+ possible, according to the attribute assigned to the whole RE. The
+ attributes assigned to the subexpressions only affect how much of that
+ match they are allowed to “eat” relative to each other.
+
+ The quantifiers {1,1} and {1,1}?
+ can be used to force greediness or non-greediness, respectively,
+ on a subexpression or a whole RE.
+ This is useful when you need the whole RE to have a greediness attribute
+ different from what's deduced from its elements. As an example,
+ suppose that we are trying to separate a string containing some digits
+ into the digits and the parts before and after them. We might try to
+ do that like this:
+
+ That didn't work: the first .* is greedy so
+ it “eats” as much as it can, leaving the \d+ to
+ match at the last possible place, the last digit. We might try to fix
+ that by making it non-greedy:
+
+ That didn't work either, because now the RE as a whole is non-greedy
+ and so it ends the overall match as soon as possible. We can get what
+ we want by forcing the RE as a whole to be greedy:
+
+ Controlling the RE's overall greediness separately from its components'
+ greediness allows great flexibility in handling variable-length patterns.
+
+ When deciding what is a longer or shorter match,
+ match lengths are measured in characters, not collating elements.
+ An empty string is considered longer than no match at all.
+ For example:
+ bb*
+ matches the three middle characters of abbbc;
+ (week|wee)(night|knights)
+ matches all ten characters of weeknights;
+ when (.*).*
+ is matched against abc the parenthesized subexpression
+ matches all three characters; and when
+ (a*)* is matched against bc
+ both the whole RE and the parenthesized
+ subexpression match an empty string.
+
+ If case-independent matching is specified,
+ the effect is much as if all case distinctions had vanished from the
+ alphabet.
+ When an alphabetic that exists in multiple cases appears as an
+ ordinary character outside a bracket expression, it is effectively
+ transformed into a bracket expression containing both cases,
+ e.g., x becomes [xX].
+ When it appears inside a bracket expression, all case counterparts
+ of it are added to the bracket expression, e.g.,
+ [x] becomes [xX]
+ and [^x] becomes [^xX].
+
+ If newline-sensitive matching is specified, .
+ and bracket expressions using ^
+ will never match the newline character
+ (so that matches will not cross lines unless the RE
+ explicitly includes a newline)
+ and ^ and $
+ will match the empty string after and before a newline
+ respectively, in addition to matching at beginning and end of string
+ respectively.
+ But the ARE escapes \A and \Z
+ continue to match beginning or end of string only.
+ Also, the character class shorthands \D
+ and \W will match a newline regardless of this mode.
+ (Before PostgreSQL 14, they did not match
+ newlines when in newline-sensitive mode.
+ Write [^[:digit:]]
+ or [^[:word:]] to get the old behavior.)
+
+ If partial newline-sensitive matching is specified,
+ this affects . and bracket expressions
+ as with newline-sensitive matching, but not ^
+ and $.
+
+ If inverse partial newline-sensitive matching is specified,
+ this affects ^ and $
+ as with newline-sensitive matching, but not .
+ and bracket expressions.
+ This isn't very useful but is provided for symmetry.
+
+ No particular limit is imposed on the length of REs in this
+ implementation. However,
+ programs intended to be highly portable should not employ REs longer
+ than 256 bytes,
+ as a POSIX-compliant implementation can refuse to accept such REs.
+
+ The only feature of AREs that is actually incompatible with
+ POSIX EREs is that \ does not lose its special
+ significance inside bracket expressions.
+ All other ARE features use syntax which is illegal or has
+ undefined or unspecified effects in POSIX EREs;
+ the *** syntax of directors likewise is outside the POSIX
+ syntax for both BREs and EREs.
+
+ Many of the ARE extensions are borrowed from Perl, but some have
+ been changed to clean them up, and a few Perl extensions are not present.
+ Incompatibilities of note include \b, \B,
+ the lack of special treatment for a trailing newline,
+ the addition of complemented bracket expressions to the things
+ affected by newline-sensitive matching,
+ the restrictions on parentheses and back references in lookahead/lookbehind
+ constraints, and the longest/shortest-match (rather than first-match)
+ matching semantics.
+
+ BREs differ from EREs in several respects.
+ In BREs, |, +, and ?
+ are ordinary characters and there is no equivalent
+ for their functionality.
+ The delimiters for bounds are
+ \{ and \},
+ with { and }
+ by themselves ordinary characters.
+ The parentheses for nested subexpressions are
+ \( and \),
+ with ( and ) by themselves ordinary characters.
+ ^ is an ordinary character except at the beginning of the
+ RE or the beginning of a parenthesized subexpression,
+ $ is an ordinary character except at the end of the
+ RE or the end of a parenthesized subexpression,
+ and * is an ordinary character if it appears at the beginning
+ of the RE or the beginning of a parenthesized subexpression
+ (after a possible leading ^).
+ Finally, single-digit back references are available, and
+ \< and \>
+ are synonyms for
+ [[:<:]] and [[:>:]]
+ respectively; no other escapes are available in BREs.
+
9.7.3.8. Differences from SQL Standard and XQuery #
+ Since SQL:2008, the SQL standard includes regular expression operators
+ and functions that performs pattern
+ matching according to the XQuery regular expression
+ standard:
+
LIKE_REGEX
OCCURRENCES_REGEX
POSITION_REGEX
SUBSTRING_REGEX
TRANSLATE_REGEX
+ PostgreSQL does not currently implement these
+ operators and functions. You can get approximately equivalent
+ functionality in each case as shown in Table 9.25. (Various optional clauses on
+ both sides have been omitted in this table.)
+
TRANSLATE_REGEX(pattern IN string WITH replacement)
regexp_replace(string, pattern, replacement)
+ Regular expression functions similar to those provided by PostgreSQL are
+ also available in a number of other SQL implementations, whereas the
+ SQL-standard functions are not as widely implemented. Some of the
+ details of the regular expression syntax will likely differ in each
+ implementation.
+
+ The SQL-standard operators and functions use XQuery regular expressions,
+ which are quite close to the ARE syntax described above.
+ Notable differences between the existing POSIX-based
+ regular-expression feature and XQuery regular expressions include:
+
+
+ XQuery character class subtraction is not supported. An example of
+ this feature is using the following to match only English
+ consonants: [a-z-[aeiou]].
+
+ XQuery character class shorthands \c,
+ \C, \i,
+ and \I are not supported.
+
+ XQuery character class elements
+ using \p{UnicodeProperty} or the
+ inverse \P{UnicodeProperty} are not supported.
+
+ POSIX interprets character classes such as \w
+ (see Table 9.21)
+ according to the prevailing locale (which you can control by
+ attaching a COLLATE clause to the operator or
+ function). XQuery specifies these classes by reference to Unicode
+ character properties, so equivalent behavior is obtained only with
+ a locale that follows the Unicode rules.
+
+ The SQL standard (not XQuery itself) attempts to cater for more
+ variants of “newline” than POSIX does. The
+ newline-sensitive matching options described above consider only
+ ASCII NL (\n) to be a newline, but SQL would have
+ us treat CR (\r), CRLF (\r\n)
+ (a Windows-style newline), and some Unicode-only characters like
+ LINE SEPARATOR (U+2028) as newlines as well.
+ Notably, . and \s should
+ count \r\n as one character not two according to
+ SQL.
+
+ Of the character-entry escapes described in
+ Table 9.20,
+ XQuery supports only \n, \r,
+ and \t.
+
+ XQuery does not support
+ the [:name:] syntax
+ for character classes within bracket expressions.
+
+ XQuery does not have lookahead or lookbehind constraints,
+ nor any of the constraint escapes described in
+ Table 9.22.
+
+ The metasyntax forms described in Section 9.7.3.4
+ do not exist in XQuery.
+
+ The regular expression flag letters defined by XQuery are
+ related to but not the same as the option letters for POSIX
+ (Table 9.24). While the
+ i and q options behave the
+ same, others do not:
+
+ XQuery's s (allow dot to match newline)
+ and m (allow ^
+ and $ to match at newlines) flags provide
+ access to the same behaviors as
+ POSIX's n, p
+ and w flags, but they
+ do not match the behavior of
+ POSIX's s and m flags.
+ Note in particular that dot-matches-newline is the default
+ behavior in POSIX but not XQuery.
+
+ XQuery's x (ignore whitespace in pattern) flag
+ is noticeably different from POSIX's expanded-mode flag.
+ POSIX's x flag also
+ allows # to begin a comment in the pattern,
+ and POSIX will not ignore a whitespace character after a
+ backslash.
+
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-math.html b/pgsql/doc/postgresql/html/functions-math.html
new file mode 100644
index 0000000000000000000000000000000000000000..e5e3f8259fae9c9ba0d4299e631f794319e901be
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-math.html
@@ -0,0 +1,1042 @@
+
+9.3. Mathematical Functions and Operators
+ Mathematical operators are provided for many
+ PostgreSQL types. For types without
+ standard mathematical conventions
+ (e.g., date/time types) we
+ describe the actual behavior in subsequent sections.
+
+ Table 9.4 shows the mathematical
+ operators that are available for the standard numeric types.
+ Unless otherwise noted, operators shown as
+ accepting numeric_type are available for all
+ the types smallint, integer,
+ bigint, numeric, real,
+ and double precision.
+ Operators shown as accepting integral_type
+ are available for the types smallint, integer,
+ and bigint.
+ Except where noted, each form of an operator returns the same data type
+ as its argument(s). Calls involving multiple argument data types, such
+ as integer+numeric,
+ are resolved by using the type appearing later in these lists.
+
Table 9.4. Mathematical Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ numeric_type+numeric_type
+ → numeric_type
+
+
+ Addition
+
+
+ 2 + 3
+ → 5
+
+ +numeric_type
+ → numeric_type
+
+
+ Unary plus (no operation)
+
+
+ + 3.5
+ → 3.5
+
+ numeric_type-numeric_type
+ → numeric_type
+
+
+ Subtraction
+
+
+ 2 - 3
+ → -1
+
+ -numeric_type
+ → numeric_type
+
+
+ Negation
+
+
+ - (-4)
+ → 4
+
+ numeric_type*numeric_type
+ → numeric_type
+
+
+ Multiplication
+
+
+ 2 * 3
+ → 6
+
+ numeric_type/numeric_type
+ → numeric_type
+
+
+ Division (for integral types, division truncates the result towards
+ zero)
+
+
+ 5.0 / 2
+ → 2.5000000000000000
+
+
+ 5 / 2
+ → 2
+
+
+ (-5) / 2
+ → -2
+
+ numeric_type%numeric_type
+ → numeric_type
+
+
+ Modulo (remainder); available for smallint,
+ integer, bigint, and numeric
+
+ Unlike typical mathematical practice, multiple uses of
+ ^ will associate left to right by default:
+
+
+ 2 ^ 3 ^ 3
+ → 512
+
+
+ 2 ^ (3 ^ 3)
+ → 134217728
+
+ |/double precision
+ → double precision
+
+
+ Square root
+
+
+ |/ 25.0
+ → 5
+
+ ||/double precision
+ → double precision
+
+
+ Cube root
+
+
+ ||/ 64.0
+ → 4
+
+ @numeric_type
+ → numeric_type
+
+
+ Absolute value
+
+
+ @ -5.0
+ → 5.0
+
+ integral_type&integral_type
+ → integral_type
+
+
+ Bitwise AND
+
+
+ 91 & 15
+ → 11
+
+ integral_type|integral_type
+ → integral_type
+
+
+ Bitwise OR
+
+
+ 32 | 3
+ → 35
+
+ integral_type#integral_type
+ → integral_type
+
+
+ Bitwise exclusive OR
+
+
+ 17 # 5
+ → 20
+
+ ~integral_type
+ → integral_type
+
+
+ Bitwise NOT
+
+
+ ~1
+ → -2
+
+ integral_type<<integer
+ → integral_type
+
+
+ Bitwise shift left
+
+
+ 1 << 4
+ → 16
+
+ integral_type>>integer
+ → integral_type
+
+
+ Bitwise shift right
+
+
+ 8 >> 2
+ → 2
+
+ Table 9.5 shows the available
+ mathematical functions.
+ Many of these functions are provided in multiple forms with different
+ argument types.
+ Except where noted, any given form of a function returns the same
+ data type as its argument(s); cross-type cases are resolved in the
+ same way as explained above for operators.
+ The functions working with double precision data are mostly
+ implemented on top of the host system's C library; accuracy and behavior in
+ boundary cases can therefore vary depending on the host system.
+
+ Greatest common divisor (the largest positive number that divides both
+ inputs with no remainder); returns 0 if both inputs
+ are zero; available for integer, bigint,
+ and numeric
+
+ Least common multiple (the smallest strictly positive number that is
+ an integral multiple of both inputs); returns 0 if
+ either input is zero; available for integer,
+ bigint, and numeric
+
+ Rounds to nearest integer. For numeric, ties are
+ broken by rounding away from zero. For double precision,
+ the tie-breaking behavior is platform dependent, but
+ “round to nearest even” is the most common rule.
+
+
+ round(42.4)
+ → 42
+
+ round ( vnumeric, sinteger )
+ → numeric
+
+
+ Rounds v to s decimal
+ places. Ties are broken by rounding away from zero.
+
+
+ round(42.4382, 2)
+ → 42.44
+
+
+ round(1234.56, -1)
+ → 1230
+
+
+ scale ( numeric )
+ → integer
+
+
+ Scale of the argument (the number of decimal digits in the fractional part)
+
+ Returns the number of the bucket in
+ which operand falls in a histogram
+ having count equal-width buckets spanning the
+ range low to high.
+ Returns 0
+ or count+1 for an input
+ outside that range.
+
+ Returns the number of the bucket in
+ which operand falls given an array listing the
+ lower bounds of the buckets. Returns 0 for an
+ input less than the first lower
+ bound. operand and the array elements can be
+ of any type having standard comparison operators.
+ The thresholds array must be
+ sorted, smallest first, or unexpected results will be
+ obtained.
+
+ Returns a random value from the normal distribution with the given
+ parameters; mean defaults to 0.0
+ and stddev defaults to 1.0
+
+
+ random_normal(0.0, 1.0)
+ → 0.051285419
+
+
+ setseed ( double precision )
+ → void
+
+
+ Sets the seed for subsequent random() and
+ random_normal() calls;
+ argument must be between -1.0 and 1.0, inclusive
+
+
+ setseed(0.12345)
+
+ The random() function uses a deterministic
+ pseudo-random number generator.
+ It is fast but not suitable for cryptographic
+ applications; see the pgcrypto module for a more
+ secure alternative.
+ If setseed() is called, the series of results of
+ subsequent random() calls in the current session
+ can be repeated by re-issuing setseed() with the same
+ argument.
+ Without any prior setseed() call in the same
+ session, the first random() call obtains a seed
+ from a platform-dependent source of random bits.
+ These remarks hold equally for random_normal().
+
+ Table 9.7 shows the
+ available trigonometric functions. Each of these functions comes in
+ two variants, one that measures angles in radians and one that
+ measures angles in degrees.
+
+ Another way to work with angles measured in degrees is to use the unit
+ transformation functions radians()
+ and degrees() shown earlier.
+ However, using the degree-based trigonometric functions is preferred,
+ as that way avoids round-off error for special cases such
+ as sind(30).
+
+ Table 9.8 shows the
+ available hyperbolic functions.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-net.html b/pgsql/doc/postgresql/html/functions-net.html
new file mode 100644
index 0000000000000000000000000000000000000000..d685d84c18d63b0a9a63f7435b78caa197cc95f2
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-net.html
@@ -0,0 +1,397 @@
+
+9.12. Network Address Functions and Operators
+ The IP network address types, cidr and inet,
+ support the usual comparison operators shown in
+ Table 9.1
+ as well as the specialized operators and functions shown in
+ Table 9.39 and
+ Table 9.40.
+
+ Any cidr value can be cast to inet implicitly;
+ therefore, the operators and functions shown below as operating on
+ inet also work on cidr values. (Where there are
+ separate functions for inet and cidr, it is
+ because the behavior should be different for the two cases.)
+ Also, it is permitted to cast an inet value
+ to cidr. When this is done, any bits to the right of the
+ netmask are silently zeroed to create a valid cidr value.
+
Table 9.39. IP Address Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ inet<<inet
+ → boolean
+
+
+ Is subnet strictly contained by subnet?
+ This operator, and the next four, test for subnet inclusion. They
+ consider only the network parts of the two addresses (ignoring any
+ bits to the right of the netmasks) and determine whether one network
+ is identical to or a subnet of the other.
+
+
+ inet '192.168.1.5' << inet '192.168.1/24'
+ → t
+
+
+ inet '192.168.0.5' << inet '192.168.1/24'
+ → f
+
+
+ inet '192.168.1/24' << inet '192.168.1/24'
+ → f
+
+ inet<<=inet
+ → boolean
+
+
+ Is subnet contained by or equal to subnet?
+
+
+ inet '192.168.1/24' <<= inet '192.168.1/24'
+ → t
+
+ inet>>inet
+ → boolean
+
+
+ Does subnet strictly contain subnet?
+
+
+ inet '192.168.1/24' >> inet '192.168.1.5'
+ → t
+
+ inet>>=inet
+ → boolean
+
+
+ Does subnet contain or equal subnet?
+
+
+ inet '192.168.1/24' >>= inet '192.168.1/24'
+ → t
+
+ inet&&inet
+ → boolean
+
+
+ Does either subnet contain or equal the other?
+
+
+ inet '192.168.1/24' && inet '192.168.1.80/28'
+ → t
+
+
+ inet '192.168.1/24' && inet '192.168.2.0/28'
+ → f
+
+ Creates an abbreviated display format as text.
+ (The result is the same as the inet output function
+ produces; it is “abbreviated” only in comparison to the
+ result of an explicit cast to text, which for historical
+ reasons will never suppress the netmask part.)
+
+
+ abbrev(inet '10.1.0.0/32')
+ → 10.1.0.0
+
+ abbrev ( cidr )
+ → text
+
+
+ Creates an abbreviated display format as text.
+ (The abbreviation consists of dropping all-zero octets to the right
+ of the netmask; more examples are in
+ Table 8.22.)
+
+
+ abbrev(cidr '10.1.0.0/16')
+ → 10.1/16
+
+
+ broadcast ( inet )
+ → inet
+
+
+ Computes the broadcast address for the address's network.
+
+ Returns the network part of the address, zeroing out
+ whatever is to the right of the netmask.
+ (This is equivalent to casting the value to cidr.)
+
+ Returns the unabbreviated IP address and netmask length as text.
+ (This has the same result as an explicit cast to text.)
+
+
+ text(inet '192.168.1.5')
+ → 192.168.1.5/32
+
Tip
+ The abbrev, host,
+ and text functions are primarily intended to offer
+ alternative display formats for IP addresses.
+
+ The MAC address types, macaddr and macaddr8,
+ support the usual comparison operators shown in
+ Table 9.1
+ as well as the specialized functions shown in
+ Table 9.41.
+ In addition, they support the bitwise logical operators
+ ~, & and |
+ (NOT, AND and OR), just as shown above for IP addresses.
+
Table 9.41. MAC Address Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ trunc ( macaddr )
+ → macaddr
+
+
+ Sets the last 3 bytes of the address to zero. The remaining prefix
+ can be associated with a particular manufacturer (using data not
+ included in PostgreSQL).
+
+ Sets the last 5 bytes of the address to zero. The remaining prefix
+ can be associated with a particular manufacturer (using data not
+ included in PostgreSQL).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-range.html b/pgsql/doc/postgresql/html/functions-range.html
new file mode 100644
index 0000000000000000000000000000000000000000..e2859dc7607f11f7e7ecd9a7c7d6cd50d8f1e58e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-range.html
@@ -0,0 +1,711 @@
+
+9.20. Range/Multirange Functions and Operators
+ See Section 8.17 for an overview of range types.
+
+ Table 9.55 shows the specialized operators
+ available for range types.
+ Table 9.56 shows the specialized operators
+ available for multirange types.
+ In addition to those, the usual comparison operators shown in
+ Table 9.1 are available for range
+ and multirange types. The comparison operators order first by the range lower
+ bounds, and only if those are equal do they compare the upper bounds. The
+ multirange operators compare each range until one is unequal. This
+ does not usually result in a useful overall ordering, but the operators are
+ provided to allow unique indexes to be constructed on ranges.
+
Table 9.55. Range Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ anyrange@>anyrange
+ → boolean
+
+
+ Does the first range contain the second?
+
+
+ int4range(2,4) @> int4range(2,3)
+ → t
+
+ anyrange@>anyelement
+ → boolean
+
+
+ Does the range contain the element?
+
+
+ '[2011-01-01,2011-03-01)'::tsrange @> '2011-01-10'::timestamp
+ → t
+
+ anyrange<@anyrange
+ → boolean
+
+
+ Is the first range contained by the second?
+
+
+ int4range(2,4) <@ int4range(1,7)
+ → t
+
+ anyelement<@anyrange
+ → boolean
+
+
+ Is the element contained in the range?
+
+
+ 42 <@ int4range(1,7)
+ → f
+
+ anyrange&&anyrange
+ → boolean
+
+
+ Do the ranges overlap, that is, have any elements in common?
+
+
+ int8range(3,7) && int8range(4,12)
+ → t
+
+ anyrange<<anyrange
+ → boolean
+
+
+ Is the first range strictly left of the second?
+
+
+ int8range(1,10) << int8range(100,110)
+ → t
+
+ anyrange>>anyrange
+ → boolean
+
+
+ Is the first range strictly right of the second?
+
+
+ int8range(50,60) >> int8range(20,30)
+ → t
+
+ anyrange&<anyrange
+ → boolean
+
+
+ Does the first range not extend to the right of the second?
+
+
+ int8range(1,20) &< int8range(18,20)
+ → t
+
+ anyrange&>anyrange
+ → boolean
+
+
+ Does the first range not extend to the left of the second?
+
+
+ int8range(7,20) &> int8range(5,10)
+ → t
+
+ anyrange-|-anyrange
+ → boolean
+
+
+ Are the ranges adjacent?
+
+
+ numrange(1.1,2.2) -|- numrange(2.2,3.3)
+ → t
+
+ anyrange+anyrange
+ → anyrange
+
+
+ Computes the union of the ranges. The ranges must overlap or be
+ adjacent, so that the union is a single range (but
+ see range_merge()).
+
+ Computes the difference of the ranges. The second range must not be
+ contained in the first in such a way that the difference would not be
+ a single range.
+
+
+ int8range(5,15) - int8range(10,20)
+ → [5,10)
+
Table 9.56. Multirange Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ anymultirange@>anymultirange
+ → boolean
+
+
+ Does the first multirange contain the second?
+
+
+ '{[2,4)}'::int4multirange @> '{[2,3)}'::int4multirange
+ → t
+
+ anymultirange@>anyrange
+ → boolean
+
+
+ Does the multirange contain the range?
+
+
+ '{[2,4)}'::int4multirange @> int4range(2,3)
+ → t
+
+ anymultirange@>anyelement
+ → boolean
+
+
+ Does the multirange contain the element?
+
+
+ '{[2011-01-01,2011-03-01)}'::tsmultirange @> '2011-01-10'::timestamp
+ → t
+
+ anyrange@>anymultirange
+ → boolean
+
+
+ Does the range contain the multirange?
+
+
+ '[2,4)'::int4range @> '{[2,3)}'::int4multirange
+ → t
+
+ anymultirange<@anymultirange
+ → boolean
+
+
+ Is the first multirange contained by the second?
+
+
+ '{[2,4)}'::int4multirange <@ '{[1,7)}'::int4multirange
+ → t
+
+ anymultirange<@anyrange
+ → boolean
+
+
+ Is the multirange contained by the range?
+
+
+ '{[2,4)}'::int4multirange <@ int4range(1,7)
+ → t
+
+ anyrange<@anymultirange
+ → boolean
+
+
+ Is the range contained by the multirange?
+
+
+ int4range(2,4) <@ '{[1,7)}'::int4multirange
+ → t
+
+ anyelement<@anymultirange
+ → boolean
+
+
+ Is the element contained by the multirange?
+
+
+ 4 <@ '{[1,7)}'::int4multirange
+ → t
+
+ anymultirange&&anymultirange
+ → boolean
+
+
+ Do the multiranges overlap, that is, have any elements in common?
+
+
+ '{[3,7)}'::int8multirange && '{[4,12)}'::int8multirange
+ → t
+
+ anymultirange&&anyrange
+ → boolean
+
+
+ Does the multirange overlap the range?
+
+
+ '{[3,7)}'::int8multirange && int8range(4,12)
+ → t
+
+ anyrange&&anymultirange
+ → boolean
+
+
+ Does the range overlap the multirange?
+
+
+ int8range(3,7) && '{[4,12)}'::int8multirange
+ → t
+
+ anymultirange<<anymultirange
+ → boolean
+
+
+ Is the first multirange strictly left of the second?
+
+
+ '{[1,10)}'::int8multirange << '{[100,110)}'::int8multirange
+ → t
+
+ anymultirange<<anyrange
+ → boolean
+
+
+ Is the multirange strictly left of the range?
+
+
+ '{[1,10)}'::int8multirange << int8range(100,110)
+ → t
+
+ anyrange<<anymultirange
+ → boolean
+
+
+ Is the range strictly left of the multirange?
+
+
+ int8range(1,10) << '{[100,110)}'::int8multirange
+ → t
+
+ anymultirange>>anymultirange
+ → boolean
+
+
+ Is the first multirange strictly right of the second?
+
+
+ '{[50,60)}'::int8multirange >> '{[20,30)}'::int8multirange
+ → t
+
+ anymultirange>>anyrange
+ → boolean
+
+
+ Is the multirange strictly right of the range?
+
+
+ '{[50,60)}'::int8multirange >> int8range(20,30)
+ → t
+
+ anyrange>>anymultirange
+ → boolean
+
+
+ Is the range strictly right of the multirange?
+
+
+ int8range(50,60) >> '{[20,30)}'::int8multirange
+ → t
+
+ anymultirange&<anymultirange
+ → boolean
+
+
+ Does the first multirange not extend to the right of the second?
+
+
+ '{[1,20)}'::int8multirange &< '{[18,20)}'::int8multirange
+ → t
+
+ anymultirange&<anyrange
+ → boolean
+
+
+ Does the multirange not extend to the right of the range?
+
+
+ '{[1,20)}'::int8multirange &< int8range(18,20)
+ → t
+
+ anyrange&<anymultirange
+ → boolean
+
+
+ Does the range not extend to the right of the multirange?
+
+
+ int8range(1,20) &< '{[18,20)}'::int8multirange
+ → t
+
+ anymultirange&>anymultirange
+ → boolean
+
+
+ Does the first multirange not extend to the left of the second?
+
+
+ '{[7,20)}'::int8multirange &> '{[5,10)}'::int8multirange
+ → t
+
+ anymultirange&>anyrange
+ → boolean
+
+
+ Does the multirange not extend to the left of the range?
+
+
+ '{[7,20)}'::int8multirange &> int8range(5,10)
+ → t
+
+ anyrange&>anymultirange
+ → boolean
+
+
+ Does the range not extend to the left of the multirange?
+
+
+ int8range(7,20) &> '{[5,10)}'::int8multirange
+ → t
+
+ anymultirange-|-anymultirange
+ → boolean
+
+
+ Are the multiranges adjacent?
+
+
+ '{[1.1,2.2)}'::nummultirange -|- '{[2.2,3.3)}'::nummultirange
+ → t
+
+ anymultirange-|-anyrange
+ → boolean
+
+
+ Is the multirange adjacent to the range?
+
+
+ '{[1.1,2.2)}'::nummultirange -|- numrange(2.2,3.3)
+ → t
+
+ anyrange-|-anymultirange
+ → boolean
+
+
+ Is the range adjacent to the multirange?
+
+
+ numrange(1.1,2.2) -|- '{[2.2,3.3)}'::nummultirange
+ → t
+
+ anymultirange+anymultirange
+ → anymultirange
+
+
+ Computes the union of the multiranges. The multiranges need not overlap
+ or be adjacent.
+
+ The left-of/right-of/adjacent operators always return false when an empty
+ range or multirange is involved; that is, an empty range is not considered to
+ be either before or after any other range.
+
+ Elsewhere empty ranges and multiranges are treated as the additive identity:
+ anything unioned with an empty value is itself. Anything minus an empty
+ value is itself. An empty multirange has exactly the same points as an empty
+ range. Every range contains the empty range. Every multirange contains as many
+ empty ranges as you like.
+
+ The range union and difference operators will fail if the resulting range would
+ need to contain two disjoint sub-ranges, as such a range cannot be
+ represented. There are separate operators for union and difference that take
+ multirange parameters and return a multirange, and they do not fail even if
+ their arguments are disjoint. So if you need a union or difference operation
+ for ranges that may be disjoint, you can avoid errors by first casting your
+ ranges to multiranges.
+
+ Table 9.57 shows the functions
+ available for use with range types.
+ Table 9.58 shows the functions
+ available for use with multirange types.
+
Table 9.57. Range Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ lower ( anyrange )
+ → anyelement
+
+
+ Extracts the lower bound of the range (NULL if the
+ range is empty or has no lower bound).
+
+
+ lower(numrange(1.1,2.2))
+ → 1.1
+
+
+ upper ( anyrange )
+ → anyelement
+
+
+ Extracts the upper bound of the range (NULL if the
+ range is empty or has no upper bound).
+
+
+ upper(numrange(1.1,2.2))
+ → 2.2
+
+
+ isempty ( anyrange )
+ → boolean
+
+
+ Is the range empty?
+
+
+ isempty(numrange(1.1,2.2))
+ → f
+
+
+ lower_inc ( anyrange )
+ → boolean
+
+
+ Is the range's lower bound inclusive?
+
+
+ lower_inc(numrange(1.1,2.2))
+ → t
+
+
+ upper_inc ( anyrange )
+ → boolean
+
+
+ Is the range's upper bound inclusive?
+
+
+ upper_inc(numrange(1.1,2.2))
+ → f
+
+
+ lower_inf ( anyrange )
+ → boolean
+
+
+ Does the range have no lower bound? (A lower bound of
+ -Infinity returns false.)
+
+
+ lower_inf('(,)'::daterange)
+ → t
+
+
+ upper_inf ( anyrange )
+ → boolean
+
+
+ Does the range have no upper bound? (An upper bound of
+ Infinity returns false.)
+
+ Returns a multirange containing just the given range.
+
+
+ multirange('[1,2)'::int4range)
+ → {[1,2)}
+
+
+ unnest ( anymultirange )
+ → setof anyrange
+
+
+ Expands a multirange into a set of ranges.
+ The ranges are read out in storage order (ascending).
+
+
+ unnest('{[1,2), [3,4)}'::int4multirange)
+ →
+
+ [1,2)
+ [3,4)
+
+
+ The lower_inc, upper_inc,
+ lower_inf, and upper_inf
+ functions all return false for an empty range or multirange.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-sequence.html b/pgsql/doc/postgresql/html/functions-sequence.html
new file mode 100644
index 0000000000000000000000000000000000000000..fe44957be16a3f327279679d5cf10b2e207a1014
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-sequence.html
@@ -0,0 +1,139 @@
+
+9.17. Sequence Manipulation Functions
+ This section describes functions for operating on sequence
+ objects, also called sequence generators or just sequences.
+ Sequence objects are special single-row tables created with CREATE SEQUENCE.
+ Sequence objects are commonly used to generate unique identifiers
+ for rows of a table. The sequence functions, listed in Table 9.52, provide simple, multiuser-safe
+ methods for obtaining successive sequence values from sequence
+ objects.
+
Table 9.52. Sequence Functions
+ Function
+
+
+ Description
+
+
+ nextval ( regclass )
+ → bigint
+
+
+ Advances the sequence object to its next value and returns that value.
+ This is done atomically: even if multiple sessions
+ execute nextval concurrently, each will safely
+ receive a distinct sequence value.
+ If the sequence object has been created with default parameters,
+ successive nextval calls will return successive
+ values beginning with 1. Other behaviors can be obtained by using
+ appropriate parameters in the CREATE SEQUENCE
+ command.
+
+
+ This function requires USAGE
+ or UPDATE privilege on the sequence.
+
+ Sets the sequence object's current value, and optionally
+ its is_called flag. The two-parameter
+ form sets the sequence's last_value field to the
+ specified value and sets its is_called field to
+ true, meaning that the next
+ nextval will advance the sequence before
+ returning a value. The value that will be reported
+ by currval is also set to the specified value.
+ In the three-parameter form, is_called can be set
+ to either true
+ or false. true has the same
+ effect as the two-parameter form. If it is set
+ to false, the next nextval
+ will return exactly the specified value, and sequence advancement
+ commences with the following nextval.
+ Furthermore, the value reported by currval is not
+ changed in this case. For example,
+
+SELECT setval('myseq', 42); Next nextval will return 43
+SELECT setval('myseq', 42, true); Same as above
+SELECT setval('myseq', 42, false); Next nextval will return 42
+
+ The result returned by setval is just the value of its
+ second argument.
+
+
+ This function requires UPDATE privilege on the
+ sequence.
+
+
+ currval ( regclass )
+ → bigint
+
+
+ Returns the value most recently obtained
+ by nextval for this sequence in the current
+ session. (An error is reported if nextval has
+ never been called for this sequence in this session.) Because this is
+ returning a session-local value, it gives a predictable answer whether
+ or not other sessions have executed nextval since
+ the current session did.
+
+
+ This function requires USAGE
+ or SELECT privilege on the sequence.
+
+
+ lastval ()
+ → bigint
+
+
+ Returns the value most recently returned by
+ nextval in the current session. This function is
+ identical to currval, except that instead
+ of taking the sequence name as an argument it refers to whichever
+ sequence nextval was most recently applied to
+ in the current session. It is an error to call
+ lastval if nextval
+ has not yet been called in the current session.
+
+
+ This function requires USAGE
+ or SELECT privilege on the last used sequence.
+
Caution
+ To avoid blocking concurrent transactions that obtain numbers from
+ the same sequence, the value obtained by nextval
+ is not reclaimed for re-use if the calling transaction later aborts.
+ This means that transaction aborts or database crashes can result in
+ gaps in the sequence of assigned values. That can happen without a
+ transaction abort, too. For example an INSERT with
+ an ON CONFLICT clause will compute the to-be-inserted
+ tuple, including doing any required nextval
+ calls, before detecting any conflict that would cause it to follow
+ the ON CONFLICT rule instead.
+ Thus, PostgreSQL sequence
+ objects cannot be used to obtain “gapless”
+ sequences.
+
+ Likewise, sequence state changes made by setval
+ are immediately visible to other transactions, and are not undone if
+ the calling transaction rolls back.
+
+ If the database cluster crashes before committing a transaction
+ containing a nextval
+ or setval call, the sequence state change might
+ not have made its way to persistent storage, so that it is uncertain
+ whether the sequence will have its original or updated state after the
+ cluster restarts. This is harmless for usage of the sequence within
+ the database, since other effects of uncommitted transactions will not
+ be visible either. However, if you wish to use a sequence value for
+ persistent outside-the-database purposes, make sure that the
+ nextval call has been committed before doing so.
+
+ The sequence to be operated on by a sequence function is specified by
+ a regclass argument, which is simply the OID of the sequence in the
+ pg_class system catalog. You do not have to look up the
+ OID by hand, however, since the regclass data type's input
+ converter will do the work for you. See Section 8.19
+ for details.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-srf.html b/pgsql/doc/postgresql/html/functions-srf.html
new file mode 100644
index 0000000000000000000000000000000000000000..dd0cd7c5a613e88794bb25a9861fe9f674027fe4
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-srf.html
@@ -0,0 +1,241 @@
+
+9.25. Set Returning Functions
+ This section describes functions that possibly return more than one row.
+ The most widely used functions in this class are series generating
+ functions, as detailed in Table 9.65 and
+ Table 9.66. Other, more specialized
+ set-returning functions are described elsewhere in this manual.
+ See Section 7.2.1.4 for ways to combine multiple
+ set-returning functions.
+
+ generate_series ( starttimestamp with time zone, stoptimestamp with time zone, stepinterval [, timezonetext] )
+ → setof timestamp with time zone
+
+
+ Generates a series of values from start
+ to stop, with a step size
+ of step.
+ In the timezone-aware form, times of day and daylight-savings
+ adjustments are computed according to the time zone named by
+ the timezone argument, or the current
+ TimeZone setting if that is omitted.
+
+ When step is positive, zero rows are returned if
+ start is greater than stop.
+ Conversely, when step is negative, zero rows are
+ returned if start is less than stop.
+ Zero rows are also returned if any input is NULL.
+ It is an error
+ for step to be zero. Some examples follow:
+
+ Generates a series comprising the valid subscripts of
+ the dim'th dimension of the given array.
+ When reverse is true, returns the series in
+ reverse order.
+
+ generate_subscripts is a convenience function that generates
+ the set of valid subscripts for the specified dimension of the given
+ array.
+ Zero rows are returned for arrays that do not have the requested dimension,
+ or if any input is NULL.
+ Some examples follow:
+
+-- basic usage:
+SELECT generate_subscripts('{NULL,1,NULL,2}'::int[], 1) AS s;
+ s
+---
+ 1
+ 2
+ 3
+ 4
+(4 rows)
+
+-- presenting an array, the subscript and the subscripted
+-- value requires a subquery:
+SELECT * FROM arrays;
+ a
+--------------------
+ {-1,-2}
+ {100,200,300}
+(2 rows)
+
+SELECT a AS array, s AS subscript, a[s] AS value
+FROM (SELECT generate_subscripts(a, 1) AS s, a FROM arrays) foo;
+ array | subscript | value
+---------------+-----------+-------
+ {-1,-2} | 1 | -1
+ {-1,-2} | 2 | -2
+ {100,200,300} | 1 | 100
+ {100,200,300} | 2 | 200
+ {100,200,300} | 3 | 300
+(5 rows)
+
+-- unnest a 2D array:
+CREATE OR REPLACE FUNCTION unnest2(anyarray)
+RETURNS SETOF anyelement AS $$
+select $1[i][j]
+ from generate_subscripts($1,1) g1(i),
+ generate_subscripts($1,2) g2(j);
+$$ LANGUAGE sql IMMUTABLE;
+CREATE FUNCTION
+SELECT * FROM unnest2(ARRAY[[1,2],[3,4]]);
+ unnest2
+---------
+ 1
+ 2
+ 3
+ 4
+(4 rows)
+
+
+ When a function in the FROM clause is suffixed
+ by WITH ORDINALITY, a bigint column is
+ appended to the function's output column(s), which starts from 1 and
+ increments by 1 for each row of the function's output.
+ This is most useful in the case of set returning
+ functions such as unnest().
+
+
+-- set returning function WITH ORDINALITY:
+SELECT * FROM pg_ls_dir('.') WITH ORDINALITY AS t(ls,n);
+ ls | n
+-----------------+----
+ pg_serial | 1
+ pg_twophase | 2
+ postmaster.opts | 3
+ pg_notify | 4
+ postgresql.conf | 5
+ pg_tblspc | 6
+ logfile | 7
+ base | 8
+ postmaster.pid | 9
+ pg_ident.conf | 10
+ global | 11
+ pg_xact | 12
+ pg_snapshots | 13
+ pg_multixact | 14
+ PG_VERSION | 15
+ pg_wal | 16
+ pg_hba.conf | 17
+ pg_stat_tmp | 18
+ pg_subtrans | 19
+(19 rows)
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-statistics.html b/pgsql/doc/postgresql/html/functions-statistics.html
new file mode 100644
index 0000000000000000000000000000000000000000..351f117fc63a12c53e7a4963ac23f54c7f5daccb
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-statistics.html
@@ -0,0 +1,24 @@
+
+9.30. Statistics Information Functions
+pg_mcv_list_items ( pg_mcv_list ) → setof record
+
+ pg_mcv_list_items returns a set of records describing
+ all items stored in a multi-column MCV list. It
+ returns the following columns:
+
+
Name
Type
Description
index
integer
index of the item in the MCV list
values
text[]
values stored in the MCV item
nulls
boolean[]
flags identifying NULL values
frequency
double precision
frequency of this MCV item
base_frequency
double precision
base frequency of this MCV item
+
+ The pg_mcv_list_items function can be used like this:
+
+
+SELECT m.* FROM pg_statistic_ext join pg_statistic_ext_data on (oid = stxoid),
+ pg_mcv_list_items(stxdmcv) m WHERE stxname = 'stts';
+
+
+ Values of the pg_mcv_list type can be obtained only from the
+ pg_statistic_ext_data.stxdmcv
+ column.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-string.html b/pgsql/doc/postgresql/html/functions-string.html
new file mode 100644
index 0000000000000000000000000000000000000000..99b485462136bd9b454f5e5b9c1f62e6fdaa731f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-string.html
@@ -0,0 +1,1208 @@
+
+9.4. String Functions and Operators
+ This section describes functions and operators for examining and
+ manipulating string values. Strings in this context include values
+ of the types character, character varying,
+ and text. Except where noted, these functions and operators
+ are declared to accept and return type text. They will
+ interchangeably accept character varying arguments.
+ Values of type character will be converted
+ to text before the function or operator is applied, resulting
+ in stripping any trailing spaces in the character value.
+
+ SQL defines some string functions that use
+ key words, rather than commas, to separate
+ arguments. Details are in
+ Table 9.9.
+ PostgreSQL also provides versions of these functions
+ that use the regular function invocation syntax
+ (see Table 9.10).
+
Note
+ The string concatenation operator (||) will accept
+ non-string input, so long as at least one input is of string type, as shown
+ in Table 9.9. For other cases, inserting an
+ explicit coercion to text can be used to have non-string input
+ accepted.
+
Table 9.9. SQL String Functions and Operators
+ Function/Operator
+
+
+ Description
+
+
+ Example(s)
+
+
+ text||text
+ → text
+
+
+ Concatenates the two strings.
+
+
+ 'Post' || 'greSQL'
+ → PostgreSQL
+
+ text||anynonarray
+ → text
+
+
+ anynonarray||text
+ → text
+
+
+ Converts the non-string input to text, then concatenates the two
+ strings. (The non-string input cannot be of an array type, because
+ that would create ambiguity with the array ||
+ operators. If you want to concatenate an array's text equivalent,
+ cast it to text explicitly.)
+
+ Checks whether the string is in the specified Unicode normalization
+ form. The optional form key word specifies the
+ form: NFC (the default), NFD,
+ NFKC, or NFKD. This expression can
+ only be used when the server encoding is UTF8. Note
+ that checking for normalization using this expression is often faster
+ than normalizing possibly already normalized strings.
+
+
+ U&'\0061\0308bc' IS NFD NORMALIZED
+ → t
+
+
+ bit_length ( text )
+ → integer
+
+
+ Returns number of bits in the string (8
+ times the octet_length).
+
+
+ bit_length('jose')
+ → 32
+
+
+
+
+ char_length ( text )
+ → integer
+
+
+
+ character_length ( text )
+ → integer
+
+
+ Returns number of characters in the string.
+
+
+ char_length('josé')
+ → 4
+
+
+ lower ( text )
+ → text
+
+
+ Converts the string to all lower case, according to the rules of the
+ database's locale.
+
+ Extends the string to length
+ length by prepending the characters
+ fill (a space by default). If the
+ string is already longer than
+ length then it is truncated (on the right).
+
+ Removes the longest string containing only characters in
+ characters (a space by default) from the start of
+ string.
+
+
+ ltrim('zzzytest', 'xyz')
+ → test
+
+
+
+ normalize ( text
+ [, form] )
+ → text
+
+
+ Converts the string to the specified Unicode
+ normalization form. The optional form key word
+ specifies the form: NFC (the default),
+ NFD, NFKC, or
+ NFKD. This function can only be used when the
+ server encoding is UTF8.
+
+ Replaces the substring of string that starts at
+ the start'th character and extends
+ for count characters
+ with newsubstring.
+ If count is omitted, it defaults to the length
+ of newsubstring.
+
+
+ overlay('Txxxxas' placing 'hom' from 2 for 4)
+ → Thomas
+
+
+ position ( substringtextINstringtext )
+ → integer
+
+
+ Returns first starting index of the specified
+ substring within
+ string, or zero if it's not present.
+
+ Extends the string to length
+ length by appending the characters
+ fill (a space by default). If the
+ string is already longer than
+ length then it is truncated.
+
+ Extracts the substring of string starting at
+ the start'th character if that is specified,
+ and stopping after count characters if that is
+ specified. Provide at least one of start
+ and count.
+
+
+ substring('Thomas' from 2 for 3)
+ → hom
+
+
+ substring('Thomas' from 3)
+ → omas
+
+
+ substring('Thomas' for 2)
+ → Th
+
+ substring ( stringtextFROMpatterntext )
+ → text
+
+
+ Extracts the first substring matching POSIX regular expression; see
+ Section 9.7.3.
+
+
+ substring('Thomas' from '...$')
+ → mas
+
+ substring ( stringtextSIMILARpatterntextESCAPEescapetext )
+ → text
+
+
+ substring ( stringtextFROMpatterntextFORescapetext )
+ → text
+
+
+ Extracts the first substring matching SQL regular expression;
+ see Section 9.7.2. The first form has
+ been specified since SQL:2003; the second form was only in SQL:1999
+ and should be considered obsolete.
+
+
+ substring('Thomas' similar '%#"o_a#"_' escape '#')
+ → oma
+
+
+ trim ( [LEADING | TRAILING | BOTH]
+ [characterstext] FROM
+ stringtext )
+ → text
+
+
+ Removes the longest string containing only characters in
+ characters (a space by default) from the
+ start, end, or both ends (BOTH is the default)
+ of string.
+
+
+ trim(both 'xyz' from 'yxTomxx')
+ → Tom
+
+ trim ( [LEADING | TRAILING | BOTH] [FROM]
+ stringtext [,
+ characterstext] )
+ → text
+
+
+ This is a non-standard syntax for trim().
+
+
+ trim(both from 'yxTomxx', 'xyz')
+ → Tom
+
+
+ upper ( text )
+ → text
+
+
+ Converts the string to all upper case, according to the rules of the
+ database's locale.
+
+
+ upper('tom')
+ → TOM
+
+ Additional string manipulation functions and operators are available
+ and are listed in Table 9.10. (Some of
+ these are used internally to implement
+ the SQL-standard string functions listed in
+ Table 9.9.)
+ There are also pattern-matching operators, which are described in
+ Section 9.7, and operators for full-text
+ search, which are described in Chapter 12.
+
Table 9.10. Other String Functions and Operators
+ Function/Operator
+
+
+ Description
+
+
+ Example(s)
+
+
+ text^@text
+ → boolean
+
+
+ Returns true if the first string starts with the second string
+ (equivalent to the starts_with() function).
+
+
+ 'alphabet' ^@ 'alph'
+ → t
+
+
+ ascii ( text )
+ → integer
+
+
+ Returns the numeric code of the first character of the argument.
+ In UTF8 encoding, returns the Unicode code point
+ of the character. In other multibyte encodings, the argument must
+ be an ASCII character.
+
+
+ ascii('x')
+ → 120
+
+
+ chr ( integer )
+ → text
+
+
+ Returns the character with the given code. In UTF8
+ encoding the argument is treated as a Unicode code point. In other
+ multibyte encodings the argument must designate
+ an ASCII character. chr(0) is
+ disallowed because text data types cannot store that character.
+
+ Concatenates all but the first argument, with separators. The first
+ argument is used as the separator string, and should not be NULL.
+ Other NULL arguments are ignored.
+
+ Converts the first letter of each word to upper case and the
+ rest to lower case. Words are sequences of alphanumeric
+ characters separated by non-alphanumeric characters.
+
+
+ initcap('hi THOMAS')
+ → Hi Thomas
+
+
+ left ( stringtext,
+ ninteger )
+ → text
+
+
+ Returns first n characters in the
+ string, or when n is negative, returns
+ all but last |n| characters.
+
+
+ left('abcde', 2)
+ → ab
+
+
+ length ( text )
+ → integer
+
+
+ Returns the number of characters in the string.
+
+
+ length('jose')
+ → 4
+
+
+ md5 ( text )
+ → text
+
+
+ Computes the MD5 hash of
+ the argument, with the result written in hexadecimal.
+
+ Splits qualified_identifier into an array of
+ identifiers, removing any quoting of individual identifiers. By
+ default, extra characters after the last identifier are considered an
+ error; but if the second parameter is false, then such
+ extra characters are ignored. (This behavior is useful for parsing
+ names for objects like functions.) Note that this function does not
+ truncate over-length identifiers. If you want truncation you can cast
+ the result to name[].
+
+ Returns the given string suitably quoted to be used as an identifier
+ in an SQL statement string.
+ Quotes are added only if necessary (i.e., if the string contains
+ non-identifier characters or would be case-folded).
+ Embedded quotes are properly doubled.
+ See also Example 43.1.
+
+
+ quote_ident('Foo bar')
+ → "Foo bar"
+
+
+ quote_literal ( text )
+ → text
+
+
+ Returns the given string suitably quoted to be used as a string literal
+ in an SQL statement string.
+ Embedded single-quotes and backslashes are properly doubled.
+ Note that quote_literal returns null on null
+ input; if the argument might be null,
+ quote_nullable is often more suitable.
+ See also Example 43.1.
+
+
+ quote_literal(E'O\'Reilly')
+ → 'O''Reilly'
+
+ quote_literal ( anyelement )
+ → text
+
+
+ Converts the given value to text and then quotes it as a literal.
+ Embedded single-quotes and backslashes are properly doubled.
+
+
+ quote_literal(42.5)
+ → '42.5'
+
+
+ quote_nullable ( text )
+ → text
+
+
+ Returns the given string suitably quoted to be used as a string literal
+ in an SQL statement string; or, if the argument
+ is null, returns NULL.
+ Embedded single-quotes and backslashes are properly doubled.
+ See also Example 43.1.
+
+
+ quote_nullable(NULL)
+ → NULL
+
+ quote_nullable ( anyelement )
+ → text
+
+
+ Converts the given value to text and then quotes it as a literal;
+ or, if the argument is null, returns NULL.
+ Embedded single-quotes and backslashes are properly doubled.
+
+ Returns the position within string where
+ the N'th match of the POSIX regular
+ expression pattern occurs, or zero if there is
+ no such match; see Section 9.7.3.
+
+ Returns substrings within the first match of the POSIX regular
+ expression pattern to
+ the string, or substrings within all
+ such matches if the g flag is used;
+ see Section 9.7.3.
+
+ Replaces the substring that is the first match to the POSIX
+ regular expression pattern, or all such
+ matches if the g flag is used; see
+ Section 9.7.3.
+
+ Returns the substring within string that
+ matches the N'th occurrence of the POSIX
+ regular expression pattern,
+ or NULL if there is no such match; see
+ Section 9.7.3.
+
+ Splits string at occurrences
+ of delimiter and returns
+ the n'th field (counting from one),
+ or when n is negative, returns
+ the |n|'th-from-last field.
+
+ Splits the string at occurrences
+ of delimiter and forms the resulting fields
+ into a text array.
+ If delimiter is NULL,
+ each character in the string will become a
+ separate element in the array.
+ If delimiter is an empty string, then
+ the string is treated as a single field.
+ If null_string is supplied and is
+ not NULL, fields matching that string are
+ replaced by NULL.
+ See also array_to_string.
+
+ Splits the string at occurrences
+ of delimiter and returns the resulting fields
+ as a set of text rows.
+ If delimiter is NULL,
+ each character in the string will become a
+ separate row of the result.
+ If delimiter is an empty string, then
+ the string is treated as a single field.
+ If null_string is supplied and is
+ not NULL, fields matching that string are
+ replaced by NULL.
+
+ Returns first starting index of the specified substring
+ within string, or zero if it's not present.
+ (Same as position(substring in
+ string), but note the reversed
+ argument order.)
+
+ Extracts the substring of string starting at
+ the start'th character,
+ and extending for count characters if that is
+ specified. (Same
+ as substring(string
+ from start
+ for count).)
+
+ Converts string to ASCII
+ from another encoding, which may be identified by name or number.
+ If encoding is omitted the database encoding
+ is assumed (which in practice is the only useful case).
+ The conversion consists primarily of dropping accents.
+ Conversion is only supported
+ from LATIN1, LATIN2,
+ LATIN9, and WIN1250 encodings.
+ (See the unaccent module for another, more flexible
+ solution.)
+
+
+ to_ascii('Karél')
+ → Karel
+
+
+ to_hex ( integer )
+ → text
+
+
+ to_hex ( bigint )
+ → text
+
+
+ Converts the number to its equivalent hexadecimal representation.
+
+ Replaces each character in string that
+ matches a character in the from set with the
+ corresponding character in the to
+ set. If from is longer than
+ to, occurrences of the extra characters in
+ from are deleted.
+
+
+ translate('12345', '143', 'ax')
+ → a2x5
+
+
+ unistr ( text )
+ → text
+
+
+ Evaluate escaped Unicode characters in the argument. Unicode characters
+ can be specified as
+ \XXXX (4 hexadecimal
+ digits), \+XXXXXX (6
+ hexadecimal digits),
+ \uXXXX (4 hexadecimal
+ digits), or \UXXXXXXXX
+ (8 hexadecimal digits). To specify a backslash, write two
+ backslashes. All other characters are taken literally.
+
+
+
+ If the server encoding is not UTF-8, the Unicode code point identified
+ by one of these escape sequences is converted to the actual server
+ encoding; an error is reported if that's not possible.
+
+
+
+ This function provides a (non-standard) alternative to string
+ constants with Unicode escapes (see Section 4.1.2.3).
+
+
+
+ unistr('d\0061t\+000061')
+ → data
+
+
+ unistr('d\u0061t\U00000061')
+ → data
+
+ The concat, concat_ws and
+ format functions are variadic, so it is possible to
+ pass the values to be concatenated or formatted as an array marked with
+ the VARIADIC keyword (see Section 38.5.6). The array's elements are
+ treated as if they were separate ordinary arguments to the function.
+ If the variadic array argument is NULL, concat
+ and concat_ws return NULL, but
+ format treats a NULL as a zero-element array.
+
+ See also the aggregate function string_agg in
+ Section 9.21, and the functions for
+ converting between strings and the bytea type in
+ Table 9.13.
+
+ formatstr is a format string that specifies how the
+ result should be formatted. Text in the format string is copied
+ directly to the result, except where format specifiers are
+ used. Format specifiers act as placeholders in the string, defining how
+ subsequent function arguments should be formatted and inserted into the
+ result. Each formatarg argument is converted to text
+ according to the usual output rules for its data type, and then formatted
+ and inserted into the result string according to the format specifier(s).
+
+ Format specifiers are introduced by a % character and have
+ the form
+
+%[position][flags][width]type
+
+ where the component fields are:
+
+
position (optional)
+ A string of the form n$ where
+ n is the index of the argument to print.
+ Index 1 means the first argument after
+ formatstr. If the position is
+ omitted, the default is to use the next argument in sequence.
+
flags (optional)
+ Additional options controlling how the format specifier's output is
+ formatted. Currently the only supported flag is a minus sign
+ (-) which will cause the format specifier's output to be
+ left-justified. This has no effect unless the width
+ field is also specified.
+
width (optional)
+ Specifies the minimum number of characters to use to
+ display the format specifier's output. The output is padded on the
+ left or right (depending on the - flag) with spaces as
+ needed to fill the width. A too-small width does not cause
+ truncation of the output, but is simply ignored. The width may be
+ specified using any of the following: a positive integer; an
+ asterisk (*) to use the next function argument as the
+ width; or a string of the form *n$ to
+ use the nth function argument as the width.
+
+ If the width comes from a function argument, that argument is
+ consumed before the argument that is used for the format specifier's
+ value. If the width argument is negative, the result is left
+ aligned (as if the - flag had been specified) within a
+ field of length abs(width).
+
type (required)
+ The type of format conversion to use to produce the format
+ specifier's output. The following types are supported:
+
+ s formats the argument value as a simple
+ string. A null value is treated as an empty string.
+
+ I treats the argument value as an SQL
+ identifier, double-quoting it if necessary.
+ It is an error for the value to be null (equivalent to
+ quote_ident).
+
+ L quotes the argument value as an SQL literal.
+ A null value is displayed as the string NULL, without
+ quotes (equivalent to quote_nullable).
+
+
+
+ In addition to the format specifiers described above, the special sequence
+ %% may be used to output a literal % character.
+
+ Here are some examples of the basic format conversions:
+
+
+ Unlike the standard C function sprintf,
+ PostgreSQL's format function allows format
+ specifiers with and without position fields to be mixed
+ in the same format string. A format specifier without a
+ position field always uses the next argument after the
+ last argument consumed.
+ In addition, the format function does not require all
+ function arguments to be used in the format string.
+ For example:
+
+
+ The %I and %L format specifiers are particularly
+ useful for safely constructing dynamic SQL statements. See
+ Example 43.1.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-subquery.html b/pgsql/doc/postgresql/html/functions-subquery.html
new file mode 100644
index 0000000000000000000000000000000000000000..f065f0c6c7caefbea60c09e58b3b03016e5ae64e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-subquery.html
@@ -0,0 +1,213 @@
+
+9.23. Subquery Expressions
+ This section describes the SQL-compliant subquery
+ expressions available in PostgreSQL.
+ All of the expression forms documented in this section return
+ Boolean (true/false) results.
+
+ The argument of EXISTS is an arbitrary SELECT statement,
+ or subquery. The
+ subquery is evaluated to determine whether it returns any rows.
+ If it returns at least one row, the result of EXISTS is
+ “true”; if the subquery returns no rows, the result of EXISTS
+ is “false”.
+
+ The subquery can refer to variables from the surrounding query,
+ which will act as constants during any one evaluation of the subquery.
+
+ The subquery will generally only be executed long enough to determine
+ whether at least one row is returned, not all the way to completion.
+ It is unwise to write a subquery that has side effects (such as
+ calling sequence functions); whether the side effects occur
+ might be unpredictable.
+
+ Since the result depends only on whether any rows are returned,
+ and not on the contents of those rows, the output list of the
+ subquery is normally unimportant. A common coding convention is
+ to write all EXISTS tests in the form
+ EXISTS(SELECT 1 WHERE ...). There are exceptions to
+ this rule however, such as subqueries that use INTERSECT.
+
+ This simple example is like an inner join on col2, but
+ it produces at most one output row for each tab1 row,
+ even if there are several matching tab2 rows:
+
+SELECT col1
+FROM tab1
+WHERE EXISTS (SELECT 1 FROM tab2 WHERE col2 = tab1.col2);
+
+ The right-hand side is a parenthesized
+ subquery, which must return exactly one column. The left-hand expression
+ is evaluated and compared to each row of the subquery result.
+ The result of IN is “true” if any equal subquery row is found.
+ The result is “false” if no equal row is found (including the
+ case where the subquery returns no rows).
+
+ Note that if the left-hand expression yields null, or if there are
+ no equal right-hand values and at least one right-hand row yields
+ null, the result of the IN construct will be null, not false.
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
+ As with EXISTS, it's unwise to assume that the subquery will
+ be evaluated completely.
+
+row_constructor IN (subquery)
+
+ The left-hand side of this form of IN is a row constructor,
+ as described in Section 4.2.13.
+ The right-hand side is a parenthesized
+ subquery, which must return exactly as many columns as there are
+ expressions in the left-hand row. The left-hand expressions are
+ evaluated and compared row-wise to each row of the subquery result.
+ The result of IN is “true” if any equal subquery row is found.
+ The result is “false” if no equal row is found (including the
+ case where the subquery returns no rows).
+
+ As usual, null values in the rows are combined per
+ the normal rules of SQL Boolean expressions. Two rows are considered
+ equal if all their corresponding members are non-null and equal; the rows
+ are unequal if any corresponding members are non-null and unequal;
+ otherwise the result of that row comparison is unknown (null).
+ If all the per-row results are either unequal or null, with at least one
+ null, then the result of IN is null.
+
+ The right-hand side is a parenthesized
+ subquery, which must return exactly one column. The left-hand expression
+ is evaluated and compared to each row of the subquery result.
+ The result of NOT IN is “true” if only unequal subquery rows
+ are found (including the case where the subquery returns no rows).
+ The result is “false” if any equal row is found.
+
+ Note that if the left-hand expression yields null, or if there are
+ no equal right-hand values and at least one right-hand row yields
+ null, the result of the NOT IN construct will be null, not true.
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
+ As with EXISTS, it's unwise to assume that the subquery will
+ be evaluated completely.
+
+row_constructor NOT IN (subquery)
+
+ The left-hand side of this form of NOT IN is a row constructor,
+ as described in Section 4.2.13.
+ The right-hand side is a parenthesized
+ subquery, which must return exactly as many columns as there are
+ expressions in the left-hand row. The left-hand expressions are
+ evaluated and compared row-wise to each row of the subquery result.
+ The result of NOT IN is “true” if only unequal subquery rows
+ are found (including the case where the subquery returns no rows).
+ The result is “false” if any equal row is found.
+
+ As usual, null values in the rows are combined per
+ the normal rules of SQL Boolean expressions. Two rows are considered
+ equal if all their corresponding members are non-null and equal; the rows
+ are unequal if any corresponding members are non-null and unequal;
+ otherwise the result of that row comparison is unknown (null).
+ If all the per-row results are either unequal or null, with at least one
+ null, then the result of NOT IN is null.
+
+expressionoperator ANY (subquery)
+expressionoperator SOME (subquery)
+
+ The right-hand side is a parenthesized
+ subquery, which must return exactly one column. The left-hand expression
+ is evaluated and compared to each row of the subquery result using the
+ given operator, which must yield a Boolean
+ result.
+ The result of ANY is “true” if any true result is obtained.
+ The result is “false” if no true result is found (including the
+ case where the subquery returns no rows).
+
+ SOME is a synonym for ANY.
+ IN is equivalent to = ANY.
+
+ Note that if there are no successes and at least one right-hand row yields
+ null for the operator's result, the result of the ANY construct
+ will be null, not false.
+ This is in accordance with SQL's normal rules for Boolean combinations
+ of null values.
+
+ As with EXISTS, it's unwise to assume that the subquery will
+ be evaluated completely.
+
+row_constructoroperator ANY (subquery)
+row_constructoroperator SOME (subquery)
+
+ The left-hand side of this form of ANY is a row constructor,
+ as described in Section 4.2.13.
+ The right-hand side is a parenthesized
+ subquery, which must return exactly as many columns as there are
+ expressions in the left-hand row. The left-hand expressions are
+ evaluated and compared row-wise to each row of the subquery result,
+ using the given operator.
+ The result of ANY is “true” if the comparison
+ returns true for any subquery row.
+ The result is “false” if the comparison returns false for every
+ subquery row (including the case where the subquery returns no
+ rows).
+ The result is NULL if no comparison with a subquery row returns true,
+ and at least one comparison returns NULL.
+
+ See Section 9.24.5 for details about the meaning
+ of a row constructor comparison.
+
+ The right-hand side is a parenthesized
+ subquery, which must return exactly one column. The left-hand expression
+ is evaluated and compared to each row of the subquery result using the
+ given operator, which must yield a Boolean
+ result.
+ The result of ALL is “true” if all rows yield true
+ (including the case where the subquery returns no rows).
+ The result is “false” if any false result is found.
+ The result is NULL if no comparison with a subquery row returns false,
+ and at least one comparison returns NULL.
+
+ NOT IN is equivalent to <> ALL.
+
+ As with EXISTS, it's unwise to assume that the subquery will
+ be evaluated completely.
+
+row_constructoroperator ALL (subquery)
+
+ The left-hand side of this form of ALL is a row constructor,
+ as described in Section 4.2.13.
+ The right-hand side is a parenthesized
+ subquery, which must return exactly as many columns as there are
+ expressions in the left-hand row. The left-hand expressions are
+ evaluated and compared row-wise to each row of the subquery result,
+ using the given operator.
+ The result of ALL is “true” if the comparison
+ returns true for all subquery rows (including the
+ case where the subquery returns no rows).
+ The result is “false” if the comparison returns false for any
+ subquery row.
+ The result is NULL if no comparison with a subquery row returns false,
+ and at least one comparison returns NULL.
+
+ See Section 9.24.5 for details about the meaning
+ of a row constructor comparison.
+
+ The left-hand side is a row constructor,
+ as described in Section 4.2.13.
+ The right-hand side is a parenthesized subquery, which must return exactly
+ as many columns as there are expressions in the left-hand row. Furthermore,
+ the subquery cannot return more than one row. (If it returns zero rows,
+ the result is taken to be null.) The left-hand side is evaluated and
+ compared row-wise to the single subquery result row.
+
+ See Section 9.24.5 for details about the meaning
+ of a row constructor comparison.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-textsearch.html b/pgsql/doc/postgresql/html/functions-textsearch.html
new file mode 100644
index 0000000000000000000000000000000000000000..539162bf79d66df2281a120cd30088064840f8cc
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-textsearch.html
@@ -0,0 +1,763 @@
+
+9.13. Text Search Functions and Operators
+ Table 9.42,
+ Table 9.43 and
+ Table 9.44
+ summarize the functions and operators that are provided
+ for full text searching. See Chapter 12 for a detailed
+ explanation of PostgreSQL's text search
+ facility.
+
Table 9.42. Text Search Operators
+ Operator
+
+
+ Description
+
+
+ Example(s)
+
+ tsvector@@tsquery
+ → boolean
+
+
+ tsquery@@tsvector
+ → boolean
+
+
+ Does tsvector match tsquery?
+ (The arguments can be given in either order.)
+
+
+ to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')
+ → t
+
+ text@@tsquery
+ → boolean
+
+
+ Does text string, after implicit invocation
+ of to_tsvector(), match tsquery?
+
+
+ 'fat cats ate rats' @@ to_tsquery('cat & rat')
+ → t
+
+ tsvector@@@tsquery
+ → boolean
+
+
+ tsquery@@@tsvector
+ → boolean
+
+
+ This is a deprecated synonym for @@.
+
+
+ to_tsvector('fat cats ate rats') @@@ to_tsquery('cat & rat')
+ → t
+
+ tsvector||tsvector
+ → tsvector
+
+
+ Concatenates two tsvectors. If both inputs contain
+ lexeme positions, the second input's positions are adjusted
+ accordingly.
+
+ Does first tsquery contain the second? (This considers
+ only whether all the lexemes appearing in one query appear in the
+ other, ignoring the combining operators.)
+
+
+ 'cat'::tsquery @> 'cat & rat'::tsquery
+ → f
+
+ tsquery<@tsquery
+ → boolean
+
+
+ Is first tsquery contained in the second? (This
+ considers only whether all the lexemes appearing in one query appear
+ in the other, ignoring the combining operators.)
+
+
+ 'cat'::tsquery <@ 'cat & rat'::tsquery
+ → t
+
+
+ 'cat'::tsquery <@ '!cat & rat'::tsquery
+ → t
+
+ In addition to these specialized operators, the usual comparison
+ operators shown in Table 9.1 are
+ available for types tsvector and tsquery.
+ These are not very
+ useful for text searching but allow, for example, unique indexes to be
+ built on columns of these types.
+
Table 9.43. Text Search Functions
+ Function
+
+
+ Description
+
+
+ Example(s)
+
+
+ array_to_tsvector ( text[] )
+ → tsvector
+
+
+ Converts an array of text strings to a tsvector.
+ The given strings are used as lexemes as-is, without further
+ processing. Array elements must not be empty strings
+ or NULL.
+
+ Converts text to a tsquery, normalizing words according to
+ the specified or default configuration. Any punctuation in the string
+ is ignored (it does not determine query operators). The resulting
+ query matches documents containing all non-stopwords in the text.
+
+ Converts text to a tsquery, normalizing words according to
+ the specified or default configuration. Any punctuation in the string
+ is ignored (it does not determine query operators). The resulting
+ query matches phrases containing all non-stopwords in the text.
+
+ Converts text to a tsquery, normalizing words according
+ to the specified or default configuration. Quoted word sequences are
+ converted to phrase tests. The word “or” is understood
+ as producing an OR operator, and a dash produces a NOT operator;
+ other punctuation is ignored.
+ This approximates the behavior of some common web search tools.
+
+ Assigns the specified weight to elements
+ of the vector that are listed
+ in lexemes.
+ The strings in lexemes are taken as lexemes
+ as-is, without further processing. Strings that do not match any
+ lexeme in vector are ignored.
+
+ Converts text to a tsquery, normalizing words according to
+ the specified or default configuration. The words must be combined
+ by valid tsquery operators.
+
+ Converts text to a tsvector, normalizing words according
+ to the specified or default configuration. Position information is
+ included in the result.
+
+
+ to_tsvector('english', 'The Fat Rats')
+ → 'fat':2 'rat':3
+
+ Converts each string value in the JSON document to
+ a tsvector, normalizing words according to the specified
+ or default configuration. The results are then concatenated in
+ document order to produce the output. Position information is
+ generated as though one stopword exists between each pair of string
+ values. (Beware that “document order” of the fields of a
+ JSON object is implementation-dependent when the input
+ is jsonb; observe the difference in the examples.)
+
+ Selects each item in the JSON document that is requested by
+ the filter and converts each one to
+ a tsvector, normalizing words according to the specified
+ or default configuration. The results are then concatenated in
+ document order to produce the output. Position information is
+ generated as though one stopword exists between each pair of selected
+ items. (Beware that “document order” of the fields of a
+ JSON object is implementation-dependent when the input
+ is jsonb.)
+ The filter must be a jsonb
+ array containing zero or more of these keywords:
+ "string" (to include all string values),
+ "numeric" (to include all numeric values),
+ "boolean" (to include all boolean values),
+ "key" (to include all keys), or
+ "all" (to include all the above).
+ As a special case, the filter can also be a
+ simple JSON value that is one of these keywords.
+
+ Removes any occurrences of the lexemes
+ in lexemes
+ from the vector.
+ The strings in lexemes are taken as lexemes
+ as-is, without further processing. Strings that do not match any
+ lexeme in vector are ignored.
+
+ Displays, in an abbreviated form, the match(es) for
+ the query in
+ the document, which must be raw text not
+ a tsvector. Words in the document are normalized
+ according to the specified or default configuration before matching to
+ the query. Use of this function is discussed in
+ Section 12.3.4, which also describes the
+ available options.
+
+
+ ts_headline('The fat cat ate the rat.', 'cat')
+ → The fat <b>cat</b> ate the rat.
+
+ Displays, in an abbreviated form, match(es) for
+ the query that occur in string values
+ within the JSON document.
+ See Section 12.3.4 for more details.
+
+
+ ts_headline('{"cat":"raining cats and dogs"}'::jsonb, 'cat')
+ → {"cat": "raining <b>cats</b> and dogs"}
+
+ Replaces portions of the query according to
+ target(s) and substitute(s) obtained by executing
+ a SELECT command.
+ See Section 12.4.2.1 for details.
+
+ All the text search functions that accept an optional regconfig
+ argument will use the configuration specified by
+ default_text_search_config
+ when that argument is omitted.
+
+ The functions in
+ Table 9.44
+ are listed separately because they are not usually used in everyday text
+ searching operations. They are primarily helpful for development and
+ debugging of new text search configurations.
+
+ Extracts and normalizes tokens from
+ the document according to the specified or
+ default text search configuration, and returns information about how
+ each token was processed.
+ See Section 12.8.1 for details.
+
+
+ ts_debug('english', 'The Brightest supernovaes')
+ → (asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...
+
+ Returns an array of replacement lexemes if the input token is known to
+ the dictionary, or an empty array if the token is known to the
+ dictionary but it is a stop word, or NULL if it is not a known word.
+ See Section 12.8.3 for details.
+
+ Executes the sqlquery, which must return a
+ single tsvector column, and returns statistics about each
+ distinct lexeme contained in the data.
+ See Section 12.4.4 for details.
+
+
+ ts_stat('SELECT vector FROM apod')
+ → (foo,10,15) ...
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-trigger.html b/pgsql/doc/postgresql/html/functions-trigger.html
new file mode 100644
index 0000000000000000000000000000000000000000..df2a7afa6a98613a4ba35d6c35636219f71103f7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-trigger.html
@@ -0,0 +1,93 @@
+
+9.28. Trigger Functions
+ While many uses of triggers involve user-written trigger functions,
+ PostgreSQL provides a few built-in trigger
+ functions that can be used directly in user-defined triggers. These
+ are summarized in Table 9.103.
+ (Additional built-in trigger functions exist, which implement foreign
+ key constraints and deferred index constraints. Those are not documented
+ here since users need not use them directly.)
+
+ For more information about creating triggers, see
+ CREATE TRIGGER.
+
+ Automatically updates a tsvector column from associated
+ plain-text document column(s). The text search configuration to use
+ is specified by name as a trigger argument. See
+ Section 12.4.3 for details.
+
+ Automatically updates a tsvector column from associated
+ plain-text document column(s). The text search configuration to use
+ is taken from a regconfig column of the table. See
+ Section 12.4.3 for details.
+
+ The suppress_redundant_updates_trigger function,
+ when applied as a row-level BEFORE UPDATE trigger,
+ will prevent any update that does not actually change the data in the
+ row from taking place. This overrides the normal behavior which always
+ performs a physical row update
+ regardless of whether or not the data has changed. (This normal behavior
+ makes updates run faster, since no checking is required, and is also
+ useful in certain cases.)
+
+ Ideally, you should avoid running updates that don't actually
+ change the data in the record. Redundant updates can cost considerable
+ unnecessary time, especially if there are lots of indexes to alter,
+ and space in dead rows that will eventually have to be vacuumed.
+ However, detecting such situations in client code is not
+ always easy, or even possible, and writing expressions to detect
+ them can be error-prone. An alternative is to use
+ suppress_redundant_updates_trigger, which will skip
+ updates that don't change the data. You should use this with care,
+ however. The trigger takes a small but non-trivial time for each record,
+ so if most of the records affected by updates do actually change,
+ use of this trigger will make updates run slower on average.
+
+ The suppress_redundant_updates_trigger function can be
+ added to a table like this:
+
+CREATE TRIGGER z_min_update
+BEFORE UPDATE ON tablename
+FOR EACH ROW EXECUTE FUNCTION suppress_redundant_updates_trigger();
+
+ In most cases, you need to fire this trigger last for each row, so that
+ it does not override other triggers that might wish to alter the row.
+ Bearing in mind that triggers fire in name order, you would therefore
+ choose a trigger name that comes after the name of any other trigger
+ you might have on the table. (Hence the “z” prefix in the
+ example.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-uuid.html b/pgsql/doc/postgresql/html/functions-uuid.html
new file mode 100644
index 0000000000000000000000000000000000000000..e973f4633d0abbc13b73195627cc2a4adec83e20
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-uuid.html
@@ -0,0 +1,16 @@
+
+9.14. UUID Functions
+ PostgreSQL includes one function to generate a UUID:
+
+gen_random_uuid () → uuid
+
+ This function returns a version 4 (random) UUID. This is the most commonly
+ used type of UUID and is appropriate for most applications.
+
+ The uuid-ossp module provides additional functions that
+ implement other standard algorithms for generating UUIDs.
+
+ PostgreSQL also provides the usual comparison
+ operators shown in Table 9.1 for
+ UUIDs.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-window.html b/pgsql/doc/postgresql/html/functions-window.html
new file mode 100644
index 0000000000000000000000000000000000000000..e937931d85974b97e93ef28485ecf3e16ef68225
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-window.html
@@ -0,0 +1,182 @@
+
+9.22. Window Functions
+ Window functions provide the ability to perform
+ calculations across sets of rows that are related to the current query
+ row. See Section 3.5 for an introduction to this
+ feature, and Section 4.2.8 for syntax
+ details.
+
+ The built-in window functions are listed in
+ Table 9.64. Note that these functions
+ must be invoked using window function syntax, i.e., an
+ OVER clause is required.
+
+ In addition to these functions, any built-in or user-defined
+ ordinary aggregate (i.e., not ordered-set or hypothetical-set aggregates)
+ can be used as a window function; see
+ Section 9.21 for a list of the built-in aggregates.
+ Aggregate functions act as window functions only when an OVER
+ clause follows the call; otherwise they act as plain aggregates
+ and return a single row for the entire set.
+
Table 9.64. General-Purpose Window Functions
+ Function
+
+
+ Description
+
+
+ row_number ()
+ → bigint
+
+
+ Returns the number of the current row within its partition, counting
+ from 1.
+
+
+ rank ()
+ → bigint
+
+
+ Returns the rank of the current row, with gaps; that is,
+ the row_number of the first row in its peer
+ group.
+
+
+ dense_rank ()
+ → bigint
+
+
+ Returns the rank of the current row, without gaps; this function
+ effectively counts peer groups.
+
+
+ percent_rank ()
+ → double precision
+
+
+ Returns the relative rank of the current row, that is
+ (rank - 1) / (total partition rows - 1).
+ The value thus ranges from 0 to 1 inclusive.
+
+
+ cume_dist ()
+ → double precision
+
+
+ Returns the cumulative distribution, that is (number of partition rows
+ preceding or peers with current row) / (total partition rows).
+ The value thus ranges from 1/N to 1.
+
+
+ ntile ( num_bucketsinteger )
+ → integer
+
+
+ Returns an integer ranging from 1 to the argument value, dividing the
+ partition as equally as possible.
+
+ Returns value evaluated at
+ the row that is offset
+ rows before the current row within the partition; if there is no such
+ row, instead returns default
+ (which must be of a type compatible with
+ value).
+ Both offset and
+ default are evaluated
+ with respect to the current row. If omitted,
+ offset defaults to 1 and
+ default to NULL.
+
+ Returns value evaluated at
+ the row that is offset
+ rows after the current row within the partition; if there is no such
+ row, instead returns default
+ (which must be of a type compatible with
+ value).
+ Both offset and
+ default are evaluated
+ with respect to the current row. If omitted,
+ offset defaults to 1 and
+ default to NULL.
+
+ Returns value evaluated
+ at the row that is the n'th
+ row of the window frame (counting from 1);
+ returns NULL if there is no such row.
+
+ All of the functions listed in
+ Table 9.64 depend on the sort ordering
+ specified by the ORDER BY clause of the associated window
+ definition. Rows that are not distinct when considering only the
+ ORDER BY columns are said to be peers.
+ The four ranking functions (including cume_dist) are
+ defined so that they give the same answer for all rows of a peer group.
+
+ Note that first_value, last_value, and
+ nth_value consider only the rows within the “window
+ frame”, which by default contains the rows from the start of the
+ partition through the last peer of the current row. This is
+ likely to give unhelpful results for last_value and
+ sometimes also nth_value. You can redefine the frame by
+ adding a suitable frame specification (RANGE,
+ ROWS or GROUPS) to
+ the OVER clause.
+ See Section 4.2.8 for more information
+ about frame specifications.
+
+ When an aggregate function is used as a window function, it aggregates
+ over the rows within the current row's window frame.
+ An aggregate used with ORDER BY and the default window frame
+ definition produces a “running sum” type of behavior, which may or
+ may not be what's wanted. To obtain
+ aggregation over the whole partition, omit ORDER BY or use
+ ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
+ Other frame specifications can be used to obtain other effects.
+
Note
+ The SQL standard defines a RESPECT NULLS or
+ IGNORE NULLS option for lead, lag,
+ first_value, last_value, and
+ nth_value. This is not implemented in
+ PostgreSQL: the behavior is always the
+ same as the standard's default, namely RESPECT NULLS.
+ Likewise, the standard's FROM FIRST or FROM LAST
+ option for nth_value is not implemented: only the
+ default FROM FIRST behavior is supported. (You can achieve
+ the result of FROM LAST by reversing the ORDER BY
+ ordering.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions-xml.html b/pgsql/doc/postgresql/html/functions-xml.html
new file mode 100644
index 0000000000000000000000000000000000000000..865028f845fd4cfc87dd44127931923154f071d1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions-xml.html
@@ -0,0 +1,912 @@
+
+9.15. XML Functions
+ The functions and function-like expressions described in this
+ section operate on values of type xml. See Section 8.13 for information about the xml
+ type. The function-like expressions xmlparse
+ and xmlserialize for converting to and from
+ type xml are documented there, not in this section.
+
+ Use of most of these functions
+ requires PostgreSQL to have been built
+ with configure --with-libxml.
+
+ A set of functions and function-like expressions is available for
+ producing XML content from SQL data. As such, they are
+ particularly suitable for formatting query results into XML
+ documents for processing in client applications.
+
+ The function xmlcomment creates an XML value
+ containing an XML comment with the specified text as content.
+ The text cannot contain “--” or end with a
+ “-”, otherwise the resulting construct
+ would not be a valid XML comment.
+ If the argument is null, the result is null.
+
+ The function xmlconcat concatenates a list
+ of individual XML values to create a single value containing an
+ XML content fragment. Null values are omitted; the result is
+ only null if there are no nonnull arguments.
+
+ XML declarations, if present, are combined as follows. If all
+ argument values have the same XML version declaration, that
+ version is used in the result, else no version is used. If all
+ argument values have the standalone declaration value
+ “yes”, then that value is used in the result. If
+ all argument values have a standalone declaration value and at
+ least one is “no”, then that is used in the result.
+ Else the result will have no standalone declaration. If the
+ result is determined to require a standalone declaration but no
+ version declaration, a version declaration with version 1.0 will
+ be used because XML requires an XML declaration to contain a
+ version declaration. Encoding declarations are ignored and
+ removed in all cases.
+
+ The xmlelement expression produces an XML
+ element with the given name, attributes, and content.
+ The name
+ and attname items shown in the syntax are
+ simple identifiers, not values. The attvalue
+ and content items are expressions, which can
+ yield any PostgreSQL data type. The
+ argument(s) within XMLATTRIBUTES generate attributes
+ of the XML element; the content value(s) are
+ concatenated to form its content.
+
+ Element and attribute names that are not valid XML names are
+ escaped by replacing the offending characters by the sequence
+ _xHHHH_, where
+ HHHH is the character's Unicode
+ codepoint in hexadecimal notation. For example:
+
+ An explicit attribute name need not be specified if the attribute
+ value is a column reference, in which case the column's name will
+ be used as the attribute name by default. In other cases, the
+ attribute must be given an explicit name. So this example is
+ valid:
+
+CREATE TABLE test (a xml, b xml);
+SELECT xmlelement(name test, xmlattributes(a, b)) FROM test;
+
+ But these are not:
+
+SELECT xmlelement(name test, xmlattributes('constant'), a, b) FROM test;
+SELECT xmlelement(name test, xmlattributes(func(a, b))) FROM test;
+
+
+ Element content, if specified, will be formatted according to
+ its data type. If the content is itself of type xml,
+ complex XML documents can be constructed. For example:
+
+
+ Content of other types will be formatted into valid XML character
+ data. This means in particular that the characters <, >,
+ and & will be converted to entities. Binary data (data type
+ bytea) will be represented in base64 or hex
+ encoding, depending on the setting of the configuration parameter
+ xmlbinary. The particular behavior for
+ individual data types is expected to evolve in order to align the
+ PostgreSQL mappings with those specified in SQL:2006 and later,
+ as discussed in Section D.3.1.3.
+
+ The xmlforest expression produces an XML
+ forest (sequence) of elements using the given names and content.
+ As for xmlelement,
+ each name must be a simple identifier, while
+ the content expressions can have any data
+ type.
+
+
+ As seen in the second example, the element name can be omitted if
+ the content value is a column reference, in which case the column
+ name is used by default. Otherwise, a name must be specified.
+
+ Element names that are not valid XML names are escaped as shown
+ for xmlelement above. Similarly, content
+ data is escaped to make valid XML content, unless it is already
+ of type xml.
+
+ Note that XML forests are not valid XML documents if they consist
+ of more than one element, so it might be useful to wrap
+ xmlforest expressions in
+ xmlelement.
+
+ The xmlpi expression creates an XML
+ processing instruction.
+ As for xmlelement,
+ the name must be a simple identifier, while
+ the content expression can have any data type.
+ The content, if present, must not contain the
+ character sequence ?>.
+
+xmlroot ( xml, VERSION {text|NO VALUE} [, STANDALONE {YES|NO|NO VALUE} ] ) → xml
+
+ The xmlroot expression alters the properties
+ of the root node of an XML value. If a version is specified,
+ it replaces the value in the root node's version declaration; if a
+ standalone setting is specified, it replaces the value in the
+ root node's standalone declaration.
+
+ The function xmlagg is, unlike the other
+ functions described here, an aggregate function. It concatenates the
+ input values to the aggregate function call,
+ much like xmlconcat does, except that concatenation
+ occurs across rows rather than across expressions in a single row.
+ See Section 9.21 for additional information
+ about aggregate functions.
+
+ Example:
+
+CREATE TABLE test (y int, x xml);
+INSERT INTO test VALUES (1, '<foo>abc</foo>');
+INSERT INTO test VALUES (2, '<bar/>');
+SELECT xmlagg(x) FROM test;
+ xmlagg
+----------------------
+ <foo>abc</foo><bar/>
+
+
+ To determine the order of the concatenation, an ORDER BY
+ clause may be added to the aggregate call as described in
+ Section 4.2.7. For example:
+
+
+SELECT xmlagg(x ORDER BY y DESC) FROM test;
+ xmlagg
+----------------------
+ <bar/><foo>abc</foo>
+
+
+ The following non-standard approach used to be recommended
+ in previous versions, and may still be useful in specific
+ cases:
+
+
+SELECT xmlagg(x) FROM (SELECT * FROM test ORDER BY y DESC) AS tab;
+ xmlagg
+----------------------
+ <bar/><foo>abc</foo>
+
+ The expression IS DOCUMENT returns true if the
+ argument XML value is a proper XML document, false if it is not
+ (that is, it is a content fragment), or null if the argument is
+ null. See Section 8.13 about the difference
+ between documents and content fragments.
+
+ The expression IS NOT DOCUMENT returns false if the
+ argument XML value is a proper XML document, true if it is not (that is,
+ it is a content fragment), or null if the argument is null.
+
+ The function xmlexists evaluates an XPath 1.0
+ expression (the first argument), with the passed XML value as its context
+ item. The function returns false if the result of that evaluation
+ yields an empty node-set, true if it yields any other value. The
+ function returns null if any argument is null. A nonnull value
+ passed as the context item must be an XML document, not a content
+ fragment or any non-XML value.
+
+ Example:
+
+SELECT xmlexists('//town[text() = ''Toronto'']' PASSING BY VALUE '<towns><town>Toronto</town><town>Ottawa</town></towns>');
+
+ xmlexists
+------------
+ t
+(1 row)
+
+
+ The BY REF and BY VALUE clauses
+ are accepted in PostgreSQL, but are ignored,
+ as discussed in Section D.3.2.
+
+ In the SQL standard, the xmlexists function
+ evaluates an expression in the XML Query language,
+ but PostgreSQL allows only an XPath 1.0
+ expression, as discussed in
+ Section D.3.1.
+
+xml_is_well_formed ( text ) → boolean
+xml_is_well_formed_document ( text ) → boolean
+xml_is_well_formed_content ( text ) → boolean
+
+ These functions check whether a text string represents
+ well-formed XML, returning a Boolean result.
+ xml_is_well_formed_document checks for a well-formed
+ document, while xml_is_well_formed_content checks
+ for well-formed content. xml_is_well_formed does
+ the former if the xmloption configuration
+ parameter is set to DOCUMENT, or the latter if it is set to
+ CONTENT. This means that
+ xml_is_well_formed is useful for seeing whether
+ a simple cast to type xml will succeed, whereas the other two
+ functions are useful for seeing whether the corresponding variants of
+ XMLPARSE will succeed.
+
+ Examples:
+
+
+SET xmloption TO DOCUMENT;
+SELECT xml_is_well_formed('<>');
+ xml_is_well_formed
+--------------------
+ f
+(1 row)
+
+SELECT xml_is_well_formed('<abc/>');
+ xml_is_well_formed
+--------------------
+ t
+(1 row)
+
+SET xmloption TO CONTENT;
+SELECT xml_is_well_formed('abc');
+ xml_is_well_formed
+--------------------
+ t
+(1 row)
+
+SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</pg:foo>');
+ xml_is_well_formed_document
+-----------------------------
+ t
+(1 row)
+
+SELECT xml_is_well_formed_document('<pg:foo xmlns:pg="http://postgresql.org/stuff">bar</my:foo>');
+ xml_is_well_formed_document
+-----------------------------
+ f
+(1 row)
+
+
+ The last example shows that the checks include whether
+ namespaces are correctly matched.
+
+ To process values of data type xml, PostgreSQL offers
+ the functions xpath and
+ xpath_exists, which evaluate XPath 1.0
+ expressions, and the XMLTABLE
+ table function.
+
+ The function xpath evaluates the XPath 1.0
+ expression xpath (given as text)
+ against the XML value
+ xml. It returns an array of XML values
+ corresponding to the node-set produced by the XPath expression.
+ If the XPath expression returns a scalar value rather than a node-set,
+ a single-element array is returned.
+
+ The second argument must be a well formed XML document. In particular,
+ it must have a single root node element.
+
+ The optional third argument of the function is an array of namespace
+ mappings. This array should be a two-dimensional text array with
+ the length of the second axis being equal to 2 (i.e., it should be an
+ array of arrays, each of which consists of exactly 2 elements).
+ The first element of each array entry is the namespace name (alias), the
+ second the namespace URI. It is not required that aliases provided in
+ this array be the same as those being used in the XML document itself (in
+ other words, both in the XML document and in the xpath
+ function context, aliases are local).
+
+ The function xpath_exists is a specialized form
+ of the xpath function. Instead of returning the
+ individual XML values that satisfy the XPath 1.0 expression, this function
+ returns a Boolean indicating whether the query was satisfied or not
+ (specifically, whether it produced any value other than an empty node-set).
+ This function is equivalent to the XMLEXISTS predicate,
+ except that it also offers support for a namespace mapping argument.
+
+ The xmltable expression produces a table based
+ on an XML value, an XPath filter to extract rows, and a
+ set of column definitions.
+ Although it syntactically resembles a function, it can only appear
+ as a table in a query's FROM clause.
+
+ The optional XMLNAMESPACES clause gives a
+ comma-separated list of namespace definitions, where
+ each namespace_uri is a text
+ expression and each namespace_name is a simple
+ identifier. It specifies the XML namespaces used in the document and
+ their aliases. A default namespace specification is not currently
+ supported.
+
+ The required row_expression argument is an
+ XPath 1.0 expression (given as text) that is evaluated,
+ passing the XML value document_expression as
+ its context item, to obtain a set of XML nodes. These nodes are what
+ xmltable transforms into output rows. No rows
+ will be produced if the document_expression
+ is null, nor if the row_expression produces
+ an empty node-set or any value other than a node-set.
+
+ document_expression provides the context
+ item for the row_expression. It must be a
+ well-formed XML document; fragments/forests are not accepted.
+ The BY REF and BY VALUE clauses
+ are accepted but ignored, as discussed in
+ Section D.3.2.
+
+ In the SQL standard, the xmltable function
+ evaluates expressions in the XML Query language,
+ but PostgreSQL allows only XPath 1.0
+ expressions, as discussed in
+ Section D.3.1.
+
+ The required COLUMNS clause specifies the
+ column(s) that will be produced in the output table.
+ See the syntax summary above for the format.
+ A name is required for each column, as is a data type
+ (unless FOR ORDINALITY is specified, in which case
+ type integer is implicit). The path, default and
+ nullability clauses are optional.
+
+ A column marked FOR ORDINALITY will be populated
+ with row numbers, starting with 1, in the order of nodes retrieved from
+ the row_expression's result node-set.
+ At most one column may be marked FOR ORDINALITY.
+
Note
+ XPath 1.0 does not specify an order for nodes in a node-set, so code
+ that relies on a particular order of the results will be
+ implementation-dependent. Details can be found in
+ Section D.3.1.2.
+
+ The column_expression for a column is an
+ XPath 1.0 expression that is evaluated for each row, with the current
+ node from the row_expression result as its
+ context item, to find the value of the column. If
+ no column_expression is given, then the
+ column name is used as an implicit path.
+
+ If a column's XPath expression returns a non-XML value (which is limited
+ to string, boolean, or double in XPath 1.0) and the column has a
+ PostgreSQL type other than xml, the column will be set
+ as if by assigning the value's string representation to the PostgreSQL
+ type. (If the value is a boolean, its string representation is taken
+ to be 1 or 0 if the output
+ column's type category is numeric, otherwise true or
+ false.)
+
+ If a column's XPath expression returns a non-empty set of XML nodes
+ and the column's PostgreSQL type is xml, the column will
+ be assigned the expression result exactly, if it is of document or
+ content form.
+ [8]
+
+ A non-XML result assigned to an xml output column produces
+ content, a single text node with the string value of the result.
+ An XML result assigned to a column of any other type may not have more than
+ one node, or an error is raised. If there is exactly one node, the column
+ will be set as if by assigning the node's string
+ value (as defined for the XPath 1.0 string function)
+ to the PostgreSQL type.
+
+ The string value of an XML element is the concatenation, in document order,
+ of all text nodes contained in that element and its descendants. The string
+ value of an element with no descendant text nodes is an
+ empty string (not NULL).
+ Any xsi:nil attributes are ignored.
+ Note that the whitespace-only text() node between two non-text
+ elements is preserved, and that leading whitespace on a text()
+ node is not flattened.
+ The XPath 1.0 string function may be consulted for the
+ rules defining the string value of other XML node types and non-XML values.
+
+ The conversion rules presented here are not exactly those of the SQL
+ standard, as discussed in Section D.3.1.3.
+
+ If the path expression returns an empty node-set
+ (typically, when it does not match)
+ for a given row, the column will be set to NULL, unless
+ a default_expression is specified; then the
+ value resulting from evaluating that expression is used.
+
+ A default_expression, rather than being
+ evaluated immediately when xmltable is called,
+ is evaluated each time a default is needed for the column.
+ If the expression qualifies as stable or immutable, the repeat
+ evaluation may be skipped.
+ This means that you can usefully use volatile functions like
+ nextval in
+ default_expression.
+
+ Columns may be marked NOT NULL. If the
+ column_expression for a NOT
+ NULL column does not match anything and there is
+ no DEFAULT or
+ the default_expression also evaluates to null,
+ an error is reported.
+
+ Examples:
+
+CREATE TABLE xmldata AS SELECT
+xml $$
+<ROWS>
+ <ROW id="1">
+ <COUNTRY_ID>AU</COUNTRY_ID>
+ <COUNTRY_NAME>Australia</COUNTRY_NAME>
+ </ROW>
+ <ROW id="5">
+ <COUNTRY_ID>JP</COUNTRY_ID>
+ <COUNTRY_NAME>Japan</COUNTRY_NAME>
+ <PREMIER_NAME>Shinzo Abe</PREMIER_NAME>
+ <SIZE unit="sq_mi">145935</SIZE>
+ </ROW>
+ <ROW id="6">
+ <COUNTRY_ID>SG</COUNTRY_ID>
+ <COUNTRY_NAME>Singapore</COUNTRY_NAME>
+ <SIZE unit="sq_km">697</SIZE>
+ </ROW>
+</ROWS>
+$$ AS data;
+
+SELECT xmltable.*
+ FROM xmldata,
+ XMLTABLE('//ROWS/ROW'
+ PASSING data
+ COLUMNS id int PATH '@id',
+ ordinality FOR ORDINALITY,
+ "COUNTRY_NAME" text,
+ country_id text PATH 'COUNTRY_ID',
+ size_sq_km float PATH 'SIZE[@unit = "sq_km"]',
+ size_other text PATH
+ 'concat(SIZE[@unit!="sq_km"], " ", SIZE[@unit!="sq_km"]/@unit)',
+ premier_name text PATH 'PREMIER_NAME' DEFAULT 'not specified');
+
+ id | ordinality | COUNTRY_NAME | country_id | size_sq_km | size_other | premier_name
+----+------------+--------------+------------+------------+--------------+---------------
+ 1 | 1 | Australia | AU | | | not specified
+ 5 | 2 | Japan | JP | | 145935 sq_mi | Shinzo Abe
+ 6 | 3 | Singapore | SG | 697 | | not specified
+
+
+ The following example shows concatenation of multiple text() nodes,
+ usage of the column name as XPath filter, and the treatment of whitespace,
+ XML comments and processing instructions:
+
+
+CREATE TABLE xmlelements AS SELECT
+xml $$
+ <root>
+ <element> Hello<!-- xyxxz -->2a2<?aaaaa?> <!--x--> bbb<x>xxx</x>CC </element>
+ </root>
+$$ AS data;
+
+SELECT xmltable.*
+ FROM xmlelements, XMLTABLE('/root' PASSING data COLUMNS element text);
+ element
+-------------------------
+ Hello2a2 bbbxxxCC
+
+
+ The following example illustrates how
+ the XMLNAMESPACES clause can be used to specify
+ a list of namespaces
+ used in the XML document as well as in the XPath expressions:
+
+
+WITH xmldata(data) AS (VALUES ('
+<example xmlns="http://example.com/myns" xmlns:B="http://example.com/b">
+ <item foo="1" B:bar="2"/>
+ <item foo="3" B:bar="4"/>
+ <item foo="4" B:bar="5"/>
+</example>'::xml)
+)
+SELECT xmltable.*
+ FROM XMLTABLE(XMLNAMESPACES('http://example.com/myns' AS x,
+ 'http://example.com/b' AS "B"),
+ '/x:example/x:item'
+ PASSING (SELECT data FROM xmldata)
+ COLUMNS foo int PATH '@foo',
+ bar int PATH '@B:bar');
+ foo | bar
+-----+-----
+ 1 | 2
+ 3 | 4
+ 4 | 5
+(3 rows)
+
+ table_to_xml maps the content of the named
+ table, passed as parameter table. The
+ regclass type accepts strings identifying tables using the
+ usual notation, including optional schema qualification and
+ double quotes (see Section 8.19 for details).
+ query_to_xml executes the
+ query whose text is passed as parameter
+ query and maps the result set.
+ cursor_to_xml fetches the indicated number of
+ rows from the cursor specified by the parameter
+ cursor. This variant is recommended if
+ large tables have to be mapped, because the result value is built
+ up in memory by each function.
+
+ If tableforest is false, then the resulting
+ XML document looks like this:
+
+
+ If no table name is available, that is, when mapping a query or a
+ cursor, the string table is used in the first
+ format, row in the second format.
+
+ The choice between these formats is up to the user. The first
+ format is a proper XML document, which will be important in many
+ applications. The second format tends to be more useful in the
+ cursor_to_xml function if the result values are to be
+ reassembled into one document later on. The functions for
+ producing XML content discussed above, in particular
+ xmlelement, can be used to alter the results
+ to taste.
+
+ The data values are mapped in the same way as described for the
+ function xmlelement above.
+
+ The parameter nulls determines whether null
+ values should be included in the output. If true, null values in
+ columns are represented as:
+
+<columnname xsi:nil="true"/>
+
+ where xsi is the XML namespace prefix for XML
+ Schema Instance. An appropriate namespace declaration will be
+ added to the result value. If false, columns containing null
+ values are simply omitted from the output.
+
+ The parameter targetns specifies the
+ desired XML namespace of the result. If no particular namespace
+ is wanted, an empty string should be passed.
+
+ The following functions return XML Schema documents describing the
+ mappings performed by the corresponding functions above:
+
+ It is essential that the same parameters are passed in order to
+ obtain matching XML data mappings and XML Schema documents.
+
+ The following functions produce XML data mappings and the
+ corresponding XML Schema in one document (or forest), linked
+ together. They can be useful where self-contained and
+ self-describing results are wanted:
+
+ In addition, the following functions are available to produce
+ analogous mappings of entire schemas or the entire current
+ database:
+
+schema_to_xml ( schemaname, nullsboolean,
+ tableforestboolean, targetnstext ) → xml
+schema_to_xmlschema ( schemaname, nullsboolean,
+ tableforestboolean, targetnstext ) → xml
+schema_to_xml_and_xmlschema ( schemaname, nullsboolean,
+ tableforestboolean, targetnstext ) → xml
+
+database_to_xml ( nullsboolean,
+ tableforestboolean, targetnstext ) → xml
+database_to_xmlschema ( nullsboolean,
+ tableforestboolean, targetnstext ) → xml
+database_to_xml_and_xmlschema ( nullsboolean,
+ tableforestboolean, targetnstext ) → xml
+
+
+ These functions ignore tables that are not readable by the current user.
+ The database-wide functions additionally ignore schemas that the current
+ user does not have USAGE (lookup) privilege for.
+
+ Note that these potentially produce a lot of data, which needs to
+ be built up in memory. When requesting content mappings of large
+ schemas or databases, it might be worthwhile to consider mapping the
+ tables separately instead, possibly even through a cursor.
+
+ The result of a schema content mapping looks like this:
+
+
+ As an example of using the output produced by these functions,
+ Example 9.1 shows an XSLT stylesheet that
+ converts the output of
+ table_to_xml_and_xmlschema to an HTML
+ document containing a tabular rendition of the table data. In a
+ similar manner, the results from these functions can be
+ converted into other XML-based formats.
+
Example 9.1. XSLT Stylesheet for Converting SQL/XML Output to HTML
[8]
+ A result containing more than one element node at the top level, or
+ non-whitespace text outside of an element, is an example of content form.
+ An XPath result can be of neither form, for example if it returns an
+ attribute node selected from the element that contains it. Such a result
+ will be put into content form with each such disallowed node replaced by
+ its string value, as defined for the XPath 1.0
+ string function.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/functions.html b/pgsql/doc/postgresql/html/functions.html
new file mode 100644
index 0000000000000000000000000000000000000000..a34265749c32cfad96c02e6b0904d9cbe3e6aee7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/functions.html
@@ -0,0 +1,33 @@
+
+Chapter 9. Functions and Operators
+ PostgreSQL provides a large number of
+ functions and operators for the built-in data types. This chapter
+ describes most of them, although additional special-purpose functions
+ appear in relevant sections of the manual. Users can also
+ define their own functions and operators, as described in
+ Part V. The
+ psql commands \df and
+ \do can be used to list all
+ available functions and operators, respectively.
+
+ The notation used throughout this chapter to describe the argument and
+ result data types of a function or operator is like this:
+
+repeat ( text, integer ) → text
+
+ which says that the function repeat takes one text and
+ one integer argument and returns a result of type text. The right arrow
+ is also used to indicate the result of an example, thus:
+
+repeat('Pg', 4) → PgPgPgPg
+
+
+ If you are concerned about portability then note that most of
+ the functions and operators described in this chapter, with the
+ exception of the most trivial arithmetic and comparison operators
+ and some explicitly marked functions, are not specified by the
+ SQL standard. Some of this extended functionality
+ is present in other SQL database management
+ systems, and in many cases this functionality is compatible and
+ consistent between the various implementations.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/fuzzystrmatch.html b/pgsql/doc/postgresql/html/fuzzystrmatch.html
new file mode 100644
index 0000000000000000000000000000000000000000..fe41f2fbbd06e2e8e365170f20e5a1f80ad8eb76
--- /dev/null
+++ b/pgsql/doc/postgresql/html/fuzzystrmatch.html
@@ -0,0 +1,248 @@
+
+F.17. fuzzystrmatch — determine string similarities and distance
F.17. fuzzystrmatch — determine string similarities and distance
+ The fuzzystrmatch module provides several
+ functions to determine similarities and distance between strings.
+
Caution
+ At present, the soundex, metaphone,
+ dmetaphone, and dmetaphone_alt functions do
+ not work well with multibyte encodings (such as UTF-8).
+ Use daitch_mokotoff
+ or levenshtein with such data.
+
+ This module is considered “trusted”, that is, it can be
+ installed by non-superusers who have CREATE privilege
+ on the current database.
+
+ The Soundex system is a method of matching similar-sounding names
+ by converting them to the same code. It was initially used by the
+ United States Census in 1880, 1900, and 1910. Note that Soundex
+ is not very useful for non-English names.
+
+ The fuzzystrmatch module provides two functions
+ for working with Soundex codes:
+
+soundex(text) returns text
+difference(text, text) returns int
+
+ The soundex function converts a string to its Soundex code.
+ The difference function converts two strings to their Soundex
+ codes and then reports the number of matching code positions. Since
+ Soundex codes have four characters, the result ranges from zero to four,
+ with zero being no match and four being an exact match. (Thus, the
+ function is misnamed — similarity would have been
+ a better name.)
+
+ Here are some usage examples:
+
+SELECT soundex('hello world!');
+
+SELECT soundex('Anne'), soundex('Ann'), difference('Anne', 'Ann');
+SELECT soundex('Anne'), soundex('Andrew'), difference('Anne', 'Andrew');
+SELECT soundex('Anne'), soundex('Margaret'), difference('Anne', 'Margaret');
+
+CREATE TABLE s (nm text);
+
+INSERT INTO s VALUES ('john');
+INSERT INTO s VALUES ('joan');
+INSERT INTO s VALUES ('wobbly');
+INSERT INTO s VALUES ('jack');
+
+SELECT * FROM s WHERE soundex(nm) = soundex('john');
+
+SELECT * FROM s WHERE difference(s.nm, 'john') > 2;
+
+ Like the original Soundex system, Daitch-Mokotoff Soundex matches
+ similar-sounding names by converting them to the same code.
+ However, Daitch-Mokotoff Soundex is significantly more useful for
+ non-English names than the original system.
+ Major improvements over the original system include:
+
+
+ The code is based on the first six meaningful letters rather than four.
+
+ A letter or combination of letters maps into ten possible codes rather
+ than seven.
+
+ Where two consecutive letters have a single sound, they are coded as a
+ single number.
+
+ When a letter or combination of letters may have different sounds,
+ multiple codes are emitted to cover all possibilities.
+
+
+ This function generates the Daitch-Mokotoff soundex codes for its input:
+
+daitch_mokotoff(source text) returns text[]
+
+ The result may contain one or more codes depending on how many plausible
+ pronunciations there are, so it is represented as an array.
+
+ Since a Daitch-Mokotoff soundex code consists of only 6 digits,
+ source should be preferably a single word or name.
+
+ For matching of single names, returned text arrays can be matched
+ directly using the && operator: any overlap
+ can be considered a match. A GIN index may
+ be used for efficiency, see Chapter 70 and this example:
+
+CREATE TABLE s (nm text);
+CREATE INDEX ix_s_dm ON s USING gin (daitch_mokotoff(nm)) WITH (fastupdate = off);
+
+INSERT INTO s (nm) VALUES
+ ('Schwartzenegger'),
+ ('John'),
+ ('James'),
+ ('Steinman'),
+ ('Steinmetz');
+
+SELECT * FROM s WHERE daitch_mokotoff(nm) && daitch_mokotoff('Swartzenegger');
+SELECT * FROM s WHERE daitch_mokotoff(nm) && daitch_mokotoff('Jane');
+SELECT * FROM s WHERE daitch_mokotoff(nm) && daitch_mokotoff('Jens');
+
+ For indexing and matching of any number of names in any order, Full Text
+ Search features can be used. See Chapter 12 and this
+ example:
+
+CREATE FUNCTION soundex_tsvector(v_name text) RETURNS tsvector
+BEGIN ATOMIC
+ SELECT to_tsvector('simple',
+ string_agg(array_to_string(daitch_mokotoff(n), ' '), ' '))
+ FROM regexp_split_to_table(v_name, '\s+') AS n;
+END;
+
+CREATE FUNCTION soundex_tsquery(v_name text) RETURNS tsquery
+BEGIN ATOMIC
+ SELECT string_agg('(' || array_to_string(daitch_mokotoff(n), '|') || ')', '&')::tsquery
+ FROM regexp_split_to_table(v_name, '\s+') AS n;
+END;
+
+CREATE TABLE s (nm text);
+CREATE INDEX ix_s_txt ON s USING gin (soundex_tsvector(nm)) WITH (fastupdate = off);
+
+INSERT INTO s (nm) VALUES
+ ('John Doe'),
+ ('Jane Roe'),
+ ('Public John Q.'),
+ ('George Best'),
+ ('John Yamson');
+
+SELECT * FROM s WHERE soundex_tsvector(nm) @@ soundex_tsquery('john');
+SELECT * FROM s WHERE soundex_tsvector(nm) @@ soundex_tsquery('jane doe');
+SELECT * FROM s WHERE soundex_tsvector(nm) @@ soundex_tsquery('john public');
+SELECT * FROM s WHERE soundex_tsvector(nm) @@ soundex_tsquery('besst, giorgio');
+SELECT * FROM s WHERE soundex_tsvector(nm) @@ soundex_tsquery('Jameson John');
+
+ If it is desired to avoid recalculation of soundex codes during index
+ rechecks, an index on a separate column can be used instead of an index on
+ an expression. A stored generated column can be used for this; see
+ Section 5.3.
+
+ Both source and target can be any
+ non-null string, with a maximum of 255 characters. The cost parameters
+ specify how much to charge for a character insertion, deletion, or
+ substitution, respectively. You can omit the cost parameters, as in
+ the second version of the function; in that case they all default to 1.
+
+ levenshtein_less_equal is an accelerated version of the
+ Levenshtein function for use when only small distances are of interest.
+ If the actual distance is less than or equal to max_d,
+ then levenshtein_less_equal returns the correct
+ distance; otherwise it returns some value greater than max_d.
+ If max_d is negative then the behavior is the same as
+ levenshtein.
+
+ Metaphone, like Soundex, is based on the idea of constructing a
+ representative code for an input string. Two strings are then
+ deemed similar if they have the same codes.
+
+ This function calculates the metaphone code of an input string:
+
+metaphone(source text, max_output_length int) returns text
+
+ source has to be a non-null string with a maximum of
+ 255 characters. max_output_length sets the maximum
+ length of the output metaphone code; if longer, the output is truncated
+ to this length.
+
+ The Double Metaphone system computes two “sounds like” strings
+ for a given input string — a “primary” and an
+ “alternate”. In most cases they are the same, but for non-English
+ names especially they can be a bit different, depending on pronunciation.
+ These functions compute the primary and alternate codes:
+
+dmetaphone(source text) returns text
+dmetaphone_alt(source text) returns text
+
+ There is no length limit on the input strings.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/generic-wal.html b/pgsql/doc/postgresql/html/generic-wal.html
new file mode 100644
index 0000000000000000000000000000000000000000..4290b1b8fe60896fcf427fa95375dd7bccf087f8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/generic-wal.html
@@ -0,0 +1,102 @@
+
+Chapter 65. Generic WAL Records
+ Although all built-in WAL-logged modules have their own types of WAL
+ records, there is also a generic WAL record type, which describes changes
+ to pages in a generic way. This is useful for extensions that provide
+ custom access methods.
+
+ In comparison with Custom WAL Resource
+ Managers, Generic WAL is simpler for an extension to implement and
+ does not require the extension library to be loaded in order to apply the
+ records.
+
Note
+ Generic WAL records are ignored during Logical Decoding. If logical decoding is
+ required for your extension, consider a Custom WAL Resource Manager.
+
+ The API for constructing generic WAL records is defined in
+ access/generic_xlog.h and implemented
+ in access/transam/generic_xlog.c.
+
+ To perform a WAL-logged data update using the generic WAL record
+ facility, follow these steps:
+
+
+ state = GenericXLogStart(relation) — start
+ construction of a generic WAL record for the given relation.
+
+ page = GenericXLogRegisterBuffer(state, buffer, flags)
+ — register a buffer to be modified within the current generic WAL
+ record. This function returns a pointer to a temporary copy of the
+ buffer's page, where modifications should be made. (Do not modify the
+ buffer's contents directly.) The third argument is a bit mask of flags
+ applicable to the operation. Currently the only such flag is
+ GENERIC_XLOG_FULL_IMAGE, which indicates that a full-page
+ image rather than a delta update should be included in the WAL record.
+ Typically this flag would be set if the page is new or has been
+ rewritten completely.
+ GenericXLogRegisterBuffer can be repeated if the
+ WAL-logged action needs to modify multiple pages.
+
+ Apply modifications to the page images obtained in the previous step.
+
+ GenericXLogFinish(state) — apply the changes to
+ the buffers and emit the generic WAL record.
+
+
+ WAL record construction can be canceled between any of the above steps by
+ calling GenericXLogAbort(state). This will discard all
+ changes to the page image copies.
+
+ Please note the following points when using the generic WAL record
+ facility:
+
+
+ No direct modifications of buffers are allowed! All modifications must
+ be done in copies acquired from GenericXLogRegisterBuffer().
+ In other words, code that makes generic WAL records should never call
+ BufferGetPage() for itself. However, it remains the
+ caller's responsibility to pin/unpin and lock/unlock the buffers at
+ appropriate times. Exclusive lock must be held on each target buffer
+ from before GenericXLogRegisterBuffer() until after
+ GenericXLogFinish().
+
+ Registrations of buffers (step 2) and modifications of page images
+ (step 3) can be mixed freely, i.e., both steps may be repeated in any
+ sequence. Keep in mind that buffers should be registered in the same
+ order in which locks are to be obtained on them during replay.
+
+ The maximum number of buffers that can be registered for a generic WAL
+ record is MAX_GENERIC_XLOG_PAGES. An error will be thrown
+ if this limit is exceeded.
+
+ Generic WAL assumes that the pages to be modified have standard
+ layout, and in particular that there is no useful data between
+ pd_lower and pd_upper.
+
+ Since you are modifying copies of buffer
+ pages, GenericXLogStart() does not start a critical
+ section. Thus, you can safely do memory allocation, error throwing,
+ etc. between GenericXLogStart() and
+ GenericXLogFinish(). The only actual critical section is
+ present inside GenericXLogFinish(). There is no need to
+ worry about calling GenericXLogAbort() during an error
+ exit, either.
+
+ GenericXLogFinish() takes care of marking buffers dirty
+ and setting their LSNs. You do not need to do this explicitly.
+
+ For unlogged relations, everything works the same except that no
+ actual WAL record is emitted. Thus, you typically do not need to do
+ any explicit checks for unlogged relations.
+
+ The generic WAL redo function will acquire exclusive locks to buffers
+ in the same order as they were registered. After redoing all changes,
+ the locks will be released in the same order.
+
+ If GENERIC_XLOG_FULL_IMAGE is not specified for a
+ registered buffer, the generic WAL record contains a delta between
+ the old and the new page images. This delta is based on byte-by-byte
+ comparison. This is not very compact for the case of moving data
+ within a page, and might be improved in the future.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/genetic-algorithm.svg b/pgsql/doc/postgresql/html/genetic-algorithm.svg
new file mode 100644
index 0000000000000000000000000000000000000000..381ec7e64d6cb78eb937d253079153e42c0c5bf8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/genetic-algorithm.svg
@@ -0,0 +1,138 @@
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/geqo-biblio.html b/pgsql/doc/postgresql/html/geqo-biblio.html
new file mode 100644
index 0000000000000000000000000000000000000000..4f92568cdb7aa23524a2d74cfa01cf99876694a8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/geqo-biblio.html
@@ -0,0 +1,18 @@
+
+62.4. Further Reading
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/geqo-intro.html b/pgsql/doc/postgresql/html/geqo-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..7d4ed108886bb7428d472d10e4dce7a3a9f7262e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/geqo-intro.html
@@ -0,0 +1,36 @@
+
+62.1. Query Handling as a Complex Optimization Problem
62.1. Query Handling as a Complex Optimization Problem
62.1. Query Handling as a Complex Optimization Problem #
+ Among all relational operators the most difficult one to process
+ and optimize is the join. The number of
+ possible query plans grows exponentially with the
+ number of joins in the query. Further optimization effort is
+ caused by the support of a variety of join
+ methods (e.g., nested loop, hash join, merge join in
+ PostgreSQL) to process individual joins
+ and a diversity of indexes (e.g.,
+ B-tree, hash, GiST and GIN in PostgreSQL) as
+ access paths for relations.
+
+ The normal PostgreSQL query optimizer
+ performs a near-exhaustive search over the
+ space of alternative strategies. This algorithm, first introduced
+ in IBM's System R database, produces a near-optimal join order,
+ but can take an enormous amount of time and memory space when the
+ number of joins in the query grows large. This makes the ordinary
+ PostgreSQL query optimizer
+ inappropriate for queries that join a large number of tables.
+
+ The Institute of Automatic Control at the University of Mining and
+ Technology, in Freiberg, Germany, encountered some problems when
+ it wanted to use PostgreSQL as the
+ backend for a decision support knowledge based system for the
+ maintenance of an electrical power grid. The DBMS needed to handle
+ large join queries for the inference machine of the knowledge
+ based system. The number of joins in these queries made using the
+ normal query optimizer infeasible.
+
+ In the following we describe the implementation of a
+ genetic algorithm to solve the join
+ ordering problem in a manner that is efficient for queries
+ involving large numbers of joins.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/geqo-intro2.html b/pgsql/doc/postgresql/html/geqo-intro2.html
new file mode 100644
index 0000000000000000000000000000000000000000..6f3bc428fc9f10657597ffe83fc354c68f7a87f0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/geqo-intro2.html
@@ -0,0 +1,27 @@
+
+62.2. Genetic Algorithms
+ The genetic algorithm (GA) is a heuristic optimization method which
+ operates through randomized search. The set of possible solutions for the
+ optimization problem is considered as a
+ population of individuals.
+ The degree of adaptation of an individual to its environment is specified
+ by its fitness.
+
+ The coordinates of an individual in the search space are represented
+ by chromosomes, in essence a set of character
+ strings. A gene is a
+ subsection of a chromosome which encodes the value of a single parameter
+ being optimized. Typical encodings for a gene could be binary or
+ integer.
+
+ Through simulation of the evolutionary operations recombination,
+ mutation, and
+ selection new generations of search points are found
+ that show a higher average fitness than their ancestors. Figure 62.1
+ illustrates these steps.
+
Figure 62.1. Structure of a Genetic Algorithm
+ According to the comp.ai.genetic FAQ it cannot be stressed too
+ strongly that a GA is not a pure random search for a solution to a
+ problem. A GA uses stochastic processes, but the result is distinctly
+ non-random (better than random).
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/geqo-pg-intro.html b/pgsql/doc/postgresql/html/geqo-pg-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..87de4354e5662448afd4f9dced15e69148ceeec8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/geqo-pg-intro.html
@@ -0,0 +1,107 @@
+
+62.3. Genetic Query Optimization (GEQO) in PostgreSQL
62.3. Genetic Query Optimization (GEQO) in PostgreSQL
+ The GEQO module approaches the query
+ optimization problem as though it were the well-known traveling salesman
+ problem (TSP).
+ Possible query plans are encoded as integer strings. Each string
+ represents the join order from one relation of the query to the next.
+ For example, the join tree
+
+ /\
+ /\ 2
+ /\ 3
+4 1
+
+ is encoded by the integer string '4-1-3-2',
+ which means, first join relation '4' and '1', then '3', and
+ then '2', where 1, 2, 3, 4 are relation IDs within the
+ PostgreSQL optimizer.
+
+ Specific characteristics of the GEQO
+ implementation in PostgreSQL
+ are:
+
+
+ Usage of a steady state GA (replacement of the least fit
+ individuals in a population, not whole-generational replacement)
+ allows fast convergence towards improved query plans. This is
+ essential for query handling with reasonable time;
+
+ Usage of edge recombination crossover
+ which is especially suited to keep edge losses low for the
+ solution of the TSP by means of a
+ GA;
+
+ Mutation as genetic operator is deprecated so that no repair
+ mechanisms are needed to generate legal TSP tours.
+
+
+ Parts of the GEQO module are adapted from D. Whitley's
+ Genitor algorithm.
+
+ The GEQO module allows
+ the PostgreSQL query optimizer to
+ support large join queries effectively through
+ non-exhaustive search.
+
+ The GEQO planning process uses the standard planner
+ code to generate plans for scans of individual relations. Then join
+ plans are developed using the genetic approach. As shown above, each
+ candidate join plan is represented by a sequence in which to join
+ the base relations. In the initial stage, the GEQO
+ code simply generates some possible join sequences at random. For each
+ join sequence considered, the standard planner code is invoked to
+ estimate the cost of performing the query using that join sequence.
+ (For each step of the join sequence, all three possible join strategies
+ are considered; and all the initially-determined relation scan plans
+ are available. The estimated cost is the cheapest of these
+ possibilities.) Join sequences with lower estimated cost are considered
+ “more fit” than those with higher cost. The genetic algorithm
+ discards the least fit candidates. Then new candidates are generated
+ by combining genes of more-fit candidates — that is, by using
+ randomly-chosen portions of known low-cost join sequences to create
+ new sequences for consideration. This process is repeated until a
+ preset number of join sequences have been considered; then the best
+ one found at any time during the search is used to generate the finished
+ plan.
+
+ This process is inherently nondeterministic, because of the randomized
+ choices made during both the initial population selection and subsequent
+ “mutation” of the best candidates. To avoid surprising changes
+ of the selected plan, each run of the GEQO algorithm restarts its
+ random number generator with the current geqo_seed
+ parameter setting. As long as geqo_seed and the other
+ GEQO parameters are kept fixed, the same plan will be generated for a
+ given query (and other planner inputs such as statistics). To experiment
+ with different search paths, try changing geqo_seed.
+
62.3.2. Future Implementation Tasks for
+ PostgreSQL GEQO #
+ Work is still needed to improve the genetic algorithm parameter
+ settings.
+ In file src/backend/optimizer/geqo/geqo_main.c,
+ routines
+ gimme_pool_size and gimme_number_generations,
+ we have to find a compromise for the parameter settings
+ to satisfy two competing demands:
+
+ Optimality of the query plan
+
+ Computing time
+
+
+ In the current implementation, the fitness of each candidate join
+ sequence is estimated by running the standard planner's join selection
+ and cost estimation code from scratch. To the extent that different
+ candidates use similar sub-sequences of joins, a great deal of work
+ will be repeated. This could be made significantly faster by retaining
+ cost estimates for sub-joins. The problem is to avoid expending
+ unreasonable amounts of memory on retaining that state.
+
+ At a more basic level, it is not clear that solving query optimization
+ with a GA algorithm designed for TSP is appropriate. In the TSP case,
+ the cost associated with any substring (partial tour) is independent
+ of the rest of the tour, but this is certainly not true for query
+ optimization. Thus it is questionable whether edge recombination
+ crossover is the most effective mutation procedure.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/geqo.html b/pgsql/doc/postgresql/html/geqo.html
new file mode 100644
index 0000000000000000000000000000000000000000..53b6222205982cb05da571627a3fb868ee192a78
--- /dev/null
+++ b/pgsql/doc/postgresql/html/geqo.html
@@ -0,0 +1,8 @@
+
+Chapter 62. Genetic Query Optimizer
+ Written by Martin Utesch (<utesch@aut.tu-freiberg.de>)
+ for the Institute of Automatic Control at the University of Mining and Technology in Freiberg, Germany.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-builtin-opclasses.html b/pgsql/doc/postgresql/html/gin-builtin-opclasses.html
new file mode 100644
index 0000000000000000000000000000000000000000..afb3a810e4e8945bd17ee74b7bb28dd1efda0dd0
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-builtin-opclasses.html
@@ -0,0 +1,13 @@
+
+70.2. Built-in Operator Classes
+ The core PostgreSQL distribution
+ includes the GIN operator classes shown in
+ Table 70.1.
+ (Some of the optional modules described in Appendix F
+ provide additional GIN operator classes.)
+
Table 70.1. Built-in GIN Operator Classes
Name
Indexable Operators
array_ops
&& (anyarray,anyarray)
@> (anyarray,anyarray)
<@ (anyarray,anyarray)
= (anyarray,anyarray)
jsonb_ops
@> (jsonb,jsonb)
@? (jsonb,jsonpath)
@@ (jsonb,jsonpath)
? (jsonb,text)
?| (jsonb,text[])
?& (jsonb,text[])
jsonb_path_ops
@> (jsonb,jsonb)
@? (jsonb,jsonpath)
@@ (jsonb,jsonpath)
tsvector_ops
@@ (tsvector,tsquery)
@@@ (tsvector,tsquery)
+ Of the two operator classes for type jsonb, jsonb_ops
+ is the default. jsonb_path_ops supports fewer operators but
+ offers better performance for those operators.
+ See Section 8.14.4 for details.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-examples.html b/pgsql/doc/postgresql/html/gin-examples.html
new file mode 100644
index 0000000000000000000000000000000000000000..caedb9c221dadbefcd6918842e574723e6426f2a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-examples.html
@@ -0,0 +1,10 @@
+
+70.7. Examples
+ The core PostgreSQL distribution
+ includes the GIN operator classes previously shown in
+ Table 70.1.
+ The following contrib modules also contain
+ GIN operator classes:
+
+
btree_gin
B-tree equivalent functionality for several data types
hstore
Module for storing (key, value) pairs
intarray
Enhanced support for int[]
pg_trgm
Text similarity using trigram matching
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-extensibility.html b/pgsql/doc/postgresql/html/gin-extensibility.html
new file mode 100644
index 0000000000000000000000000000000000000000..a930480431601c60982d1192c59241b3272d3636
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-extensibility.html
@@ -0,0 +1,237 @@
+
+70.3. Extensibility
+ The GIN interface has a high level of abstraction,
+ requiring the access method implementer only to implement the semantics of
+ the data type being accessed. The GIN layer itself
+ takes care of concurrency, logging and searching the tree structure.
+
+ All it takes to get a GIN access method working is to
+ implement a few user-defined methods, which define the behavior of
+ keys in the tree and the relationships between keys, indexed items,
+ and indexable queries. In short, GIN combines
+ extensibility with generality, code reuse, and a clean interface.
+
+ There are two methods that an operator class for
+ GIN must provide:
+
+
Datum *extractValue(Datum itemValue, int32 *nkeys,
+ bool **nullFlags)
+ Returns a palloc'd array of keys given an item to be indexed. The
+ number of returned keys must be stored into *nkeys.
+ If any of the keys can be null, also palloc an array of
+ *nkeysbool fields, store its address at
+ *nullFlags, and set these null flags as needed.
+ *nullFlags can be left NULL (its initial value)
+ if all keys are non-null.
+ The return value can be NULL if the item contains no keys.
+
Datum *extractQuery(Datum query, int32 *nkeys,
+ StrategyNumber n, bool **pmatch, Pointer **extra_data,
+ bool **nullFlags, int32 *searchMode)
+ Returns a palloc'd array of keys given a value to be queried; that is,
+ query is the value on the right-hand side of an
+ indexable operator whose left-hand side is the indexed column.
+ n is the strategy number of the operator within the
+ operator class (see Section 38.16.2).
+ Often, extractQuery will need
+ to consult n to determine the data type of
+ query and the method it should use to extract key values.
+ The number of returned keys must be stored into *nkeys.
+ If any of the keys can be null, also palloc an array of
+ *nkeysbool fields, store its address at
+ *nullFlags, and set these null flags as needed.
+ *nullFlags can be left NULL (its initial value)
+ if all keys are non-null.
+ The return value can be NULL if the query contains no keys.
+
+ searchMode is an output argument that allows
+ extractQuery to specify details about how the search
+ will be done.
+ If *searchMode is set to
+ GIN_SEARCH_MODE_DEFAULT (which is the value it is
+ initialized to before call), only items that match at least one of
+ the returned keys are considered candidate matches.
+ If *searchMode is set to
+ GIN_SEARCH_MODE_INCLUDE_EMPTY, then in addition to items
+ containing at least one matching key, items that contain no keys at
+ all are considered candidate matches. (This mode is useful for
+ implementing is-subset-of operators, for example.)
+ If *searchMode is set to GIN_SEARCH_MODE_ALL,
+ then all non-null items in the index are considered candidate
+ matches, whether they match any of the returned keys or not. (This
+ mode is much slower than the other two choices, since it requires
+ scanning essentially the entire index, but it may be necessary to
+ implement corner cases correctly. An operator that needs this mode
+ in most cases is probably not a good candidate for a GIN operator
+ class.)
+ The symbols to use for setting this mode are defined in
+ access/gin.h.
+
+ pmatch is an output argument for use when partial match
+ is supported. To use it, extractQuery must allocate
+ an array of *nkeysbools and store its address at
+ *pmatch. Each element of the array should be set to true
+ if the corresponding key requires partial match, false if not.
+ If *pmatch is set to NULL then GIN assumes partial match
+ is not required. The variable is initialized to NULL before call,
+ so this argument can simply be ignored by operator classes that do
+ not support partial match.
+
+ extra_data is an output argument that allows
+ extractQuery to pass additional data to the
+ consistent and comparePartial methods.
+ To use it, extractQuery must allocate
+ an array of *nkeys pointers and store its address at
+ *extra_data, then store whatever it wants to into the
+ individual pointers. The variable is initialized to NULL before
+ call, so this argument can simply be ignored by operator classes that
+ do not require extra data. If *extra_data is set, the
+ whole array is passed to the consistent method, and
+ the appropriate element to the comparePartial method.
+
+
+ An operator class must also provide a function to check if an indexed item
+ matches the query. It comes in two flavors, a Boolean consistent
+ function, and a ternary triConsistent function.
+ triConsistent covers the functionality of both, so providing
+ triConsistent alone is sufficient. However, if the Boolean
+ variant is significantly cheaper to calculate, it can be advantageous to
+ provide both. If only the Boolean variant is provided, some optimizations
+ that depend on refuting index items before fetching all the keys are
+ disabled.
+
+
bool consistent(bool check[], StrategyNumber n, Datum query,
+ int32 nkeys, Pointer extra_data[], bool *recheck,
+ Datum queryKeys[], bool nullFlags[])
+ Returns true if an indexed item satisfies the query operator with
+ strategy number n (or might satisfy it, if the recheck
+ indication is returned). This function does not have direct access
+ to the indexed item's value, since GIN does not
+ store items explicitly. Rather, what is available is knowledge
+ about which key values extracted from the query appear in a given
+ indexed item. The check array has length
+ nkeys, which is the same as the number of keys previously
+ returned by extractQuery for this query datum.
+ Each element of the
+ check array is true if the indexed item contains the
+ corresponding query key, i.e., if (check[i] == true) the i-th key of the
+ extractQuery result array is present in the indexed item.
+ The original query datum is
+ passed in case the consistent method needs to consult it,
+ and so are the queryKeys[] and nullFlags[]
+ arrays previously returned by extractQuery.
+ extra_data is the extra-data array returned by
+ extractQuery, or NULL if none.
+
+ When extractQuery returns a null key in
+ queryKeys[], the corresponding check[] element
+ is true if the indexed item contains a null key; that is, the
+ semantics of check[] are like IS NOT DISTINCT
+ FROM. The consistent function can examine the
+ corresponding nullFlags[] element if it needs to tell
+ the difference between a regular value match and a null match.
+
+ On success, *recheck should be set to true if the heap
+ tuple needs to be rechecked against the query operator, or false if
+ the index test is exact. That is, a false return value guarantees
+ that the heap tuple does not match the query; a true return value with
+ *recheck set to false guarantees that the heap tuple does
+ match the query; and a true return value with
+ *recheck set to true means that the heap tuple might match
+ the query, so it needs to be fetched and rechecked by evaluating the
+ query operator directly against the originally indexed item.
+
GinTernaryValue triConsistent(GinTernaryValue check[], StrategyNumber n, Datum query,
+ int32 nkeys, Pointer extra_data[],
+ Datum queryKeys[], bool nullFlags[])
+ triConsistent is similar to consistent,
+ but instead of Booleans in the check vector, there are
+ three possible values for each
+ key: GIN_TRUE, GIN_FALSE and
+ GIN_MAYBE. GIN_FALSE and GIN_TRUE
+ have the same meaning as regular Boolean values, while
+ GIN_MAYBE means that the presence of that key is not known.
+ When GIN_MAYBE values are present, the function should only
+ return GIN_TRUE if the item certainly matches whether or
+ not the index item contains the corresponding query keys. Likewise, the
+ function must return GIN_FALSE only if the item certainly
+ does not match, whether or not it contains the GIN_MAYBE
+ keys. If the result depends on the GIN_MAYBE entries, i.e.,
+ the match cannot be confirmed or refuted based on the known query keys,
+ the function must return GIN_MAYBE.
+
+ When there are no GIN_MAYBE values in the check
+ vector, a GIN_MAYBE return value is the equivalent of
+ setting the recheck flag in the
+ Boolean consistent function.
+
+
+ In addition, GIN must have a way to sort the key values stored in the index.
+ The operator class can define the sort ordering by specifying a comparison
+ method:
+
+
int compare(Datum a, Datum b)
+ Compares two keys (not indexed items!) and returns an integer less than
+ zero, zero, or greater than zero, indicating whether the first key is
+ less than, equal to, or greater than the second. Null keys are never
+ passed to this function.
+
+
+ Alternatively, if the operator class does not provide a compare
+ method, GIN will look up the default btree operator class for the index
+ key data type, and use its comparison function. It is recommended to
+ specify the comparison function in a GIN operator class that is meant for
+ just one data type, as looking up the btree operator class costs a few
+ cycles. However, polymorphic GIN operator classes (such
+ as array_ops) typically cannot specify a single comparison
+ function.
+
+ An operator class for GIN can optionally supply the
+ following methods:
+
+
int comparePartial(Datum partial_key, Datum key, StrategyNumber n,
+ Pointer extra_data)
+ Compare a partial-match query key to an index key. Returns an integer
+ whose sign indicates the result: less than zero means the index key
+ does not match the query, but the index scan should continue; zero
+ means that the index key does match the query; greater than zero
+ indicates that the index scan should stop because no more matches
+ are possible. The strategy number n of the operator
+ that generated the partial match query is provided, in case its
+ semantics are needed to determine when to end the scan. Also,
+ extra_data is the corresponding element of the extra-data
+ array made by extractQuery, or NULL if none.
+ Null keys are never passed to this function.
+
void options(local_relopts *relopts)
+ Defines a set of user-visible parameters that control operator class
+ behavior.
+
+ The options function is passed a pointer to a
+ local_relopts struct, which needs to be
+ filled with a set of operator class specific options. The options
+ can be accessed from other support functions using the
+ PG_HAS_OPCLASS_OPTIONS() and
+ PG_GET_OPCLASS_OPTIONS() macros.
+
+ Since both key extraction of indexed values and representation of the
+ key in GIN are flexible, they may depend on
+ user-specified parameters.
+
+
+ To support “partial match” queries, an operator class must
+ provide the comparePartial method, and its
+ extractQuery method must set the pmatch
+ parameter when a partial-match query is encountered. See
+ Section 70.4.2 for details.
+
+ The actual data types of the various Datum values mentioned
+ above vary depending on the operator class. The item values passed to
+ extractValue are always of the operator class's input type, and
+ all key values must be of the class's STORAGE type. The type of
+ the query argument passed to extractQuery,
+ consistent and triConsistent is whatever is the
+ right-hand input type of the class member operator identified by the
+ strategy number. This need not be the same as the indexed type, so long as
+ key values of the correct type can be extracted from it. However, it is
+ recommended that the SQL declarations of these three support functions use
+ the opclass's indexed data type for the query argument, even
+ though the actual type might be something else depending on the operator.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-implementation.html b/pgsql/doc/postgresql/html/gin-implementation.html
new file mode 100644
index 0000000000000000000000000000000000000000..32b1d071f9d2aa3b17c3d3e112914db9583bbe8b
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-implementation.html
@@ -0,0 +1,64 @@
+
+70.4. Implementation
+ Internally, a GIN index contains a B-tree index
+ constructed over keys, where each key is an element of one or more indexed
+ items (a member of an array, for example) and where each tuple in a leaf
+ page contains either a pointer to a B-tree of heap pointers (a
+ “posting tree”), or a simple list of heap pointers (a “posting
+ list”) when the list is small enough to fit into a single index tuple along
+ with the key value. Figure 70.1 illustrates
+ these components of a GIN index.
+
+ As of PostgreSQL 9.1, null key values can be
+ included in the index. Also, placeholder nulls are included in the index
+ for indexed items that are null or contain no keys according to
+ extractValue. This allows searches that should find empty
+ items to do so.
+
+ Multicolumn GIN indexes are implemented by building
+ a single B-tree over composite values (column number, key value). The
+ key values for different columns can be of different types.
+
+ Updating a GIN index tends to be slow because of the
+ intrinsic nature of inverted indexes: inserting or updating one heap row
+ can cause many inserts into the index (one for each key extracted
+ from the indexed item).
+ GIN is capable of postponing much of this work by inserting
+ new tuples into a temporary, unsorted list of pending entries.
+ When the table is vacuumed or autoanalyzed, or when
+ gin_clean_pending_list function is called, or if the
+ pending list becomes larger than
+ gin_pending_list_limit, the entries are moved to the
+ main GIN data structure using the same bulk insert
+ techniques used during initial index creation. This greatly improves
+ GIN index update speed, even counting the additional
+ vacuum overhead. Moreover the overhead work can be done by a background
+ process instead of in foreground query processing.
+
+ The main disadvantage of this approach is that searches must scan the list
+ of pending entries in addition to searching the regular index, and so
+ a large list of pending entries will slow searches significantly.
+ Another disadvantage is that, while most updates are fast, an update
+ that causes the pending list to become “too large” will incur an
+ immediate cleanup cycle and thus be much slower than other updates.
+ Proper use of autovacuum can minimize both of these problems.
+
+ If consistent response time is more important than update speed,
+ use of pending entries can be disabled by turning off the
+ fastupdate storage parameter for a
+ GIN index. See CREATE INDEX
+ for details.
+
+ GIN can support “partial match” queries, in which the query
+ does not determine an exact match for one or more keys, but the possible
+ matches fall within a reasonably narrow range of key values (within the
+ key sorting order determined by the compare support method).
+ The extractQuery method, instead of returning a key value
+ to be matched exactly, returns a key value that is the lower bound of
+ the range to be searched, and sets the pmatch flag true.
+ The key range is then scanned using the comparePartial
+ method. comparePartial must return zero for a matching
+ index key, less than zero for a non-match that is still within the range
+ to be searched, or greater than zero if the index key is past the range
+ that could match.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-intro.html b/pgsql/doc/postgresql/html/gin-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..10be41cad7ccfce146473949b0678cba41539c70
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-intro.html
@@ -0,0 +1,40 @@
+
+70.1. Introduction
+ GIN stands for Generalized Inverted Index.
+ GIN is designed for handling cases where the items
+ to be indexed are composite values, and the queries to be handled by
+ the index need to search for element values that appear within
+ the composite items. For example, the items could be documents,
+ and the queries could be searches for documents containing specific words.
+
+ We use the word item to refer to a composite value that
+ is to be indexed, and the word key to refer to an element
+ value. GIN always stores and searches for keys,
+ not item values per se.
+
+ A GIN index stores a set of (key, posting list) pairs,
+ where a posting list is a set of row IDs in which the key
+ occurs. The same row ID can appear in multiple posting lists, since
+ an item can contain more than one key. Each key value is stored only
+ once, so a GIN index is very compact for cases
+ where the same key appears many times.
+
+ GIN is generalized in the sense that the
+ GIN access method code does not need to know the
+ specific operations that it accelerates.
+ Instead, it uses custom strategies defined for particular data types.
+ The strategy defines how keys are extracted from indexed items and
+ query conditions, and how to determine whether a row that contains
+ some of the key values in a query actually satisfies the query.
+
+ One advantage of GIN is that it allows the development
+ of custom data types with the appropriate access methods, by
+ an expert in the domain of the data type, rather than a database expert.
+ This is much the same advantage as using GiST.
+
+ The GIN
+ implementation in PostgreSQL is primarily
+ maintained by Teodor Sigaev and Oleg Bartunov. There is more
+ information about GIN on their
+ website.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-limit.html b/pgsql/doc/postgresql/html/gin-limit.html
new file mode 100644
index 0000000000000000000000000000000000000000..7cf0fd29cf4ac17e34e1623f7d86059509de76a7
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-limit.html
@@ -0,0 +1,10 @@
+
+70.6. Limitations
+ GIN assumes that indexable operators are strict. This
+ means that extractValue will not be called at all on a null
+ item value (instead, a placeholder index entry is created automatically),
+ and extractQuery will not be called on a null query
+ value either (instead, the query is presumed to be unsatisfiable). Note
+ however that null key values contained within a non-null composite item
+ or query value are supported.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin-tips.html b/pgsql/doc/postgresql/html/gin-tips.html
new file mode 100644
index 0000000000000000000000000000000000000000..8f6b0e618b58576a03d28869dec5d46d87994e8e
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin-tips.html
@@ -0,0 +1,58 @@
+
+70.5. GIN Tips and Tricks
+ Insertion into a GIN index can be slow
+ due to the likelihood of many keys being inserted for each item.
+ So, for bulk insertions into a table it is advisable to drop the GIN
+ index and recreate it after finishing bulk insertion.
+
+ When fastupdate is enabled for GIN
+ (see Section 70.4.1 for details), the penalty is
+ less than when it is not. But for very large updates it may still be
+ best to drop and recreate the index.
+
+ Build time for a GIN index is very sensitive to
+ the maintenance_work_mem setting; it doesn't pay to
+ skimp on work memory during index creation.
+
+ During a series of insertions into an existing GIN
+ index that has fastupdate enabled, the system will clean up
+ the pending-entry list whenever the list grows larger than
+ gin_pending_list_limit. To avoid fluctuations in observed
+ response time, it's desirable to have pending-list cleanup occur in the
+ background (i.e., via autovacuum). Foreground cleanup operations
+ can be avoided by increasing gin_pending_list_limit
+ or making autovacuum more aggressive.
+ However, enlarging the threshold of the cleanup operation means that
+ if a foreground cleanup does occur, it will take even longer.
+
+ gin_pending_list_limit can be overridden for individual
+ GIN indexes by changing storage parameters, which allows each
+ GIN index to have its own cleanup threshold.
+ For example, it's possible to increase the threshold only for the GIN
+ index which can be updated heavily, and decrease it otherwise.
+
+ The primary goal of developing GIN indexes was
+ to create support for highly scalable full-text search in
+ PostgreSQL, and there are often situations when
+ a full-text search returns a very large set of results. Moreover, this
+ often happens when the query contains very frequent words, so that the
+ large result set is not even useful. Since reading many
+ tuples from the disk and sorting them could take a lot of time, this is
+ unacceptable for production. (Note that the index search itself is very
+ fast.)
+
+ To facilitate controlled execution of such queries,
+ GIN has a configurable soft upper limit on the
+ number of rows returned: the
+ gin_fuzzy_search_limit configuration parameter.
+ It is set to 0 (meaning no limit) by default.
+ If a non-zero limit is set, then the returned set is a subset of
+ the whole result set, chosen at random.
+
+ “Soft” means that the actual number of returned results
+ could differ somewhat from the specified limit, depending on the query
+ and the quality of the system's random number generator.
+
+ From experience, values in the thousands (e.g., 5000 — 20000)
+ work well.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin.html b/pgsql/doc/postgresql/html/gin.html
new file mode 100644
index 0000000000000000000000000000000000000000..bb993bc97e30d1c14ccca91576b69a6ede59f386
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin.html
@@ -0,0 +1,2 @@
+
+Chapter 70. GIN Indexes
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gin.svg b/pgsql/doc/postgresql/html/gin.svg
new file mode 100644
index 0000000000000000000000000000000000000000..347fd3bc0e6cf0ddea289ae7d8636b120b67f653
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gin.svg
@@ -0,0 +1,315 @@
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gist-builtin-opclasses.html b/pgsql/doc/postgresql/html/gist-builtin-opclasses.html
new file mode 100644
index 0000000000000000000000000000000000000000..6f7b304dd7d0286d2a9406fc07f96d0d1a03c11f
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gist-builtin-opclasses.html
@@ -0,0 +1,16 @@
+
+68.2. Built-in Operator Classes
+ The core PostgreSQL distribution
+ includes the GiST operator classes shown in
+ Table 68.1.
+ (Some of the optional modules described in Appendix F
+ provide additional GiST operator classes.)
+
Table 68.1. Built-in GiST Operator Classes
Name
Indexable Operators
Ordering Operators
box_ops
<< (box, box)
<-> (box, point)
&< (box, box)
&& (box, box)
&> (box, box)
>> (box, box)
~= (box, box)
@> (box, box)
<@ (box, box)
&<| (box, box)
<<| (box, box)
|>> (box, box)
|&> (box, box)
circle_ops
<< (circle, circle)
<-> (circle, point)
&< (circle, circle)
&> (circle, circle)
>> (circle, circle)
<@ (circle, circle)
@> (circle, circle)
~= (circle, circle)
&& (circle, circle)
|>> (circle, circle)
<<| (circle, circle)
&<| (circle, circle)
|&> (circle, circle)
inet_ops
<< (inet, inet)
<<= (inet, inet)
>> (inet, inet)
>>= (inet, inet)
= (inet, inet)
<> (inet, inet)
< (inet, inet)
<= (inet, inet)
> (inet, inet)
>= (inet, inet)
&& (inet, inet)
multirange_ops
= (anymultirange, anymultirange)
&& (anymultirange, anymultirange)
&& (anymultirange, anyrange)
@> (anymultirange, anyelement)
@> (anymultirange, anymultirange)
@> (anymultirange, anyrange)
<@ (anymultirange, anymultirange)
<@ (anymultirange, anyrange)
<< (anymultirange, anymultirange)
<< (anymultirange, anyrange)
>> (anymultirange, anymultirange)
>> (anymultirange, anyrange)
&< (anymultirange, anymultirange)
&< (anymultirange, anyrange)
&> (anymultirange, anymultirange)
&> (anymultirange, anyrange)
-|- (anymultirange, anymultirange)
-|- (anymultirange, anyrange)
point_ops
|>> (point, point)
<-> (point, point)
<< (point, point)
>> (point, point)
<<| (point, point)
~= (point, point)
<@ (point, box)
<@ (point, polygon)
<@ (point, circle)
poly_ops
<< (polygon, polygon)
<-> (polygon, point)
&< (polygon, polygon)
&> (polygon, polygon)
>> (polygon, polygon)
<@ (polygon, polygon)
@> (polygon, polygon)
~= (polygon, polygon)
&& (polygon, polygon)
<<| (polygon, polygon)
&<| (polygon, polygon)
|&> (polygon, polygon)
|>> (polygon, polygon)
range_ops
= (anyrange, anyrange)
&& (anyrange, anyrange)
&& (anyrange, anymultirange)
@> (anyrange, anyelement)
@> (anyrange, anyrange)
@> (anyrange, anymultirange)
<@ (anyrange, anyrange)
<@ (anyrange, anymultirange)
<< (anyrange, anyrange)
<< (anyrange, anymultirange)
>> (anyrange, anyrange)
>> (anyrange, anymultirange)
&< (anyrange, anyrange)
&< (anyrange, anymultirange)
&> (anyrange, anyrange)
&> (anyrange, anymultirange)
-|- (anyrange, anyrange)
-|- (anyrange, anymultirange)
tsquery_ops
<@ (tsquery, tsquery)
@> (tsquery, tsquery)
tsvector_ops
@@ (tsvector, tsquery)
+ For historical reasons, the inet_ops operator class is
+ not the default class for types inet and cidr.
+ To use it, mention the class name in CREATE INDEX,
+ for example
+
+CREATE INDEX ON my_table USING GIST (my_inet_column inet_ops);
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gist-examples.html b/pgsql/doc/postgresql/html/gist-examples.html
new file mode 100644
index 0000000000000000000000000000000000000000..42fe55e63fc0dadddd1989b3329ee280167e87a6
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gist-examples.html
@@ -0,0 +1,13 @@
+
+68.5. Examples
+ The PostgreSQL source distribution includes
+ several examples of index methods implemented using
+ GiST. The core system currently provides text search
+ support (indexing for tsvector and tsquery) as well as
+ R-Tree equivalent functionality for some of the built-in geometric data types
+ (see src/backend/access/gist/gistproc.c). The following
+ contrib modules also contain GiST
+ operator classes:
+
+
btree_gist
B-tree equivalent functionality for several data types
cube
Indexing for multidimensional cubes
hstore
Module for storing (key, value) pairs
intarray
RD-Tree for one-dimensional array of int4 values
ltree
Indexing for tree-like structures
pg_trgm
Text similarity using trigram matching
seg
Indexing for “float ranges”
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gist-extensibility.html b/pgsql/doc/postgresql/html/gist-extensibility.html
new file mode 100644
index 0000000000000000000000000000000000000000..8935b611df748907a460b0cdba24049c0f2893ec
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gist-extensibility.html
@@ -0,0 +1,813 @@
+
+68.3. Extensibility
+ Traditionally, implementing a new index access method meant a lot of
+ difficult work. It was necessary to understand the inner workings of the
+ database, such as the lock manager and Write-Ahead Log. The
+ GiST interface has a high level of abstraction,
+ requiring the access method implementer only to implement the semantics of
+ the data type being accessed. The GiST layer itself
+ takes care of concurrency, logging and searching the tree structure.
+
+ This extensibility should not be confused with the extensibility of the
+ other standard search trees in terms of the data they can handle. For
+ example, PostgreSQL supports extensible B-trees
+ and hash indexes. That means that you can use
+ PostgreSQL to build a B-tree or hash over any
+ data type you want. But B-trees only support range predicates
+ (<, =, >),
+ and hash indexes only support equality queries.
+
+ So if you index, say, an image collection with a
+ PostgreSQL B-tree, you can only issue queries
+ such as “is imagex equal to imagey”, “is imagex less
+ than imagey” and “is imagex greater than imagey”.
+ Depending on how you define “equals”, “less than”
+ and “greater than” in this context, this could be useful.
+ However, by using a GiST based index, you could create
+ ways to ask domain-specific questions, perhaps “find all images of
+ horses” or “find all over-exposed images”.
+
+ All it takes to get a GiST access method up and running
+ is to implement several user-defined methods, which define the behavior of
+ keys in the tree. Of course these methods have to be pretty fancy to
+ support fancy queries, but for all the standard queries (B-trees,
+ R-trees, etc.) they're relatively straightforward. In short,
+ GiST combines extensibility along with generality, code
+ reuse, and a clean interface.
+
+ There are five methods that an index operator class for
+ GiST must provide, and six that are optional.
+ Correctness of the index is ensured
+ by proper implementation of the same, consistent
+ and union methods, while efficiency (size and speed) of the
+ index will depend on the penalty and picksplit
+ methods.
+ Two optional methods are compress and
+ decompress, which allow an index to have internal tree data of
+ a different type than the data it indexes. The leaves are to be of the
+ indexed data type, while the other tree nodes can be of any C struct (but
+ you still have to follow PostgreSQL data type rules here,
+ see about varlena for variable sized data). If the tree's
+ internal data type exists at the SQL level, the STORAGE option
+ of the CREATE OPERATOR CLASS command can be used.
+ The optional eighth method is distance, which is needed
+ if the operator class wishes to support ordered scans (nearest-neighbor
+ searches). The optional ninth method fetch is needed if the
+ operator class wishes to support index-only scans, except when the
+ compress method is omitted. The optional tenth method
+ options is needed if the operator class has
+ user-specified parameters.
+ The optional eleventh method sortsupport is used to
+ speed up building a GiST index.
+
consistent
+ Given an index entry p and a query value q,
+ this function determines whether the index entry is
+ “consistent” with the query; that is, could the predicate
+ “indexed_column
+ indexable_operatorq” be true for
+ any row represented by the index entry? For a leaf index entry this is
+ equivalent to testing the indexable condition, while for an internal
+ tree node this determines whether it is necessary to scan the subtree
+ of the index represented by the tree node. When the result is
+ true, a recheck flag must also be returned.
+ This indicates whether the predicate is certainly true or only possibly
+ true. If recheck = false then the index has
+ tested the predicate condition exactly, whereas if recheck
+ = true the row is only a candidate match. In that case the
+ system will automatically evaluate the
+ indexable_operator against the actual row value to see
+ if it is really a match. This convention allows
+ GiST to support both lossless and lossy index
+ structures.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_consistent(internal, data_type, smallint, oid, internal)
+RETURNS bool
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_consistent);
+
+Datum
+my_consistent(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ data_type *query = PG_GETARG_DATA_TYPE_P(1);
+ StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
+ /* Oid subtype = PG_GETARG_OID(3); */
+ bool *recheck = (bool *) PG_GETARG_POINTER(4);
+ data_type *key = DatumGetDataType(entry->key);
+ bool retval;
+
+ /*
+ * determine return value as a function of strategy, key and query.
+ *
+ * Use GIST_LEAF(entry) to know where you're called in the index tree,
+ * which comes handy when supporting the = operator for example (you could
+ * check for non empty union() in non-leaf nodes and equality in leaf
+ * nodes).
+ */
+
+ *recheck = true; /* or false if check is exact */
+
+ PG_RETURN_BOOL(retval);
+}
+
+
+ Here, key is an element in the index and query
+ the value being looked up in the index. The StrategyNumber
+ parameter indicates which operator of your operator class is being
+ applied — it matches one of the operator numbers in the
+ CREATE OPERATOR CLASS command.
+
+ Depending on which operators you have included in the class, the data
+ type of query could vary with the operator, since it will
+ be whatever type is on the right-hand side of the operator, which might
+ be different from the indexed data type appearing on the left-hand side.
+ (The above code skeleton assumes that only one type is possible; if
+ not, fetching the query argument value would have to depend
+ on the operator.) It is recommended that the SQL declaration of
+ the consistent function use the opclass's indexed data
+ type for the query argument, even though the actual type
+ might be something else depending on the operator.
+
union
+ This method consolidates information in the tree. Given a set of
+ entries, this function generates a new index entry that represents
+ all the given entries.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_union(internal, internal)
+RETURNS storage_type
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_union);
+
+Datum
+my_union(PG_FUNCTION_ARGS)
+{
+ GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
+ GISTENTRY *ent = entryvec->vector;
+ data_type *out,
+ *tmp,
+ *old;
+ int numranges,
+ i = 0;
+
+ numranges = entryvec->n;
+ tmp = DatumGetDataType(ent[0].key);
+ out = tmp;
+
+ if (numranges == 1)
+ {
+ out = data_type_deep_copy(tmp);
+
+ PG_RETURN_DATA_TYPE_P(out);
+ }
+
+ for (i = 1; i < numranges; i++)
+ {
+ old = out;
+ tmp = DatumGetDataType(ent[i].key);
+ out = my_union_implementation(out, tmp);
+ }
+
+ PG_RETURN_DATA_TYPE_P(out);
+}
+
+
+ As you can see, in this skeleton we're dealing with a data type
+ where union(X, Y, Z) = union(union(X, Y), Z). It's easy
+ enough to support data types where this is not the case, by
+ implementing the proper union algorithm in this
+ GiST support method.
+
+ The result of the union function must be a value of the
+ index's storage type, whatever that is (it might or might not be
+ different from the indexed column's type). The union
+ function should return a pointer to newly palloc()ed
+ memory. You can't just return the input value as-is, even if there is
+ no type change.
+
+ As shown above, the union function's
+ first internal argument is actually
+ a GistEntryVector pointer. The second argument is a
+ pointer to an integer variable, which can be ignored. (It used to be
+ required that the union function store the size of its
+ result value into that variable, but this is no longer necessary.)
+
compress
+ Converts a data item into a format suitable for physical storage in
+ an index page.
+ If the compress method is omitted, data items are stored
+ in the index without modification.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_compress(internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_compress);
+
+Datum
+my_compress(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ GISTENTRY *retval;
+
+ if (entry->leafkey)
+ {
+ /* replace entry->key with a compressed version */
+ compressed_data_type *compressed_data = palloc(sizeof(compressed_data_type));
+
+ /* fill *compressed_data from entry->key ... */
+
+ retval = palloc(sizeof(GISTENTRY));
+ gistentryinit(*retval, PointerGetDatum(compressed_data),
+ entry->rel, entry->page, entry->offset, FALSE);
+ }
+ else
+ {
+ /* typically we needn't do anything with non-leaf entries */
+ retval = entry;
+ }
+
+ PG_RETURN_POINTER(retval);
+}
+
+
+ You have to adapt compressed_data_type to the specific
+ type you're converting to in order to compress your leaf nodes, of
+ course.
+
decompress
+ Converts the stored representation of a data item into a format that
+ can be manipulated by the other GiST methods in the operator class.
+ If the decompress method is omitted, it is assumed that
+ the other GiST methods can work directly on the stored data format.
+ (decompress is not necessarily the reverse of
+ the compress method; in particular,
+ if compress is lossy then it's impossible
+ for decompress to exactly reconstruct the original
+ data. decompress is not necessarily equivalent
+ to fetch, either, since the other GiST methods might not
+ require full reconstruction of the data.)
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_decompress(internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+
+ The above skeleton is suitable for the case where no decompression
+ is needed. (But, of course, omitting the method altogether is even
+ easier, and is recommended in such cases.)
+
penalty
+ Returns a value indicating the “cost” of inserting the new
+ entry into a particular branch of the tree. Items will be inserted
+ down the path of least penalty in the tree.
+ Values returned by penalty should be non-negative.
+ If a negative value is returned, it will be treated as zero.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_penalty(internal, internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT; -- in some cases penalty functions need not be strict
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+
+ For historical reasons, the penalty function doesn't
+ just return a float result; instead it has to store the value
+ at the location indicated by the third argument. The return
+ value per se is ignored, though it's conventional to pass back the
+ address of that argument.
+
+ The penalty function is crucial to good performance of
+ the index. It'll get used at insertion time to determine which branch
+ to follow when choosing where to add the new entry in the tree. At
+ query time, the more balanced the index, the quicker the lookup.
+
picksplit
+ When an index page split is necessary, this function decides which
+ entries on the page are to stay on the old page, and which are to move
+ to the new page.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_picksplit(internal, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_picksplit);
+
+Datum
+my_picksplit(PG_FUNCTION_ARGS)
+{
+ GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
+ GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
+ OffsetNumber maxoff = entryvec->n - 1;
+ GISTENTRY *ent = entryvec->vector;
+ int i,
+ nbytes;
+ OffsetNumber *left,
+ *right;
+ data_type *tmp_union;
+ data_type *unionL;
+ data_type *unionR;
+ GISTENTRY **raw_entryvec;
+
+ maxoff = entryvec->n - 1;
+ nbytes = (maxoff + 1) * sizeof(OffsetNumber);
+
+ v->spl_left = (OffsetNumber *) palloc(nbytes);
+ left = v->spl_left;
+ v->spl_nleft = 0;
+
+ v->spl_right = (OffsetNumber *) palloc(nbytes);
+ right = v->spl_right;
+ v->spl_nright = 0;
+
+ unionL = NULL;
+ unionR = NULL;
+
+ /* Initialize the raw entry vector. */
+ raw_entryvec = (GISTENTRY **) malloc(entryvec->n * sizeof(void *));
+ for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
+ raw_entryvec[i] = &(entryvec->vector[i]);
+
+ for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
+ {
+ int real_index = raw_entryvec[i] - entryvec->vector;
+
+ tmp_union = DatumGetDataType(entryvec->vector[real_index].key);
+ Assert(tmp_union != NULL);
+
+ /*
+ * Choose where to put the index entries and update unionL and unionR
+ * accordingly. Append the entries to either v->spl_left or
+ * v->spl_right, and care about the counters.
+ */
+
+ if (my_choice_is_left(unionL, curl, unionR, curr))
+ {
+ if (unionL == NULL)
+ unionL = tmp_union;
+ else
+ unionL = my_union_implementation(unionL, tmp_union);
+
+ *left = real_index;
+ ++left;
+ ++(v->spl_nleft);
+ }
+ else
+ {
+ /*
+ * Same on the right
+ */
+ }
+ }
+
+ v->spl_ldatum = DataTypeGetDatum(unionL);
+ v->spl_rdatum = DataTypeGetDatum(unionR);
+ PG_RETURN_POINTER(v);
+}
+
+
+ Notice that the picksplit function's result is delivered
+ by modifying the passed-in v structure. The return
+ value per se is ignored, though it's conventional to pass back the
+ address of v.
+
+ Like penalty, the picksplit function
+ is crucial to good performance of the index. Designing suitable
+ penalty and picksplit implementations
+ is where the challenge of implementing well-performing
+ GiST indexes lies.
+
same
+ Returns true if two index entries are identical, false otherwise.
+ (An “index entry” is a value of the index's storage type,
+ not necessarily the original indexed column's type.)
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_same(storage_type, storage_type, internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+
+ For historical reasons, the same function doesn't
+ just return a Boolean result; instead it has to store the flag
+ at the location indicated by the third argument. The return
+ value per se is ignored, though it's conventional to pass back the
+ address of that argument.
+
distance
+ Given an index entry p and a query value q,
+ this function determines the index entry's
+ “distance” from the query value. This function must be
+ supplied if the operator class contains any ordering operators.
+ A query using the ordering operator will be implemented by returning
+ index entries with the smallest “distance” values first,
+ so the results must be consistent with the operator's semantics.
+ For a leaf index entry the result just represents the distance to
+ the index entry; for an internal tree node, the result must be the
+ smallest distance that any child entry could have.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_distance(internal, data_type, smallint, oid, internal)
+RETURNS float8
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ And the matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_distance);
+
+Datum
+my_distance(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ data_type *query = PG_GETARG_DATA_TYPE_P(1);
+ StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
+ /* Oid subtype = PG_GETARG_OID(3); */
+ /* bool *recheck = (bool *) PG_GETARG_POINTER(4); */
+ data_type *key = DatumGetDataType(entry->key);
+ double retval;
+
+ /*
+ * determine return value as a function of strategy, key and query.
+ */
+
+ PG_RETURN_FLOAT8(retval);
+}
+
+
+ The arguments to the distance function are identical to
+ the arguments of the consistent function.
+
+ Some approximation is allowed when determining the distance, so long
+ as the result is never greater than the entry's actual distance. Thus,
+ for example, distance to a bounding box is usually sufficient in
+ geometric applications. For an internal tree node, the distance
+ returned must not be greater than the distance to any of the child
+ nodes. If the returned distance is not exact, the function must set
+ *recheck to true. (This is not necessary for internal tree
+ nodes; for them, the calculation is always assumed to be inexact.) In
+ this case the executor will calculate the accurate distance after
+ fetching the tuple from the heap, and reorder the tuples if necessary.
+
+ If the distance function returns *recheck = true for any
+ leaf node, the original ordering operator's return type must
+ be float8 or float4, and the distance function's
+ result values must be comparable to those of the original ordering
+ operator, since the executor will sort using both distance function
+ results and recalculated ordering-operator results. Otherwise, the
+ distance function's result values can be any finite float8
+ values, so long as the relative order of the result values matches the
+ order returned by the ordering operator. (Infinity and minus infinity
+ are used internally to handle cases such as nulls, so it is not
+ recommended that distance functions return these values.)
+
fetch
+ Converts the compressed index representation of a data item into the
+ original data type, for index-only scans. The returned data must be an
+ exact, non-lossy copy of the originally indexed value.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_fetch(internal)
+RETURNS internal
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ The argument is a pointer to a GISTENTRY struct. On
+ entry, its key field contains a non-NULL leaf datum in
+ compressed form. The return value is another GISTENTRY
+ struct, whose key field contains the same datum in its
+ original, uncompressed form. If the opclass's compress function does
+ nothing for leaf entries, the fetch method can return the
+ argument as-is. Or, if the opclass does not have a compress function,
+ the fetch method can be omitted as well, since it would
+ necessarily be a no-op.
+
+ The matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_fetch);
+
+Datum
+my_fetch(PG_FUNCTION_ARGS)
+{
+ GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
+ input_data_type *in = DatumGetPointer(entry->key);
+ fetched_data_type *fetched_data;
+ GISTENTRY *retval;
+
+ retval = palloc(sizeof(GISTENTRY));
+ fetched_data = palloc(sizeof(fetched_data_type));
+
+ /*
+ * Convert 'fetched_data' into the a Datum of the original datatype.
+ */
+
+ /* fill *retval from fetched_data. */
+ gistentryinit(*retval, PointerGetDatum(converted_datum),
+ entry->rel, entry->page, entry->offset, FALSE);
+
+ PG_RETURN_POINTER(retval);
+}
+
+
+ If the compress method is lossy for leaf entries, the operator class
+ cannot support index-only scans, and must not define
+ a fetch function.
+
options
+ Allows definition of user-visible parameters that control operator
+ class behavior.
+
+ The SQL declaration of the function must look like this:
+
+
+CREATE OR REPLACE FUNCTION my_options(internal)
+RETURNS void
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ The function is passed a pointer to a local_relopts
+ struct, which needs to be filled with a set of operator class
+ specific options. The options can be accessed from other support
+ functions using the PG_HAS_OPCLASS_OPTIONS() and
+ PG_GET_OPCLASS_OPTIONS() macros.
+
+ An example implementation of my_options() and parameters use
+ from other support functions are given below:
+
+
+typedef enum MyEnumType
+{
+ MY_ENUM_ON,
+ MY_ENUM_OFF,
+ MY_ENUM_AUTO
+} MyEnumType;
+
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int int_param; /* integer parameter */
+ double real_param; /* real parameter */
+ MyEnumType enum_param; /* enum parameter */
+ int str_param; /* string parameter */
+} MyOptionsStruct;
+
+/* String representation of enum values */
+static relopt_enum_elt_def myEnumValues[] =
+{
+ {"on", MY_ENUM_ON},
+ {"off", MY_ENUM_OFF},
+ {"auto", MY_ENUM_AUTO},
+ {(const char *) NULL} /* list terminator */
+};
+
+static char *str_param_default = "default";
+
+/*
+ * Sample validator: checks that string is not longer than 8 bytes.
+ */
+static void
+validate_my_string_relopt(const char *value)
+{
+ if (strlen(value) > 8)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("str_param must be at most 8 bytes")));
+}
+
+/*
+ * Sample filler: switches characters to lower case.
+ */
+static Size
+fill_my_string_relopt(const char *value, void *ptr)
+{
+ char *tmp = str_tolower(value, strlen(value), DEFAULT_COLLATION_OID);
+ int len = strlen(tmp);
+
+ if (ptr)
+ strcpy((char *) ptr, tmp);
+
+ pfree(tmp);
+ return len + 1;
+}
+
+PG_FUNCTION_INFO_V1(my_options);
+
+Datum
+my_options(PG_FUNCTION_ARGS)
+{
+ local_relopts *relopts = (local_relopts *) PG_GETARG_POINTER(0);
+
+ init_local_reloptions(relopts, sizeof(MyOptionsStruct));
+ add_local_int_reloption(relopts, "int_param", "integer parameter",
+ 100, 0, 1000000,
+ offsetof(MyOptionsStruct, int_param));
+ add_local_real_reloption(relopts, "real_param", "real parameter",
+ 1.0, 0.0, 1000000.0,
+ offsetof(MyOptionsStruct, real_param));
+ add_local_enum_reloption(relopts, "enum_param", "enum parameter",
+ myEnumValues, MY_ENUM_ON,
+ "Valid values are: \"on\", \"off\" and \"auto\".",
+ offsetof(MyOptionsStruct, enum_param));
+ add_local_string_reloption(relopts, "str_param", "string parameter",
+ str_param_default,
+ &validate_my_string_relopt,
+ &fill_my_string_relopt,
+ offsetof(MyOptionsStruct, str_param));
+
+ PG_RETURN_VOID();
+}
+
+PG_FUNCTION_INFO_V1(my_compress);
+
+Datum
+my_compress(PG_FUNCTION_ARGS)
+{
+ int int_param = 100;
+ double real_param = 1.0;
+ MyEnumType enum_param = MY_ENUM_ON;
+ char *str_param = str_param_default;
+
+ /*
+ * Normally, when opclass contains 'options' method, then options are always
+ * passed to support functions. However, if you add 'options' method to
+ * existing opclass, previously defined indexes have no options, so the
+ * check is required.
+ */
+ if (PG_HAS_OPCLASS_OPTIONS())
+ {
+ MyOptionsStruct *options = (MyOptionsStruct *) PG_GET_OPCLASS_OPTIONS();
+
+ int_param = options->int_param;
+ real_param = options->real_param;
+ enum_param = options->enum_param;
+ str_param = GET_STRING_RELOPTION(options, str_param);
+ }
+
+ /* the rest implementation of support function */
+}
+
+
+
+ Since the representation of the key in GiST is
+ flexible, it may depend on user-specified parameters. For instance,
+ the length of key signature may be specified. See
+ gtsvector_options() for example.
+
sortsupport
+ Returns a comparator function to sort data in a way that preserves
+ locality. It is used by CREATE INDEX and
+ REINDEX commands. The quality of the created index
+ depends on how well the sort order determined by the comparator function
+ preserves locality of the inputs.
+
+ The sortsupport method is optional. If it is not
+ provided, CREATE INDEX builds the index by inserting
+ each tuple to the tree using the penalty and
+ picksplit functions, which is much slower.
+
+ The SQL declaration of the function must look like
+ this:
+
+
+CREATE OR REPLACE FUNCTION my_sortsupport(internal)
+RETURNS void
+AS 'MODULE_PATHNAME'
+LANGUAGE C STRICT;
+
+
+ The argument is a pointer to a SortSupport
+ struct. At a minimum, the function must fill in its comparator field.
+ The comparator takes three arguments: two Datums to compare, and
+ a pointer to the SortSupport struct. The
+ Datums are the two indexed values in the format that they are stored
+ in the index; that is, in the format returned by the
+ compress method. The full API is defined in
+ src/include/utils/sortsupport.h.
+
+ The matching code in the C module could then follow this skeleton:
+
+
+PG_FUNCTION_INFO_V1(my_sortsupport);
+
+static int
+my_fastcmp(Datum x, Datum y, SortSupport ssup)
+{
+ /* establish order between x and y by computing some sorting value z */
+
+ int z1 = ComputeSpatialCode(x);
+ int z2 = ComputeSpatialCode(y);
+
+ return z1 == z2 ? 0 : z1 > z2 ? 1 : -1;
+}
+
+Datum
+my_sortsupport(PG_FUNCTION_ARGS)
+{
+ SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
+
+ ssup->comparator = my_fastcmp;
+ PG_RETURN_VOID();
+}
+
+
+ All the GiST support methods are normally called in short-lived memory
+ contexts; that is, CurrentMemoryContext will get reset after
+ each tuple is processed. It is therefore not very important to worry about
+ pfree'ing everything you palloc. However, in some cases it's useful for a
+ support method to cache data across repeated calls. To do that, allocate
+ the longer-lived data in fcinfo->flinfo->fn_mcxt, and
+ keep a pointer to it in fcinfo->flinfo->fn_extra. Such
+ data will survive for the life of the index operation (e.g., a single GiST
+ index scan, index build, or index tuple insertion). Be careful to pfree
+ the previous value when replacing a fn_extra value, or the leak
+ will accumulate for the duration of the operation.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gist-implementation.html b/pgsql/doc/postgresql/html/gist-implementation.html
new file mode 100644
index 0000000000000000000000000000000000000000..51265458670285f688714783889908aa3d9453de
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gist-implementation.html
@@ -0,0 +1,38 @@
+
+68.4. Implementation
+ The simplest way to build a GiST index is just to insert all the entries,
+ one by one. This tends to be slow for large indexes, because if the
+ index tuples are scattered across the index and the index is large enough
+ to not fit in cache, a lot of random I/O will be
+ needed. PostgreSQL supports two alternative
+ methods for initial build of a GiST index: sorted
+ and buffered modes.
+
+ The sorted method is only available if each of the opclasses used by the
+ index provides a sortsupport function, as described
+ in Section 68.3. If they do, this method is
+ usually the best, so it is used by default.
+
+ The buffered method works by not inserting tuples directly into the index
+ right away. It can dramatically reduce the amount of random I/O needed
+ for non-ordered data sets. For well-ordered data sets the benefit is
+ smaller or non-existent, because only a small number of pages receive new
+ tuples at a time, and those pages fit in cache even if the index as a
+ whole does not.
+
+ The buffered method needs to call the penalty
+ function more often than the simple method does, which consumes some
+ extra CPU resources. Also, the buffers need temporary disk space, up to
+ the size of the resulting index. Buffering can also influence the quality
+ of the resulting index, in both positive and negative directions. That
+ influence depends on various factors, like the distribution of the input
+ data and the operator class implementation.
+
+ If sorting is not possible, then by default a GiST index build switches
+ to the buffering method when the index size reaches
+ effective_cache_size. Buffering can be manually
+ forced or prevented by the buffering parameter to the
+ CREATE INDEX command. The default behavior is good for most cases, but
+ turning buffering off might speed up the build somewhat if the input data
+ is ordered.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gist-intro.html b/pgsql/doc/postgresql/html/gist-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..6610e94d452e8480a9c9f059bc316c04d7a4e2ca
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gist-intro.html
@@ -0,0 +1,23 @@
+
+68.1. Introduction
+ GiST stands for Generalized Search Tree. It is a
+ balanced, tree-structured access method, that acts as a base template in
+ which to implement arbitrary indexing schemes. B-trees, R-trees and many
+ other indexing schemes can be implemented in GiST.
+
+ One advantage of GiST is that it allows the development
+ of custom data types with the appropriate access methods, by
+ an expert in the domain of the data type, rather than a database expert.
+
+ Some of the information here is derived from the University of California
+ at Berkeley's GiST Indexing Project
+ web site and
+ Marcel Kornacker's thesis,
+
+ Access Methods for Next-Generation Database Systems.
+ The GiST
+ implementation in PostgreSQL is primarily
+ maintained by Teodor Sigaev and Oleg Bartunov, and there is more
+ information on their
+ web site.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gist.html b/pgsql/doc/postgresql/html/gist.html
new file mode 100644
index 0000000000000000000000000000000000000000..02c99ae228728ca98d25c6b60b6a9ba3f8f6e087
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gist.html
@@ -0,0 +1,2 @@
+
+Chapter 68. GiST Indexes
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/git.html b/pgsql/doc/postgresql/html/git.html
new file mode 100644
index 0000000000000000000000000000000000000000..d4af5b533b1bac93714a1a62f99f147ecc679bb1
--- /dev/null
+++ b/pgsql/doc/postgresql/html/git.html
@@ -0,0 +1,42 @@
+
+I.1. Getting the Source via Git
+ With Git you will make a copy of the entire code repository
+ on your local machine, so you will have access to all history and branches
+ offline. This is the fastest and most flexible way to develop or test
+ patches.
+
Git
+ You will need an installed version of Git, which you can
+ get from https://git-scm.com. Many systems already
+ have a recent version of Git installed by default, or
+ available in their package distribution system.
+
+ To begin using the Git repository, make a clone of the official mirror:
+
+
+
+ This will copy the full repository to your local machine, so it may take
+ a while to complete, especially if you have a slow Internet connection.
+ The files will be placed in a new subdirectory postgresql of
+ your current directory.
+
+ The Git mirror can also be reached via the Git protocol. Just change the URL
+ prefix to git, as in:
+
+
+ Whenever you want to get the latest updates in the system, cd
+ into the repository, and run:
+
+
+git fetch
+
+
+ Git can do a lot more things than just fetch the source. For
+ more information, consult the Git man pages, or see the
+ website at https://git-scm.com.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/glossary.html b/pgsql/doc/postgresql/html/glossary.html
new file mode 100644
index 0000000000000000000000000000000000000000..04a478df13d3b8a22d64678aacc01ec96013df9a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/glossary.html
@@ -0,0 +1,1134 @@
+
+Appendix M. Glossary
+ This is a list of terms and their meaning in the context of
+ PostgreSQL and relational database
+ systems in general.
+
ACID
+ Atomicity,
+ Consistency,
+ Isolation, and
+ Durability.
+ This set of properties of database transactions is intended to
+ guarantee validity in concurrent operation and even in event of
+ errors, power failures, etc.
+
Aggregate function (routine)
+ A function that
+ combines (aggregates) multiple input values,
+ for example by counting, averaging or adding,
+ yielding a single output value.
+
+ The act of collecting statistics from data in
+ tables
+ and other relations
+ to help the query planner
+ to make decisions about how to execute
+ queries.
+
+ (Don't confuse this term with the ANALYZE option
+ to the EXPLAIN command.)
+
+ The property of a transaction
+ that either all its operations complete as a single unit or none do.
+ In addition, if a system failure occurs during the execution of a
+ transaction, no partial results are visible after recovery.
+ This is one of the ACID properties.
+
Attribute
+ An element with a certain name and data type found within a
+ tuple.
+
Autovacuum (process)
+ A set of background processes that routinely perform
+ vacuum
+ and analyze operations.
+ The auxiliary process
+ that coordinates the work and is always present (unless autovacuum
+ is disabled) is known as the autovacuum launcher,
+ and the processes that carry out the tasks are known as the
+ autovacuum workers.
+
+ Process within an instance,
+ which runs system- or user-supplied code.
+ Serves as infrastructure for several features in
+ PostgreSQL, such as
+ logical replication
+ and parallel queries.
+ In addition, Extensions can add
+ custom background worker processes.
+
+ An auxiliary process
+ that writes dirty
+ data pages from
+ shared memory to
+ the file system. It wakes up periodically, but works only for a short
+ period in order to distribute its expensive I/O
+ activity over time to avoid generating larger
+ I/O peaks which could block other processes.
+
+ A binary copy of all
+ database cluster
+ files. It is generated by the tool pg_basebackup.
+ In combination with WAL files it can be used as the starting point
+ for recovery, log shipping, or streaming replication.
+
Bloat
+ Space in data pages which does not contain current row versions,
+ such as unused (free) space or outdated row versions.
+
+ This user owns all system catalog tables in each database. It is also the role
+ from which all granted permissions originate. Because of these things, this
+ role may not be dropped.
+
+ Some operations will access a large number of
+ pages. A
+ Buffer Access Strategy helps to prevent these
+ operations from evicting too many pages from
+ shared buffers.
+
+ A Buffer Access Strategy sets up references to a limited number of
+ shared buffers and
+ reuses them circularly. When the operation requires a new page, a victim
+ buffer is chosen from the buffers in the strategy ring, which may require
+ flushing the page's dirty data and possibly also unflushed
+ WAL to permanent storage.
+
+ Buffer Access Strategies are used for various operations such as
+ sequential scans of large tables, VACUUM,
+ COPY, CREATE TABLE AS SELECT,
+ ALTER TABLE, CREATE DATABASE,
+ CREATE INDEX, and CLUSTER.
+
Cast
+ A conversion of a datum
+ from its current data type to another data type.
+
+ A type of constraint
+ defined on a relation
+ which restricts the values allowed in one or more
+ attributes. The
+ check constraint can make reference to any attribute of the same row in
+ the relation, but cannot reference other rows of the same relation or
+ other relations.
+
+ A point in the WAL sequence
+ at which it is guaranteed that the heap and index data files have been
+ updated with all information from
+ shared memory
+ modified before that checkpoint;
+ a checkpoint record is written and flushed to WAL
+ to mark that point.
+
+ A checkpoint is also the act of carrying out all the actions that
+ are necessary to reach a checkpoint as defined above.
+ This process is initiated when predefined conditions are met,
+ such as a specified amount of time has passed, or a certain volume
+ of records has been written; or it can be invoked by the user
+ with the command CHECKPOINT.
+
+ The operating system user that owns the
+ data directory
+ and under which the postgres process is run.
+ It is required that this user exist prior to creating a new
+ database cluster.
+
+ On operating systems with a root user,
+ said user is not allowed to be the cluster owner.
+
+ The concept that multiple independent operations happen within the
+ database at the same time.
+ In PostgreSQL, concurrency is controlled by
+ the multiversion concurrency control
+ mechanism.
+
Connection
+ An established line of communication between a client process and a
+ backend process,
+ usually over a network, supporting a
+ session. This term is
+ sometimes used as a synonym for session.
+
+ The property that the data in the
+ database
+ is always in compliance with
+ integrity constraints.
+ Transactions may be allowed to violate some of the constraints
+ transiently before it commits, but if such violations are not resolved
+ by the time it commits, such a transaction is automatically
+ rolled back.
+ This is one of the ACID properties.
+
Constraint
+ A restriction on the values of data allowed within a
+ table,
+ or in attributes of a
+ domain.
+
+ A collection of databases and global SQL objects,
+ and their common static and dynamic metadata.
+ Sometimes referred to as a
+ cluster.
+ A database cluster is created using the
+ initdb program.
+
+ In PostgreSQL, the term
+ cluster is also sometimes used to refer to an instance.
+ (Don't confuse this term with the SQL command CLUSTER.)
+
+ See also cluster owner,
+ the operating-system owner of a cluster,
+ and bootstrap superuser,
+ the PostgreSQL owner of a cluster.
+
+ A role having superuser status
+ (see Section 22.2).
+
+ Frequently referred to as superuser.
+
Data directory
+ The base directory on the file system of a
+ server that contains all
+ data files and subdirectories associated with a
+ database cluster
+ (with the exception of
+ tablespaces,
+ and optionally WAL).
+ The environment variable PGDATA is commonly used to
+ refer to the data directory.
+
+ A cluster's storage
+ space comprises the data directory plus any additional tablespaces.
+
+ The basic structure used to store relation data.
+ All pages are of the same size.
+ Data pages are typically stored on disk, each in a specific file,
+ and can be read to shared buffers
+ where they can be modified, becoming
+ dirty. They become clean when written
+ to disk. New pages, which initially exist in memory only, are also
+ dirty until written.
+
Datum
+ The internal representation of one value of an SQL
+ data type.
+
Delete
+ An SQL command which removes
+ rows from a given
+ table
+ or relation.
+
+ A user-defined data type that is based on another underlying data type.
+ It acts the same as the underlying type except for possibly restricting
+ the set of allowed values.
+
+ The assurance that once a
+ transaction has
+ been committed, the
+ changes remain even after a system failure or crash.
+ This is one of the ACID properties.
+
+ A physical file which stores data for a given
+ relation.
+ File segments are limited in size by a configuration value
+ (typically 1 gigabyte),
+ so if a relation exceeds that size, it is split into multiple segments.
+
+ (Don't confuse this term with the similar term
+ WAL segment).
+
Foreign data wrapper
+ A means of representing data that is not contained in the local
+ database so that it appears as if were in local
+ table(s). With a foreign data wrapper it is
+ possible to define a foreign server and
+ foreign tables.
+
+ A type of constraint
+ defined on one or more columns
+ in a table which
+ requires the value(s) in those columns to
+ identify zero or one row
+ in another (or, infrequently, the same)
+ table.
+
Foreign server
+ A named collection of
+ foreign tables which
+ all use the same
+ foreign data wrapper
+ and have other configuration values in common.
+
+ Each of the separate segmented file sets in which a relation is stored.
+ The main fork is where the actual data resides.
+ There also exist two secondary forks for metadata:
+ the free space map
+ and the visibility map.
+ Unlogged relations
+ also have an init fork.
+
Free space map (fork)
+ A storage structure that keeps metadata about each data page of a table's
+ main fork. The free space map entry for each page stores the
+ amount of free space that's available for future tuples, and is structured
+ to be efficiently searched for available space for a new tuple of a given
+ size.
+
+ A type of routine that receives zero or more arguments, returns zero or more
+ output values, and is constrained to run within one transaction.
+ Functions are invoked as part of a query, for example via
+ SELECT.
+ Certain functions can return
+ sets; those are
+ called set-returning functions.
+
+ Functions can also be used for
+ triggers to invoke.
+
+ Contains the values of row
+ attributes (i.e., the data) for a
+ relation.
+ The heap is realized within one or more
+ file segments
+ in the relation's main fork.
+
Host
+ A computer that communicates with other computers over a network.
+ This is sometimes used as a synonym for
+ server.
+ It is also used to refer to a computer where
+ client processes run.
+
Index (relation)
+ A relation that contains
+ data derived from a table
+ or materialized view.
+ Its internal structure supports fast retrieval of and access to the original
+ data.
+
+ A group of backend and
+ auxiliary processes
+ that communicate using a common shared memory area. One
+ postmaster process
+ manages the instance; one instance manages exactly one
+ database cluster
+ with all its databases. Many instances can run on the same
+ server
+ as long as their TCP ports do not conflict.
+
+ The instance handles all key features of a DBMS:
+ read and write access to files and shared memory,
+ assurance of the ACID properties,
+ connections to
+ client processes,
+ privilege verification, crash recovery, replication, etc.
+
Isolation
+ The property that the effects of a transaction are not visible to
+ concurrent transactions
+ before it commits.
+ This is one of the ACID properties.
+
+ A table is considered
+ logged if changes to it are sent to the
+ WAL. By default, all regular
+ tables are logged. A table can be specified as
+ unlogged either at
+ creation time or via the ALTER TABLE command.
+
Logger (process)
+ An auxiliary process
+ which, if enabled, writes information about database events into the current
+ log file.
+ When reaching certain time- or
+ volume-dependent criteria, a new log file is created.
+ Also called syslogger.
+
+ The property that some information has been pre-computed and stored
+ for later use, rather than computing it on-the-fly.
+
+ This term is used in
+ materialized view,
+ to mean that the data derived from the view's query is stored on
+ disk separately from the sources of that data.
+
+ This term is also used to refer to some multi-step queries to mean that
+ the data resulting from executing a given step is stored in memory
+ (with the possibility of spilling to disk), so that it can be read multiple
+ times by another step.
+
Materialized view (relation)
+ A relation that is
+ defined by a SELECT statement
+ (just like a view),
+ but stores data in the same way that a
+ table does. It cannot be
+ modified via INSERT, UPDATE,
+ DELETE, or MERGE operations.
+
+ A mechanism designed to allow several
+ transactions to be
+ reading and writing the same rows without one process causing other
+ processes to stall.
+ In PostgreSQL, MVCC is implemented by
+ creating copies (versions) of
+ tuples as they are
+ modified; after transactions that can see the old versions terminate,
+ those old versions need to be removed.
+
Null
+ A concept of non-existence that is a central tenet of relational
+ database theory. It represents the absence of a definite value.
+
+ The ability to handle parts of executing a
+ query to take advantage
+ of parallel processes on servers with multiple CPUs.
+
Partition
+ One of several disjoint (not overlapping) subsets of a larger set.
+
+ In reference to a
+ partitioned table:
+ One of the tables that each contain part of the data of the partitioned table,
+ which is said to be the parent.
+ The partition is itself a table, so it can also be queried directly;
+ at the same time, a partition can sometimes be a partitioned table,
+ allowing hierarchies to be created.
+
+ In reference to a window function
+ in a query,
+ a partition is a user-defined criterion that identifies which neighboring
+ rows
+ of the query's result set
+ can be considered by the function.
+
Partitioned table (relation)
+ A relation that is
+ in semantic terms the same as a table,
+ but whose storage is distributed across several
+ partitions.
+
+ A special case of a
+ unique constraint
+ defined on a
+ table or other
+ relation that also
+ guarantees that all of the
+ attributes
+ within the primary key
+ do not have null values.
+ As the name implies, there can be only one
+ primary key per table, though it is possible to have multiple unique
+ constraints that also have no null-capable attributes.
+
Primary (server)
+ When two or more databases
+ are linked via replication,
+ the server
+ that is considered the authoritative source of information is called
+ the primary,
+ also known as a master.
+
Procedure (routine)
+ A type of routine.
+ Their distinctive qualities are that they do not return values,
+ and that they are allowed to make transactional statements such
+ as COMMIT and ROLLBACK.
+ They are invoked via the CALL command.
+
+ A request sent by a client to a backend,
+ usually to return results or to modify data on the database.
+
Query planner
+ The part of PostgreSQL that is devoted to
+ determining (planning) the most efficient way to
+ execute queries.
+ Also known as query optimizer,
+ optimizer, or simply planner.
+
+ More generically, a relation is a set of tuples; for example,
+ the result of a query is also a relation.
+
+ In PostgreSQL,
+ Class is an archaic synonym for
+ relation.
+
Replica (server)
+ A database that is paired
+ with a primary
+ database and is maintaining a copy of some or all of the primary database's
+ data. The foremost reasons for doing this are to allow for greater access
+ to that data, and to maintain availability of the data in the event that
+ the primary
+ becomes unavailable.
+
Replication
+ The act of reproducing data on one
+ server onto another
+ server called a replica.
+ This can take the form of physical replication,
+ where all file changes from one server are copied verbatim,
+ or logical replication where a defined subset
+ of data changes are conveyed using a higher-level representation.
+
+ A relation transmitted
+ from a backend process
+ to a client upon the
+ completion of an SQL command, usually a
+ SELECT but it can be an
+ INSERT, UPDATE, or
+ DELETE command if the RETURNING
+ clause is specified.
+
+ The fact that a result set is a relation means that a query can be used
+ in the definition of another query, becoming a
+ subquery.
+
+
Revoke
+ A command to prevent access to a named set of
+ database objects for a
+ named list of roles.
+
+ A collection of access privileges to the
+ instance.
+ Roles are themselves a privilege that can be granted to other roles.
+ This is often done for convenience or to ensure completeness
+ when multiple users need
+ the same privileges.
+
+ A defined set of instructions stored in the database system
+ that can be invoked for execution.
+ A routine can be written in a variety of programming
+ languages. Routines can be
+ functions
+ (including set-returning functions and
+ trigger functions),
+ aggregate functions,
+ and procedures.
+
+ Many routines are already defined within PostgreSQL
+ itself, but user-defined ones can also be added.
+
+ A special mark in the sequence of steps in a
+ transaction.
+ Data modifications after this point in time may be reverted
+ to the time of the savepoint.
+
+ A schema is a namespace for
+ SQL objects,
+ which all reside in the same
+ database.
+ Each SQL object must reside in exactly one schema.
+
+ All system-defined SQL objects reside in schema pg_catalog.
+
+ More generically, the term schema is used to mean
+ all data descriptions (table definitions,
+ constraints, comments, etc.)
+ for a given database or
+ subset thereof.
+
+ The SQL command used to request data from a
+ database.
+ Normally, SELECT commands are not expected to modify the
+ database in any way,
+ but it is possible that
+ functions invoked within
+ the query could have side effects that do modify data.
+
+ A type of relation that is used to generate values.
+ Typically the generated values are sequential non-repeating numbers.
+ They are commonly used to generate surrogate
+ primary key
+ values.
+
Server
+ A computer on which PostgreSQL
+ instances run.
+ The term server denotes real hardware, a
+ container, or a virtual machine.
+
+ This term is sometimes used to refer to an instance or to a host.
+
Session
+ A state that allows a client and a backend to interact,
+ communicating over a connection.
+
Shared memory
+ RAM which is used by the processes common to an
+ instance.
+ It mirrors parts of database
+ files, provides a transient area for
+ WAL records,
+ and stores additional common information.
+ Note that shared memory belongs to the complete instance, not to a single
+ database.
+
+ The largest part of shared memory is known as shared buffers
+ and is used to mirror part of data files, organized into pages.
+ When a page is modified, it is called a dirty page until it is
+ written back to the file system.
+
+ Any object that can be created with a CREATE
+ command. Most objects are specific to one database, and are commonly
+ known as local objects.
+
+ Most local objects reside in a specific
+ schema in their
+ containing database, such as
+ relations (all types),
+ routines (all types),
+ data types, etc.
+ The names of such objects of the same type in the same schema
+ are enforced to be unique.
+
+ There also exist local objects that do not reside in schemas; some examples are
+ extensions,
+ data type casts, and
+ foreign data wrappers.
+ The names of such objects of the same type are enforced to be unique
+ within the database.
+
+ Other object types, such as
+ roles,
+ tablespaces,
+ replication origins, subscriptions for logical replication, and
+ databases themselves are not local SQL objects since they exist
+ entirely outside of any specific database;
+ they are called global objects.
+ The names of such objects are enforced to be unique within the whole
+ database cluster.
+
+ (The name is historical: the startup process was named before
+ replication was implemented; the name refers to its task as it
+ relates to the server startup following a crash.)
+
Superuser
+ As used in this documentation, it is a synonym for
+ database superuser.
+
System catalog
+ A collection of tables
+ which describe the structure of all
+ SQL objects
+ of the instance.
+ The system catalog resides in the schema pg_catalog.
+ These tables contain data in internal representation and are
+ not typically considered useful for user examination;
+ a number of user-friendlier views,
+ also in schema pg_catalog, offer more convenient access to
+ some of that information, while additional tables and views
+ exist in schema information_schema
+ (see Chapter 37) that expose some
+ of the same and additional information as mandated by the
+ SQL standard.
+
+ A collection of tuples having
+ a common data structure (the same number of
+ attributes, in the same
+ order, having the same name and type per position).
+ A table is the most common form of
+ relation in
+ PostgreSQL.
+
+ A named location on the server file system.
+ All SQL objects
+ which require storage beyond their definition in the
+ system catalog
+ must belong to a single tablespace.
+ Initially, a database cluster contains a single usable tablespace which is
+ used as the default for all SQL objects, called pg_default.
+
+ Tables that exist either
+ for the lifetime of a
+ session or a
+ transaction, as
+ specified at the time of creation.
+ The data in them is not visible to other sessions, and is not
+ logged.
+ Temporary tables are often used to store intermediate data for a
+ multi-step operation.
+
+ A mechanism by which large attributes of table rows are split and
+ stored in a secondary table, called the TOAST table.
+ Each relation with large attributes has its own TOAST table.
+
+ A combination of commands that must act as a single
+ atomic command: they all
+ succeed or all fail as a single unit, and their effects are not visible to
+ other sessions until
+ the transaction is complete, and possibly even later, depending on the
+ isolation level.
+
+ The numerical, unique, sequentially-assigned identifier that each
+ transaction receives when it first causes a database modification.
+ Frequently abbreviated as xid.
+ When stored on disk, xids are only 32-bits wide, so only
+ approximately four billion write transaction IDs can be generated;
+ to permit the system to run for longer than that,
+ epochs are used, also 32 bits wide.
+ When the counter reaches the maximum xid value, it starts over at
+ 3 (values under that are reserved) and the
+ epoch value is incremented by one.
+ In some contexts, the epoch and xid values are
+ considered together as a single 64-bit value; see Section 74.1 for more details.
+
+ Average number of transactions that are executed per second,
+ totaled across all sessions active for a measured run.
+ This is used as a measure of the performance characteristics of
+ an instance.
+
Trigger
+ A function which can
+ be defined to execute whenever a certain operation (INSERT,
+ UPDATE, DELETE,
+ TRUNCATE) is applied to a
+ relation.
+ A trigger executes within the same
+ transaction as the
+ statement which invoked it, and if the function fails, then the invoking
+ statement also fails.
+
+ A collection of attributes
+ in a fixed order.
+ That order may be defined by the table
+ (or other relation)
+ where the tuple is contained, in which case the tuple is often called a
+ row. It may also be defined by the structure of a
+ result set, in which case it is sometimes called a record.
+
Unique constraint
+ A type of constraint
+ defined on a relation
+ which restricts the values allowed in one or a combination of columns
+ so that each value or combination of values can only appear once in the
+ relation — that is, no other row in the relation contains values
+ that are equal to those.
+
+ Because null values are
+ not considered equal to each other, multiple rows with null values are
+ allowed to exist without violating the unique constraint.
+
Unlogged
+ The property of certain relations
+ that the changes to them are not reflected in the
+ WAL.
+ This disables replication and crash recovery for these relations.
+
+ The primary use of unlogged tables is for storing
+ transient work data that must be shared across processes.
+
+ The process of removing outdated
+ tuple versions
+ from tables or materialized views, and other closely related
+ processing required by PostgreSQL's
+ implementation of MVCC.
+ This can be initiated through the use of
+ the VACUUM command, but can also be handled automatically
+ via autovacuum processes.
+
+ A relation that is defined by a
+ SELECT statement, but has no storage of its own.
+ Any time a query references a view, the definition of the view is
+ substituted into the query as if the user had typed it as a subquery
+ instead of the name of the view.
+
+ A storage structure that keeps metadata about each data page
+ of a table's main fork. The visibility map entry for
+ each page stores two bits: the first one
+ (all-visible) indicates that all tuples
+ in the page are visible to all transactions. The second one
+ (all-frozen) indicates that all tuples
+ in the page are marked frozen.
+
+ Also known as WAL segment or
+ WAL segment file.
+ Each of the sequentially-numbered files that provide storage space for
+ WAL.
+ The files are all of the same predefined size
+ and are written in sequential order, interspersing changes
+ as they occur in multiple simultaneous sessions.
+ If the system crashes, the files are read in order, and each of the
+ changes is replayed to restore the system to the state it was in
+ before the crash.
+
+ Each WAL file can be released after a
+ checkpoint
+ writes all the changes in it to the corresponding data files.
+ Releasing the file can be done either by deleting it, or by changing its
+ name so that it will be used in the future, which is called
+ recycling.
+
+ A low-level description of an individual data change.
+ It contains sufficient information for the data change to be
+ re-executed (replayed) in case a system failure
+ causes the change to be lost.
+ WAL records use a non-printable binary format.
+
+ A special backend process
+ that streams WAL over a network. The receiving end can be a
+ WAL receiver
+ in a replica,
+ pg_receivewal, or any other client program
+ that speaks the replication protocol.
+
+ A type of function
+ used in a query
+ that applies to a partition
+ of the query's result set;
+ the function's result is based on values found in
+ rows of the same partition or frame.
+
+ All aggregate functions
+ can be used as window functions, but window functions can also be
+ used to, for example, give ranks to each of the rows in the partition.
+ Also known as analytic functions.
+
+ The journal that keeps track of the changes in the
+ database cluster
+ as user- and system-invoked operations take place.
+ It comprises many individual
+ WAL records written
+ sequentially to WAL files.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gssapi-auth.html b/pgsql/doc/postgresql/html/gssapi-auth.html
new file mode 100644
index 0000000000000000000000000000000000000000..04a76d599be09ae22857d93abc2a46d55d12c173
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gssapi-auth.html
@@ -0,0 +1,118 @@
+
+21.6. GSSAPI Authentication
+ GSSAPI is an industry-standard protocol
+ for secure authentication defined in
+ RFC 2743.
+ PostgreSQL
+ supports GSSAPI for authentication,
+ communications encryption, or both.
+ GSSAPI provides automatic authentication
+ (single sign-on) for systems that support it. The authentication itself is
+ secure. If GSSAPI encryption
+ or SSL encryption is
+ used, the data sent along the database connection will be encrypted;
+ otherwise, it will not.
+
+ GSSAPI support has to be enabled when PostgreSQL is built;
+ see Chapter 17 for more information.
+
+ When GSSAPI uses
+ Kerberos, it uses a standard service
+ principal (authentication identity) name in the format
+ servicename/hostname@realm.
+ The principal name used by a particular installation is not encoded in
+ the PostgreSQL server in any way; rather it
+ is specified in the keytab file that the server
+ reads to determine its identity. If multiple principals are listed in
+ the keytab file, the server will accept any one of them.
+ The server's realm name is the preferred realm specified in the Kerberos
+ configuration file(s) accessible to the server.
+
+ When connecting, the client must know the principal name of the server
+ it intends to connect to. The servicename
+ part of the principal is ordinarily postgres,
+ but another value can be selected via libpq's
+ krbsrvname connection parameter.
+ The hostname part is the fully qualified
+ host name that libpq is told to connect to.
+ The realm name is the preferred realm specified in the Kerberos
+ configuration file(s) accessible to the client.
+
+ The client will also have a principal name for its own identity
+ (and it must have a valid ticket for this principal). To
+ use GSSAPI for authentication, the client
+ principal must be associated with
+ a PostgreSQL database user name.
+ The pg_ident.conf configuration file can be used
+ to map principals to user names; for example,
+ pgusername@realm could be mapped to just pgusername.
+ Alternatively, you can use the full username@realm principal as
+ the role name in PostgreSQL without any mapping.
+
+ PostgreSQL also supports mapping
+ client principals to user names by just stripping the realm from
+ the principal. This method is supported for backwards compatibility and is
+ strongly discouraged as it is then impossible to distinguish different users
+ with the same user name but coming from different realms. To enable this,
+ set include_realm to 0. For simple single-realm
+ installations, doing that combined with setting the
+ krb_realm parameter (which checks that the principal's realm
+ matches exactly what is in the krb_realm parameter)
+ is still secure; but this is a
+ less capable approach compared to specifying an explicit mapping in
+ pg_ident.conf.
+
+ The location of the server's keytab file is specified by the krb_server_keyfile configuration parameter.
+ For security reasons, it is recommended to use a separate keytab
+ just for the PostgreSQL server rather
+ than allowing the server to read the system keytab file.
+ Make sure that your server keytab file is readable (and preferably
+ only readable, not writable) by the PostgreSQL
+ server account. (See also Section 19.1.)
+
+ The keytab file is generated using the Kerberos software; see the
+ Kerberos documentation for details. The following example shows
+ doing this using the kadmin tool of
+ MIT Kerberos:
+
+ The following authentication options are supported for
+ the GSSAPI authentication method:
+
include_realm
+ If set to 0, the realm name from the authenticated user principal is
+ stripped off before being passed through the user name mapping
+ (Section 21.2). This is discouraged and is
+ primarily available for backwards compatibility, as it is not secure
+ in multi-realm environments unless krb_realm is
+ also used. It is recommended to
+ leave include_realm set to the default (1) and to
+ provide an explicit mapping in pg_ident.conf to convert
+ principal names to PostgreSQL user names.
+
map
+ Allows mapping from client principals to database user names. See
+ Section 21.2 for details. For a GSSAPI/Kerberos
+ principal, such as username@EXAMPLE.COM (or, less
+ commonly, username/hostbased@EXAMPLE.COM), the
+ user name used for mapping is
+ username@EXAMPLE.COM (or
+ username/hostbased@EXAMPLE.COM, respectively),
+ unless include_realm has been set to 0, in which case
+ username (or username/hostbased)
+ is what is seen as the system user name when mapping.
+
krb_realm
+ Sets the realm to match user principal names against. If this parameter
+ is set, only users of that realm will be accepted. If it is not set,
+ users of any realm can connect, subject to whatever user name mapping
+ is done.
+
+
+ In addition to these settings, which can be different for
+ different pg_hba.conf entries, there is the
+ server-wide krb_caseins_users configuration
+ parameter. If that is set to true, client principals are matched to
+ user map entries case-insensitively. krb_realm, if
+ set, is also matched case-insensitively.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/gssapi-enc.html b/pgsql/doc/postgresql/html/gssapi-enc.html
new file mode 100644
index 0000000000000000000000000000000000000000..3c5b4c4c4a95a5b473119ff1f5122c0740e058be
--- /dev/null
+++ b/pgsql/doc/postgresql/html/gssapi-enc.html
@@ -0,0 +1,31 @@
+
+19.10. Secure TCP/IP Connections with GSSAPI Encryption
19.10. Secure TCP/IP Connections with GSSAPI Encryption
+ PostgreSQL also has native support for
+ using GSSAPI to encrypt client/server communications for
+ increased security. Support requires that a GSSAPI
+ implementation (such as MIT Kerberos) is installed on both client and server
+ systems, and that support in PostgreSQL is
+ enabled at build time (see Chapter 17).
+
+ The PostgreSQL server will listen for both
+ normal and GSSAPI-encrypted connections on the same TCP
+ port, and will negotiate with any connecting client whether to
+ use GSSAPI for encryption (and for authentication). By
+ default, this decision is up to the client (which means it can be
+ downgraded by an attacker); see Section 21.1 about
+ setting up the server to require the use of GSSAPI for
+ some or all connections.
+
+ When using GSSAPI for encryption, it is common to
+ use GSSAPI for authentication as well, since the
+ underlying mechanism will determine both client and server identities
+ (according to the GSSAPI implementation) in any
+ case. But this is not required;
+ another PostgreSQL authentication method
+ can be chosen to perform additional verification.
+
+ Other than configuration of the negotiation
+ behavior, GSSAPI encryption requires no setup beyond
+ that which is necessary for GSSAPI authentication. (For more information
+ on configuring that, see Section 21.6.)
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/hash-implementation.html b/pgsql/doc/postgresql/html/hash-implementation.html
new file mode 100644
index 0000000000000000000000000000000000000000..348b88fa6afdd4bb2f53867c6d69ec08db196703
--- /dev/null
+++ b/pgsql/doc/postgresql/html/hash-implementation.html
@@ -0,0 +1,36 @@
+
+72.2. Implementation
+ There are four kinds of pages in a hash index: the meta page (page zero),
+ which contains statically allocated control information; primary bucket
+ pages; overflow pages; and bitmap pages, which keep track of overflow
+ pages that have been freed and are available for re-use. For addressing
+ purposes, bitmap pages are regarded as a subset of the overflow pages.
+
+ Both scanning the index and inserting tuples require locating the bucket
+ where a given tuple ought to be located. To do this, we need the bucket
+ count, highmask, and lowmask from the metapage; however, it's undesirable
+ for performance reasons to have to have to lock and pin the metapage for
+ every such operation. Instead, we retain a cached copy of the metapage
+ in each backend's relcache entry. This will produce the correct bucket
+ mapping as long as the target bucket hasn't been split since the last
+ cache refresh.
+
+ Primary bucket pages and overflow pages are allocated independently since
+ any given index might need more or fewer overflow pages relative to its
+ number of buckets. The hash code uses an interesting set of addressing
+ rules to support a variable number of overflow pages while not having to
+ move primary bucket pages around after they are created.
+
+ Each row in the table indexed is represented by a single index tuple in
+ the hash index. Hash index tuples are stored in bucket pages, and if
+ they exist, overflow pages. We speed up searches by keeping the index entries
+ in any one index page sorted by hash code, thus allowing binary search to be
+ used within an index page. Note however that there is *no* assumption about
+ the relative ordering of hash codes across different index pages of a bucket.
+
+ The bucket splitting algorithms to expand the hash index are too complex to
+ be worthy of mention here, though are described in more detail in
+ src/backend/access/hash/README.
+ The split algorithm is crash safe and can be restarted if not completed
+ successfully.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/hash-index.html b/pgsql/doc/postgresql/html/hash-index.html
new file mode 100644
index 0000000000000000000000000000000000000000..4e2b7ba3da03e5ae16556eced9b9551f29a5c8cf
--- /dev/null
+++ b/pgsql/doc/postgresql/html/hash-index.html
@@ -0,0 +1,2 @@
+
+Chapter 72. Hash Indexes
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/hash-intro.html b/pgsql/doc/postgresql/html/hash-intro.html
new file mode 100644
index 0000000000000000000000000000000000000000..13dd819024decafe70253f8b663d135c88b66c57
--- /dev/null
+++ b/pgsql/doc/postgresql/html/hash-intro.html
@@ -0,0 +1,77 @@
+
+72.1. Overview
+ PostgreSQL
+ includes an implementation of persistent on-disk hash indexes,
+ which are fully crash recoverable. Any data type can be indexed by a
+ hash index, including data types that do not have a well-defined linear
+ ordering. Hash indexes store only the hash value of the data being
+ indexed, thus there are no restrictions on the size of the data column
+ being indexed.
+
+ Hash indexes support only single-column indexes and do not allow
+ uniqueness checking.
+
+ Hash indexes support only the = operator,
+ so WHERE clauses that specify range operations will not be able to take
+ advantage of hash indexes.
+
+ Each hash index tuple stores just the 4-byte hash value, not the actual
+ column value. As a result, hash indexes may be much smaller than B-trees
+ when indexing longer data items such as UUIDs, URLs, etc. The absence of
+ the column value also makes all hash index scans lossy. Hash indexes may
+ take part in bitmap index scans and backward scans.
+
+ Hash indexes are best optimized for SELECT and UPDATE-heavy workloads
+ that use equality scans on larger tables. In a B-tree index, searches must
+ descend through the tree until the leaf page is found. In tables with
+ millions of rows, this descent can increase access time to data. The
+ equivalent of a leaf page in a hash index is referred to as a bucket page. In
+ contrast, a hash index allows accessing the bucket pages directly,
+ thereby potentially reducing index access time in larger tables. This
+ reduction in "logical I/O" becomes even more pronounced on indexes/data
+ larger than shared_buffers/RAM.
+
+ Hash indexes have been designed to cope with uneven distributions of
+ hash values. Direct access to the bucket pages works well if the hash
+ values are evenly distributed. When inserts mean that the bucket page
+ becomes full, additional overflow pages are chained to that specific
+ bucket page, locally expanding the storage for index tuples that match
+ that hash value. When scanning a hash bucket during queries, we need to
+ scan through all of the overflow pages. Thus an unbalanced hash index
+ might actually be worse than a B-tree in terms of number of block
+ accesses required, for some data.
+
+ As a result of the overflow cases, we can say that hash indexes are
+ most suitable for unique, nearly unique data or data with a low number
+ of rows per hash bucket.
+ One possible way to avoid problems is to exclude highly non-unique
+ values from the index using a partial index condition, but this may
+ not be suitable in many cases.
+
+ Like B-Trees, hash indexes perform simple index tuple deletion. This
+ is a deferred maintenance operation that deletes index tuples that are
+ known to be safe to delete (those whose item identifier's LP_DEAD bit
+ is already set). If an insert finds no space is available on a page we
+ try to avoid creating a new overflow page by attempting to remove dead
+ index tuples. Removal cannot occur if the page is pinned at that time.
+ Deletion of dead index pointers also occurs during VACUUM.
+
+ If it can, VACUUM will also try to squeeze the index tuples onto as
+ few overflow pages as possible, minimizing the overflow chain. If an
+ overflow page becomes empty, overflow pages can be recycled for reuse
+ in other buckets, though we never return them to the operating system.
+ There is currently no provision to shrink a hash index, other than by
+ rebuilding it with REINDEX.
+ There is no provision for reducing the number of buckets, either.
+
+ Hash indexes may expand the number of bucket pages as the number of
+ rows indexed grows. The hash key-to-bucket-number mapping is chosen so that
+ the index can be incrementally expanded. When a new bucket is to be added to
+ the index, exactly one existing bucket will need to be "split", with some of
+ its tuples being transferred to the new bucket according to the updated
+ key-to-bucket-number mapping.
+
+ The expansion occurs in the foreground, which could increase execution
+ time for user inserts. Thus, hash indexes may not be suitable for tables
+ with rapidly increasing number of rows.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/high-availability.html b/pgsql/doc/postgresql/html/high-availability.html
new file mode 100644
index 0000000000000000000000000000000000000000..5b07c81da1bbe70aa3341e49938989cbe7bcd3c5
--- /dev/null
+++ b/pgsql/doc/postgresql/html/high-availability.html
@@ -0,0 +1,57 @@
+
+Chapter 27. High Availability, Load Balancing, and Replication
Chapter 27. High Availability, Load Balancing, and Replication
+ Database servers can work together to allow a second server to
+ take over quickly if the primary server fails (high
+ availability), or to allow several computers to serve the same
+ data (load balancing). Ideally, database servers could work
+ together seamlessly. Web servers serving static web pages can
+ be combined quite easily by merely load-balancing web requests
+ to multiple machines. In fact, read-only database servers can
+ be combined relatively easily too. Unfortunately, most database
+ servers have a read/write mix of requests, and read/write servers
+ are much harder to combine. This is because though read-only
+ data needs to be placed on each server only once, a write to any
+ server has to be propagated to all servers so that future read
+ requests to those servers return consistent results.
+
+ This synchronization problem is the fundamental difficulty for
+ servers working together. Because there is no single solution
+ that eliminates the impact of the sync problem for all use cases,
+ there are multiple solutions. Each solution addresses this
+ problem in a different way, and minimizes its impact for a specific
+ workload.
+
+ Some solutions deal with synchronization by allowing only one
+ server to modify the data. Servers that can modify data are
+ called read/write, master or primary servers.
+ Servers that track changes in the primary are called standby
+ or secondary servers. A standby server that cannot be connected
+ to until it is promoted to a primary server is called a warm
+ standby server, and one that can accept connections and serves read-only
+ queries is called a hot standby server.
+
+ Some solutions are synchronous,
+ meaning that a data-modifying transaction is not considered
+ committed until all servers have committed the transaction. This
+ guarantees that a failover will not lose any data and that all
+ load-balanced servers will return consistent results no matter
+ which server is queried. In contrast, asynchronous solutions allow some
+ delay between the time of a commit and its propagation to the other servers,
+ opening the possibility that some transactions might be lost in
+ the switch to a backup server, and that load balanced servers
+ might return slightly stale results. Asynchronous communication
+ is used when synchronous would be too slow.
+
+ Solutions can also be categorized by their granularity. Some solutions
+ can deal only with an entire database server, while others allow control
+ at the per-table or per-database level.
+
+ Performance must be considered in any choice. There is usually a
+ trade-off between functionality and
+ performance. For example, a fully synchronous solution over a slow
+ network might cut performance by more than half, while an asynchronous
+ one might have a minimal performance impact.
+
+ The remainder of this section outlines various failover, replication,
+ and load balancing solutions.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/history.html b/pgsql/doc/postgresql/html/history.html
new file mode 100644
index 0000000000000000000000000000000000000000..4bc20cee190094b4e2a3ca1e8b5cf94bc3415a97
--- /dev/null
+++ b/pgsql/doc/postgresql/html/history.html
@@ -0,0 +1,140 @@
+
+2. A Brief History of PostgreSQL
+ The object-relational database management system now known as
+ PostgreSQL is derived from the
+ POSTGRES package written at the
+ University of California at Berkeley. With decades of
+ development behind it, PostgreSQL is now
+ the most advanced open-source database available anywhere.
+
+ The POSTGRES project, led by Professor
+ Michael Stonebraker, was sponsored by the Defense Advanced Research
+ Projects Agency (DARPA), the Army Research
+ Office (ARO), the National Science Foundation
+ (NSF), and ESL, Inc. The implementation of
+ POSTGRES began in 1986. The initial
+ concepts for the system were presented in [ston86],
+ and the definition of the initial data model appeared in [rowe87]. The design of the rule system at that time was
+ described in [ston87a]. The rationale and
+ architecture of the storage manager were detailed in [ston87b].
+
+ POSTGRES has undergone several major
+ releases since then. The first “demoware” system
+ became operational in 1987 and was shown at the 1988
+ ACM-SIGMOD Conference. Version 1, described in
+ [ston90a], was released to a few external users in
+ June 1989. In response to a critique of the first rule system
+ ([ston89]), the rule system was redesigned ([ston90b]), and Version 2 was released in June 1990 with
+ the new rule system. Version 3 appeared in 1991 and added support
+ for multiple storage managers, an improved query executor, and a
+ rewritten rule system. For the most part, subsequent releases
+ until Postgres95 (see below) focused on
+ portability and reliability.
+
+ POSTGRES has been used to implement many
+ different research and production applications. These include: a
+ financial data analysis system, a jet engine performance monitoring
+ package, an asteroid tracking database, a medical information
+ database, and several geographic information systems.
+ POSTGRES has also been used as an
+ educational tool at several universities. Finally, Illustra
+ Information Technologies (later merged into
+ Informix,
+ which is now owned by IBM) picked up the code and
+ commercialized it. In late 1992,
+ POSTGRES became the primary data manager
+ for the
+
+ Sequoia 2000 scientific computing project.
+
+ The size of the external user community nearly doubled during 1993.
+ It became increasingly obvious that maintenance of the prototype
+ code and support was taking up large amounts of time that should
+ have been devoted to database research. In an effort to reduce
+ this support burden, the Berkeley
+ POSTGRES project officially ended with
+ Version 4.2.
+
+ In 1994, Andrew Yu and Jolly Chen added an SQL language interpreter
+ to POSTGRES. Under a new name,
+ Postgres95 was subsequently released to
+ the web to find its own way in the world as an open-source
+ descendant of the original POSTGRES
+ Berkeley code.
+
+ Postgres95 code was completely ANSI C
+ and trimmed in size by 25%. Many internal changes improved
+ performance and
+ maintainability. Postgres95 release
+ 1.0.x ran about 30–50% faster on the Wisconsin Benchmark compared
+ to POSTGRES, Version 4.2. Apart from
+ bug fixes, the following were the major enhancements:
+
+
+ The query language PostQUEL was replaced with
+ SQL (implemented in the server). (Interface
+ library libpq was named after PostQUEL.)
+ Subqueries
+ were not supported until PostgreSQL
+ (see below), but they could be imitated in
+ Postgres95 with user-defined
+ SQL functions. Aggregate functions were
+ re-implemented. Support for the GROUP BY
+ query clause was also added.
+
+ A new program
+ (psql) was provided for interactive
+ SQL queries, which used GNU
+ Readline. This largely superseded
+ the old monitor program.
+
+ A new front-end library, libpgtcl,
+ supported Tcl-based clients. A sample shell,
+ pgtclsh, provided new Tcl commands to
+ interface Tcl programs with the
+ Postgres95 server.
+
+ The large-object interface was overhauled. The inversion large
+ objects were the only mechanism for storing large objects. (The
+ inversion file system was removed.)
+
+ The instance-level rule system was removed. Rules were still
+ available as rewrite rules.
+
+ A short tutorial introducing regular SQL
+ features as well as those of
+ Postgres95 was distributed with the
+ source code
+
+ GNU make (instead of BSD
+ make) was used for the build. Also,
+ Postgres95 could be compiled with an
+ unpatched GCC (data alignment of
+ doubles was fixed).
+
+ By 1996, it became clear that the name “Postgres95”
+ would not stand the test of time. We chose a new name,
+ PostgreSQL, to reflect the relationship
+ between the original POSTGRES and the
+ more recent versions with SQL capability. At
+ the same time, we set the version numbering to start at 6.0,
+ putting the numbers back into the sequence originally begun by the
+ Berkeley POSTGRES project.
+
+ Many people continue to refer to
+ PostgreSQL as “Postgres”
+ (now rarely in all capital letters) because of tradition or because
+ it is easier to pronounce. This usage is widely accepted as a
+ nickname or alias.
+
+ The emphasis during development of
+ Postgres95 was on identifying and
+ understanding existing problems in the server code. With
+ PostgreSQL, the emphasis has shifted to
+ augmenting features and capabilities, although work continues in
+ all areas.
+
+ Details about what has happened in PostgreSQL since
+ then can be found in Appendix E.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/hot-standby.html b/pgsql/doc/postgresql/html/hot-standby.html
new file mode 100644
index 0000000000000000000000000000000000000000..eb2d543e510e5b4c15940d0743272013462fefe5
--- /dev/null
+++ b/pgsql/doc/postgresql/html/hot-standby.html
@@ -0,0 +1,567 @@
+
+27.4. Hot Standby
+ Hot standby is the term used to describe the ability to connect to
+ the server and run read-only queries while the server is in archive
+ recovery or standby mode. This
+ is useful both for replication purposes and for restoring a backup
+ to a desired state with great precision.
+ The term hot standby also refers to the ability of the server to move
+ from recovery through to normal operation while users continue running
+ queries and/or keep their connections open.
+
+ Running queries in hot standby mode is similar to normal query operation,
+ though there are several usage and administrative differences
+ explained below.
+
+ When the hot_standby parameter is set to true on a
+ standby server, it will begin accepting connections once the recovery has
+ brought the system to a consistent state. All such connections are
+ strictly read-only; not even temporary tables may be written.
+
+ The data on the standby takes some time to arrive from the primary server
+ so there will be a measurable delay between primary and standby. Running the
+ same query nearly simultaneously on both primary and standby might therefore
+ return differing results. We say that data on the standby is
+ eventually consistent with the primary. Once the
+ commit record for a transaction is replayed on the standby, the changes
+ made by that transaction will be visible to any new snapshots taken on
+ the standby. Snapshots may be taken at the start of each query or at the
+ start of each transaction, depending on the current transaction isolation
+ level. For more details, see Section 13.2.
+
+ Transactions started during hot standby may issue the following commands:
+
+
+ Query access: SELECT, COPY TO
+
+ Cursor commands: DECLARE, FETCH, CLOSE
+
+ Settings: SHOW, SET, RESET
+
+ Transaction management commands:
+
+ BEGIN, END, ABORT, START TRANSACTION
+
+ SAVEPOINT, RELEASE, ROLLBACK TO SAVEPOINT
+
+ EXCEPTION blocks and other internal subtransactions
+
+
+ LOCK TABLE, though only when explicitly in one of these modes:
+ ACCESS SHARE, ROW SHARE or ROW EXCLUSIVE.
+
+ Plans and resources: PREPARE, EXECUTE,
+ DEALLOCATE, DISCARD
+
+ Plugins and extensions: LOAD
+
+ UNLISTEN
+
+
+ Transactions started during hot standby will never be assigned a
+ transaction ID and cannot write to the system write-ahead log.
+ Therefore, the following actions will produce error messages:
+
+
+ Data Manipulation Language (DML): INSERT,
+ UPDATE, DELETE,
+ MERGE, COPY FROM,
+ TRUNCATE.
+ Note that there are no allowed actions that result in a trigger
+ being executed during recovery. This restriction applies even to
+ temporary tables, because table rows cannot be read or written without
+ assigning a transaction ID, which is currently not possible in a
+ hot standby environment.
+
+ Data Definition Language (DDL): CREATE,
+ DROP, ALTER, COMMENT.
+ This restriction applies even to temporary tables, because carrying
+ out these operations would require updating the system catalog tables.
+
+ SELECT ... FOR SHARE | UPDATE, because row locks cannot be
+ taken without updating the underlying data files.
+
+ Rules on SELECT statements that generate DML commands.
+
+ LOCK that explicitly requests a mode higher than ROW EXCLUSIVE MODE.
+
+ LOCK in short default form, since it requests ACCESS EXCLUSIVE MODE.
+
+ Transaction management commands that explicitly set non-read-only state:
+
+ BEGIN READ WRITE,
+ START TRANSACTION READ WRITE
+
+ SET TRANSACTION READ WRITE,
+ SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE
+
+ SET transaction_read_only = off
+
+
+ Two-phase commit commands: PREPARE TRANSACTION,
+ COMMIT PREPARED, ROLLBACK PREPARED
+ because even read-only transactions need to write WAL in the
+ prepare phase (the first phase of two phase commit).
+
+ Sequence updates: nextval(), setval()
+
+ LISTEN, NOTIFY
+
+
+ In normal operation, “read-only” transactions are allowed to
+ use LISTEN and NOTIFY,
+ so hot standby sessions operate under slightly tighter
+ restrictions than ordinary read-only sessions. It is possible that some
+ of these restrictions might be loosened in a future release.
+
+ During hot standby, the parameter transaction_read_only is always
+ true and may not be changed. But as long as no attempt is made to modify
+ the database, connections during hot standby will act much like any other
+ database connection. If failover or switchover occurs, the database will
+ switch to normal processing mode. Sessions will remain connected while the
+ server changes mode. Once hot standby finishes, it will be possible to
+ initiate read-write transactions (even from a session begun during
+ hot standby).
+
+ Users can determine whether hot standby is currently active for their
+ session by issuing SHOW in_hot_standby.
+ (In server versions before 14, the in_hot_standby
+ parameter did not exist; a workable substitute method for older servers
+ is SHOW transaction_read_only.) In addition, a set of
+ functions (Table 9.92) allow users to
+ access information about the standby server. These allow you to write
+ programs that are aware of the current state of the database. These
+ can be used to monitor the progress of recovery, or to allow you to
+ write complex programs that restore the database to particular states.
+
+ The primary and standby servers are in many ways loosely connected. Actions
+ on the primary will have an effect on the standby. As a result, there is
+ potential for negative interactions or conflicts between them. The easiest
+ conflict to understand is performance: if a huge data load is taking place
+ on the primary then this will generate a similar stream of WAL records on the
+ standby, so standby queries may contend for system resources, such as I/O.
+
+ There are also additional types of conflict that can occur with hot standby.
+ These conflicts are hard conflicts in the sense that queries
+ might need to be canceled and, in some cases, sessions disconnected to resolve them.
+ The user is provided with several ways to handle these
+ conflicts. Conflict cases include:
+
+
+ Access Exclusive locks taken on the primary server, including both
+ explicit LOCK commands and various DDL
+ actions, conflict with table accesses in standby queries.
+
+ Dropping a tablespace on the primary conflicts with standby queries
+ using that tablespace for temporary work files.
+
+ Dropping a database on the primary conflicts with sessions connected
+ to that database on the standby.
+
+ Application of a vacuum cleanup record from WAL conflicts with
+ standby transactions whose snapshots can still “see” any of
+ the rows to be removed.
+
+ Application of a vacuum cleanup record from WAL conflicts with
+ queries accessing the target page on the standby, whether or not
+ the data to be removed is visible.
+
+
+ On the primary server, these cases simply result in waiting; and the
+ user might choose to cancel either of the conflicting actions. However,
+ on the standby there is no choice: the WAL-logged action already occurred
+ on the primary so the standby must not fail to apply it. Furthermore,
+ allowing WAL application to wait indefinitely may be very undesirable,
+ because the standby's state will become increasingly far behind the
+ primary's. Therefore, a mechanism is provided to forcibly cancel standby
+ queries that conflict with to-be-applied WAL records.
+
+ An example of the problem situation is an administrator on the primary
+ server running DROP TABLE on a table that is currently being
+ queried on the standby server. Clearly the standby query cannot continue
+ if the DROP TABLE is applied on the standby. If this situation
+ occurred on the primary, the DROP TABLE would wait until the
+ other query had finished. But when DROP TABLE is run on the
+ primary, the primary doesn't have information about what queries are
+ running on the standby, so it will not wait for any such standby
+ queries. The WAL change records come through to the standby while the
+ standby query is still running, causing a conflict. The standby server
+ must either delay application of the WAL records (and everything after
+ them, too) or else cancel the conflicting query so that the DROP
+ TABLE can be applied.
+
+ When a conflicting query is short, it's typically desirable to allow it to
+ complete by delaying WAL application for a little bit; but a long delay in
+ WAL application is usually not desirable. So the cancel mechanism has
+ parameters, max_standby_archive_delay and max_standby_streaming_delay, that define the maximum
+ allowed delay in WAL application. Conflicting queries will be canceled
+ once it has taken longer than the relevant delay setting to apply any
+ newly-received WAL data. There are two parameters so that different delay
+ values can be specified for the case of reading WAL data from an archive
+ (i.e., initial recovery from a base backup or “catching up” a
+ standby server that has fallen far behind) versus reading WAL data via
+ streaming replication.
+
+ In a standby server that exists primarily for high availability, it's
+ best to set the delay parameters relatively short, so that the server
+ cannot fall far behind the primary due to delays caused by standby
+ queries. However, if the standby server is meant for executing
+ long-running queries, then a high or even infinite delay value may be
+ preferable. Keep in mind however that a long-running query could
+ cause other sessions on the standby server to not see recent changes
+ on the primary, if it delays application of WAL records.
+
+ Once the delay specified by max_standby_archive_delay or
+ max_standby_streaming_delay has been exceeded, conflicting
+ queries will be canceled. This usually results just in a cancellation
+ error, although in the case of replaying a DROP DATABASE
+ the entire conflicting session will be terminated. Also, if the conflict
+ is over a lock held by an idle transaction, the conflicting session is
+ terminated (this behavior might change in the future).
+
+ Canceled queries may be retried immediately (after beginning a new
+ transaction, of course). Since query cancellation depends on
+ the nature of the WAL records being replayed, a query that was
+ canceled may well succeed if it is executed again.
+
+ Keep in mind that the delay parameters are compared to the elapsed time
+ since the WAL data was received by the standby server. Thus, the grace
+ period allowed to any one query on the standby is never more than the
+ delay parameter, and could be considerably less if the standby has already
+ fallen behind as a result of waiting for previous queries to complete, or
+ as a result of being unable to keep up with a heavy update load.
+
+ The most common reason for conflict between standby queries and WAL replay
+ is “early cleanup”. Normally, PostgreSQL allows
+ cleanup of old row versions when there are no transactions that need to
+ see them to ensure correct visibility of data according to MVCC rules.
+ However, this rule can only be applied for transactions executing on the
+ primary. So it is possible that cleanup on the primary will remove row
+ versions that are still visible to a transaction on the standby.
+
+ Row version cleanup isn't the only potential cause of conflicts with
+ standby queries. All index-only scans (including those that run on
+ standbys) must use an MVCC snapshot that
+ “agrees” with the visibility map. Conflicts are therefore
+ required whenever VACUUMsets a page as all-visible in the
+ visibility map containing one or more rows
+ not visible to all standby queries. So even running
+ VACUUM against a table with no updated or deleted rows
+ requiring cleanup might lead to conflicts.
+
+ Users should be clear that tables that are regularly and heavily updated
+ on the primary server will quickly cause cancellation of longer running
+ queries on the standby. In such cases the setting of a finite value for
+ max_standby_archive_delay or
+ max_standby_streaming_delay can be considered similar to
+ setting statement_timeout.
+
+ Remedial possibilities exist if the number of standby-query cancellations
+ is found to be unacceptable. The first option is to set the parameter
+ hot_standby_feedback, which prevents VACUUM from
+ removing recently-dead rows and so cleanup conflicts do not occur.
+ If you do this, you
+ should note that this will delay cleanup of dead rows on the primary,
+ which may result in undesirable table bloat. However, the cleanup
+ situation will be no worse than if the standby queries were running
+ directly on the primary server, and you are still getting the benefit of
+ off-loading execution onto the standby.
+ If standby servers connect and disconnect frequently, you
+ might want to make adjustments to handle the period when
+ hot_standby_feedback feedback is not being provided.
+ For example, consider increasing max_standby_archive_delay
+ so that queries are not rapidly canceled by conflicts in WAL archive
+ files during disconnected periods. You should also consider increasing
+ max_standby_streaming_delay to avoid rapid cancellations
+ by newly-arrived streaming WAL entries after reconnection.
+
+ The number of query cancels and the reason for them can be viewed using
+ the pg_stat_database_conflicts system view on the standby
+ server. The pg_stat_database system view also contains
+ summary information.
+
+ Users can control whether a log message is produced when WAL replay is waiting
+ longer than deadlock_timeout for conflicts. This
+ is controlled by the log_recovery_conflict_waits parameter.
+
+ If hot_standby is on in postgresql.conf
+ (the default value) and there is a
+ standby.signal
+ file present, the server will run in hot standby mode.
+ However, it may take some time for hot standby connections to be allowed,
+ because the server will not accept connections until it has completed
+ sufficient recovery to provide a consistent state against which queries
+ can run. During this period,
+ clients that attempt to connect will be refused with an error message.
+ To confirm the server has come up, either loop trying to connect from
+ the application, or look for these messages in the server logs:
+
+
+LOG: entering standby mode
+
+... then some time later ...
+
+LOG: consistent recovery state reached
+LOG: database system is ready to accept read-only connections
+
+
+ Consistency information is recorded once per checkpoint on the primary.
+ It is not possible to enable hot standby when reading WAL
+ written during a period when wal_level was not set to
+ replica or logical on the primary. Reaching
+ a consistent state can also be delayed in the presence of both of these
+ conditions:
+
+
+ A write transaction has more than 64 subtransactions
+
+ Very long-lived write transactions
+
+
+ If you are running file-based log shipping ("warm standby"), you might need
+ to wait until the next WAL file arrives, which could be as long as the
+ archive_timeout setting on the primary.
+
+ The settings of some parameters determine the size of shared memory for
+ tracking transaction IDs, locks, and prepared transactions. These shared
+ memory structures must be no smaller on a standby than on the primary in
+ order to ensure that the standby does not run out of shared memory during
+ recovery. For example, if the primary had used a prepared transaction but
+ the standby had not allocated any shared memory for tracking prepared
+ transactions, then recovery could not continue until the standby's
+ configuration is changed. The parameters affected are:
+
+
+ max_connections
+
+ max_prepared_transactions
+
+ max_locks_per_transaction
+
+ max_wal_senders
+
+ max_worker_processes
+
+
+ The easiest way to ensure this does not become a problem is to have these
+ parameters set on the standbys to values equal to or greater than on the
+ primary. Therefore, if you want to increase these values, you should do
+ so on all standby servers first, before applying the changes to the
+ primary server. Conversely, if you want to decrease these values, you
+ should do so on the primary server first, before applying the changes to
+ all standby servers. Keep in mind that when a standby is promoted, it
+ becomes the new reference for the required parameter settings for the
+ standbys that follow it. Therefore, to avoid this becoming a problem
+ during a switchover or failover, it is recommended to keep these settings
+ the same on all standby servers.
+
+ The WAL tracks changes to these parameters on the
+ primary. If a hot standby processes WAL that indicates that the current
+ value on the primary is higher than its own value, it will log a warning
+ and pause recovery, for example:
+
+WARNING: hot standby is not possible because of insufficient parameter settings
+DETAIL: max_connections = 80 is a lower setting than on the primary server, where its value was 100.
+LOG: recovery has paused
+DETAIL: If recovery is unpaused, the server will shut down.
+HINT: You can then restart the server after making the necessary configuration changes.
+
+ At that point, the settings on the standby need to be updated and the
+ instance restarted before recovery can continue. If the standby is not a
+ hot standby, then when it encounters the incompatible parameter change, it
+ will shut down immediately without pausing, since there is then no value
+ in keeping it up.
+
+ It is important that the administrator select appropriate settings for
+ max_standby_archive_delay and max_standby_streaming_delay. The best choices vary
+ depending on business priorities. For example if the server is primarily
+ tasked as a High Availability server, then you will want low delay
+ settings, perhaps even zero, though that is a very aggressive setting. If
+ the standby server is tasked as an additional server for decision support
+ queries then it might be acceptable to set the maximum delay values to
+ many hours, or even -1 which means wait forever for queries to complete.
+
+ Transaction status "hint bits" written on the primary are not WAL-logged,
+ so data on the standby will likely re-write the hints again on the standby.
+ Thus, the standby server will still perform disk writes even though
+ all users are read-only; no changes occur to the data values
+ themselves. Users will still write large sort temporary files and
+ re-generate relcache info files, so no part of the database
+ is truly read-only during hot standby mode.
+ Note also that writes to remote databases using
+ dblink module, and other operations outside the
+ database using PL functions will still be possible, even though the
+ transaction is read-only locally.
+
+ The following types of administration commands are not accepted
+ during recovery mode:
+
+
+ Data Definition Language (DDL): e.g., CREATE INDEX
+
+ Privilege and Ownership: GRANT, REVOKE,
+ REASSIGN
+
+ Again, note that some of these commands are actually allowed during
+ "read only" mode transactions on the primary.
+
+ As a result, you cannot create additional indexes that exist solely
+ on the standby, nor statistics that exist solely on the standby.
+ If these administration commands are needed, they should be executed
+ on the primary, and eventually those changes will propagate to the
+ standby.
+
+ pg_cancel_backend()
+ and pg_terminate_backend() will work on user backends,
+ but not the startup process, which performs
+ recovery. pg_stat_activity does not show
+ recovering transactions as active. As a result,
+ pg_prepared_xacts is always empty during
+ recovery. If you wish to resolve in-doubt prepared transactions, view
+ pg_prepared_xacts on the primary and issue commands to
+ resolve transactions there or resolve them after the end of recovery.
+
+ pg_locks will show locks held by backends,
+ as normal. pg_locks also shows
+ a virtual transaction managed by the startup process that owns all
+ AccessExclusiveLocks held by transactions being replayed by recovery.
+ Note that the startup process does not acquire locks to
+ make database changes, and thus locks other than AccessExclusiveLocks
+ do not show in pg_locks for the Startup
+ process; they are just presumed to exist.
+
+ The Nagios plugin check_pgsql will
+ work, because the simple information it checks for exists.
+ The check_postgres monitoring script will also work,
+ though some reported values could give different or confusing results.
+ For example, last vacuum time will not be maintained, since no
+ vacuum occurs on the standby. Vacuums running on the primary
+ do still send their changes to the standby.
+
+ WAL file control commands will not work during recovery,
+ e.g., pg_backup_start, pg_switch_wal etc.
+
+ Dynamically loadable modules work, including pg_stat_statements.
+
+ Advisory locks work normally in recovery, including deadlock detection.
+ Note that advisory locks are never WAL logged, so it is impossible for
+ an advisory lock on either the primary or the standby to conflict with WAL
+ replay. Nor is it possible to acquire an advisory lock on the primary
+ and have it initiate a similar advisory lock on the standby. Advisory
+ locks relate only to the server on which they are acquired.
+
+ Trigger-based replication systems such as Slony,
+ Londiste and Bucardo won't run on the
+ standby at all, though they will run happily on the primary server as
+ long as the changes are not sent to standby servers to be applied.
+ WAL replay is not trigger-based so you cannot relay from the
+ standby to any system that requires additional database writes or
+ relies on the use of triggers.
+
+ New OIDs cannot be assigned, though some UUID generators may still
+ work as long as they do not rely on writing new status to the database.
+
+ Currently, temporary table creation is not allowed during read-only
+ transactions, so in some cases existing scripts will not run correctly.
+ This restriction might be relaxed in a later release. This is
+ both an SQL standard compliance issue and a technical issue.
+
+ DROP TABLESPACE can only succeed if the tablespace is empty.
+ Some standby users may be actively using the tablespace via their
+ temp_tablespaces parameter. If there are temporary files in the
+ tablespace, all active queries are canceled to ensure that temporary
+ files are removed, so the tablespace can be removed and WAL replay
+ can continue.
+
+ Running DROP DATABASE or ALTER DATABASE ... SET
+ TABLESPACE on the primary
+ will generate a WAL entry that will cause all users connected to that
+ database on the standby to be forcibly disconnected. This action occurs
+ immediately, whatever the setting of
+ max_standby_streaming_delay. Note that
+ ALTER DATABASE ... RENAME does not disconnect users, which
+ in most cases will go unnoticed, though might in some cases cause a
+ program confusion if it depends in some way upon database name.
+
+ In normal (non-recovery) mode, if you issue DROP USER or DROP ROLE
+ for a role with login capability while that user is still connected then
+ nothing happens to the connected user — they remain connected. The user cannot
+ reconnect however. This behavior applies in recovery also, so a
+ DROP USER on the primary does not disconnect that user on the standby.
+
+ The cumulative statistics system is active during recovery. All scans,
+ reads, blocks, index usage, etc., will be recorded normally on the
+ standby. However, WAL replay will not increment relation and database
+ specific counters. I.e. replay will not increment pg_stat_all_tables
+ columns (like n_tup_ins), nor will reads or writes performed by the
+ startup process be tracked in the pg_statio views, nor will associated
+ pg_stat_database columns be incremented.
+
+ Autovacuum is not active during recovery. It will start normally at the
+ end of recovery.
+
+ The checkpointer process and the background writer process are active during
+ recovery. The checkpointer process will perform restartpoints (similar to
+ checkpoints on the primary) and the background writer process will perform
+ normal block cleaning activities. This can include updates of the hint bit
+ information stored on the standby server.
+ The CHECKPOINT command is accepted during recovery,
+ though it performs a restartpoint rather than a new checkpoint.
+
+ There are several limitations of hot standby.
+ These can and probably will be fixed in future releases:
+
+
+ Full knowledge of running transactions is required before snapshots
+ can be taken. Transactions that use large numbers of subtransactions
+ (currently greater than 64) will delay the start of read-only
+ connections until the completion of the longest running write transaction.
+ If this situation occurs, explanatory messages will be sent to the server log.
+
+ Valid starting points for standby queries are generated at each
+ checkpoint on the primary. If the standby is shut down while the primary
+ is in a shutdown state, it might not be possible to re-enter hot standby
+ until the primary is started up, so that it generates further starting
+ points in the WAL logs. This situation isn't a problem in the most
+ common situations where it might happen. Generally, if the primary is
+ shut down and not available anymore, that's likely due to a serious
+ failure that requires the standby being converted to operate as
+ the new primary anyway. And in situations where the primary is
+ being intentionally taken down, coordinating to make sure the standby
+ becomes the new primary smoothly is also standard procedure.
+
+ At the end of recovery, AccessExclusiveLocks held by prepared transactions
+ will require twice the normal number of lock table entries. If you plan
+ on running either a large number of concurrent prepared transactions
+ that normally take AccessExclusiveLocks, or you plan on having one
+ large transaction that takes many AccessExclusiveLocks, you are
+ advised to select a larger value of max_locks_per_transaction,
+ perhaps as much as twice the value of the parameter on
+ the primary server. You need not consider this at all if
+ your setting of max_prepared_transactions is 0.
+
+ The Serializable transaction isolation level is not yet available in hot
+ standby. (See Section 13.2.3 and
+ Section 13.4.1 for details.)
+ An attempt to set a transaction to the serializable isolation level in
+ hot standby mode will generate an error.
+
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/how-parallel-query-works.html b/pgsql/doc/postgresql/html/how-parallel-query-works.html
new file mode 100644
index 0000000000000000000000000000000000000000..3b0efabfbaf9d6e6c02c5841fa139ee184d8a4ab
--- /dev/null
+++ b/pgsql/doc/postgresql/html/how-parallel-query-works.html
@@ -0,0 +1,71 @@
+
+15.1. How Parallel Query Works
+ When the optimizer determines that parallel query is the fastest execution
+ strategy for a particular query, it will create a query plan that includes
+ a Gather or Gather Merge
+ node. Here is a simple example:
+
+
+EXPLAIN SELECT * FROM pgbench_accounts WHERE filler LIKE '%x%';
+ QUERY PLAN
+-------------------------------------------------------------------------------------
+ Gather (cost=1000.00..217018.43 rows=1 width=97)
+ Workers Planned: 2
+ -> Parallel Seq Scan on pgbench_accounts (cost=0.00..216018.33 rows=1 width=97)
+ Filter: (filler ~~ '%x%'::text)
+(4 rows)
+
+
+ In all cases, the Gather or
+ Gather Merge node will have exactly one
+ child plan, which is the portion of the plan that will be executed in
+ parallel. If the Gather or Gather Merge node is
+ at the very top of the plan tree, then the entire query will execute in
+ parallel. If it is somewhere else in the plan tree, then only the portion
+ of the plan below it will run in parallel. In the example above, the
+ query accesses only one table, so there is only one plan node other than
+ the Gather node itself; since that plan node is a child of the
+ Gather node, it will run in parallel.
+
+ Using EXPLAIN, you can see the number of
+ workers chosen by the planner. When the Gather node is reached
+ during query execution, the process that is implementing the user's
+ session will request a number of background
+ worker processes equal to the number
+ of workers chosen by the planner. The number of background workers that
+ the planner will consider using is limited to at most
+ max_parallel_workers_per_gather. The total number
+ of background workers that can exist at any one time is limited by both
+ max_worker_processes and
+ max_parallel_workers. Therefore, it is possible for a
+ parallel query to run with fewer workers than planned, or even with
+ no workers at all. The optimal plan may depend on the number of workers
+ that are available, so this can result in poor query performance. If this
+ occurrence is frequent, consider increasing
+ max_worker_processes and max_parallel_workers
+ so that more workers can be run simultaneously or alternatively reducing
+ max_parallel_workers_per_gather so that the planner
+ requests fewer workers.
+
+ Every background worker process that is successfully started for a given
+ parallel query will execute the parallel portion of the plan. The leader
+ will also execute that portion of the plan, but it has an additional
+ responsibility: it must also read all of the tuples generated by the
+ workers. When the parallel portion of the plan generates only a small
+ number of tuples, the leader will often behave very much like an additional
+ worker, speeding up query execution. Conversely, when the parallel portion
+ of the plan generates a large number of tuples, the leader may be almost
+ entirely occupied with reading the tuples generated by the workers and
+ performing any further processing steps that are required by plan nodes
+ above the level of the Gather node or
+ Gather Merge node. In such cases, the leader will
+ do very little of the work of executing the parallel portion of the plan.
+
+ When the node at the top of the parallel portion of the plan is
+ Gather Merge rather than Gather, it indicates that
+ each process executing the parallel portion of the plan is producing
+ tuples in sorted order, and that the leader is performing an
+ order-preserving merge. In contrast, Gather reads tuples
+ from the workers in whatever order is convenient, destroying any sort
+ order that may have existed.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/hstore.html b/pgsql/doc/postgresql/html/hstore.html
new file mode 100644
index 0000000000000000000000000000000000000000..5215503d0da7637fac26b083584330dc829eec14
--- /dev/null
+++ b/pgsql/doc/postgresql/html/hstore.html
@@ -0,0 +1,699 @@
+
+F.18. hstore — hstore key/value datatype
+ This module implements the hstore data type for storing sets of
+ key/value pairs within a single PostgreSQL value.
+ This can be useful in various scenarios, such as rows with many attributes
+ that are rarely examined, or semi-structured data. Keys and values are
+ simply text strings.
+
+ This module is considered “trusted”, that is, it can be
+ installed by non-superusers who have CREATE privilege
+ on the current database.
+
+
+ The text representation of an hstore, used for input and output,
+ includes zero or more key=>
+ value pairs separated by commas. Some examples:
+
+
+k => v
+foo => bar, baz => whatever
+"1-a" => "anything at all"
+
+
+ The order of the pairs is not significant (and may not be reproduced on
+ output). Whitespace between pairs or around the => sign is
+ ignored. Double-quote keys and values that include whitespace, commas,
+ =s or >s. To include a double quote or a
+ backslash in a key or value, escape it with a backslash.
+
+ Each key in an hstore is unique. If you declare an hstore
+ with duplicate keys, only one will be stored in the hstore and
+ there is no guarantee as to which will be kept:
+
+
+ A value (but not a key) can be an SQL NULL. For example:
+
+
+key => NULL
+
+
+ The NULL keyword is case-insensitive. Double-quote the
+ NULL to treat it as the ordinary string “NULL”.
+
Note
+ Keep in mind that the hstore text format, when used for input,
+ applies before any required quoting or escaping. If you are
+ passing an hstore literal via a parameter, then no additional
+ processing is needed. But if you're passing it as a quoted literal
+ constant, then any single-quote characters and (depending on the setting of
+ the standard_conforming_strings configuration parameter)
+ backslash characters need to be escaped correctly. See
+ Section 4.1.2.1 for more on the handling of string
+ constants.
+
+ On output, double quotes always surround keys and values, even when it's
+ not strictly necessary.
+
+ In addition to these operators and functions, values of
+ the hstore type can be subscripted, allowing them to act
+ like associative arrays. Only a single subscript of type text
+ can be specified; it is interpreted as a key and the corresponding
+ value is fetched or stored. For example,
+
+
+CREATE TABLE mytable (h hstore);
+INSERT INTO mytable VALUES ('a=>b, c=>d');
+SELECT h['a'] FROM mytable;
+ h
+---
+ b
+(1 row)
+
+UPDATE mytable SET h['c'] = 'new';
+SELECT h FROM mytable;
+ h
+----------------------
+ "a"=>"b", "c"=>"new"
+(1 row)
+
+
+ A subscripted fetch returns NULL if the subscript
+ is NULL or that key does not exist in
+ the hstore. (Thus, a subscripted fetch is not greatly
+ different from the -> operator.)
+ A subscripted update fails if the subscript is NULL;
+ otherwise, it replaces the value for that key, adding an entry to
+ the hstore if the key does not already exist.
+
+ hstore has GiST and GIN index support for the @>,
+ ?, ?& and ?| operators. For example:
+
+CREATE INDEX hidx ON testhstore USING GIST (h);
+
+CREATE INDEX hidx ON testhstore USING GIN (h);
+
+ gist_hstore_ops GiST opclass approximates a set of
+ key/value pairs as a bitmap signature. Its optional integer parameter
+ siglen determines the
+ signature length in bytes. The default length is 16 bytes.
+ Valid values of signature length are between 1 and 2024 bytes. Longer
+ signatures lead to a more precise search (scanning a smaller fraction of the index and
+ fewer heap pages), at the cost of a larger index.
+
+ Example of creating such an index with a signature length of 32 bytes:
+
+CREATE INDEX hidx ON testhstore USING GIST (h gist_hstore_ops(siglen=32));
+
+
+ hstore also supports btree or hash indexes for
+ the = operator. This allows hstore columns to be
+ declared UNIQUE, or to be used in GROUP BY,
+ ORDER BY or DISTINCT expressions. The sort ordering
+ for hstore values is not particularly useful, but these indexes
+ may be useful for equivalence lookups. Create indexes for =
+ comparisons as follows:
+
+CREATE INDEX hidx ON testhstore USING BTREE (h);
+
+CREATE INDEX hidx ON testhstore USING HASH (h);
+
+ The hstore type, because of its intrinsic liberality, could
+ contain a lot of different keys. Checking for valid keys is the task of the
+ application. The following examples demonstrate several techniques for
+ checking keys and obtaining statistics.
+
+ Simple example:
+
+SELECT * FROM each('aaa=>bq, b=>NULL, ""=>1');
+
+
+ Using a table:
+
+CREATE TABLE stat AS SELECT (each(h)).key, (each(h)).value FROM testhstore;
+
+
+ Online statistics:
+
+SELECT key, count(*) FROM
+ (SELECT (each(h)).key FROM testhstore) AS stat
+ GROUP BY key
+ ORDER BY count DESC, key;
+ key | count
+-----------+-------
+ line | 883
+ query | 207
+ pos | 203
+ node | 202
+ space | 197
+ status | 195
+ public | 194
+ title | 190
+ org | 189
+...................
+
+ As of PostgreSQL 9.0, hstore uses a different internal
+ representation than previous versions. This presents no obstacle for
+ dump/restore upgrades since the text representation (used in the dump) is
+ unchanged.
+
+ In the event of a binary upgrade, upward compatibility is maintained by
+ having the new code recognize old-format data. This will entail a slight
+ performance penalty when processing data that has not yet been modified by
+ the new code. It is possible to force an upgrade of all values in a table
+ column by doing an UPDATE statement as follows:
+
+UPDATE tablename SET hstorecol = hstorecol || '';
+
+
+ Another way to do it is:
+
+ALTER TABLE tablename ALTER hstorecol TYPE hstore USING hstorecol || '';
+
+ The ALTER TABLE method requires an
+ ACCESS EXCLUSIVE lock on the table,
+ but does not result in bloating the table with old row versions.
+
+ Additional extensions are available that implement transforms for
+ the hstore type for the languages PL/Perl and PL/Python. The
+ extensions for PL/Perl are called hstore_plperl
+ and hstore_plperlu, for trusted and untrusted PL/Perl.
+ If you install these transforms and specify them when creating a
+ function, hstore values are mapped to Perl hashes. The
+ extension for PL/Python is called hstore_plpython3u.
+ If you use it, hstore values are mapped to Python dictionaries.
+
Caution
+ It is strongly recommended that the transform extensions be installed in
+ the same schema as hstore. Otherwise there are
+ installation-time security hazards if a transform extension's schema
+ contains objects defined by a hostile user.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index-api.html b/pgsql/doc/postgresql/html/index-api.html
new file mode 100644
index 0000000000000000000000000000000000000000..0cb8f170264ddcae0bfa2f48a7c771e168ff8688
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index-api.html
@@ -0,0 +1,191 @@
+
+64.1. Basic API Structure for Indexes
+ Each index access method is described by a row in the
+ pg_am
+ system catalog. The pg_am entry
+ specifies a name and a handler function for the index
+ access method. These entries can be created and deleted using the
+ CREATE ACCESS METHOD and
+ DROP ACCESS METHOD SQL commands.
+
+ An index access method handler function must be declared to accept a
+ single argument of type internal and to return the
+ pseudo-type index_am_handler. The argument is a dummy value that
+ simply serves to prevent handler functions from being called directly from
+ SQL commands. The result of the function must be a palloc'd struct of
+ type IndexAmRoutine, which contains everything
+ that the core code needs to know to make use of the index access method.
+ The IndexAmRoutine struct, also called the access
+ method's API struct, includes fields specifying assorted
+ fixed properties of the access method, such as whether it can support
+ multicolumn indexes. More importantly, it contains pointers to support
+ functions for the access method, which do all of the real work to access
+ indexes. These support functions are plain C functions and are not
+ visible or callable at the SQL level. The support functions are described
+ in Section 64.2.
+
+ The structure IndexAmRoutine is defined thus:
+
+typedef struct IndexAmRoutine
+{
+ NodeTag type;
+
+ /*
+ * Total number of strategies (operators) by which we can traverse/search
+ * this AM. Zero if AM does not have a fixed set of strategy assignments.
+ */
+ uint16 amstrategies;
+ /* total number of support functions that this AM uses */
+ uint16 amsupport;
+ /* opclass options support function number or 0 */
+ uint16 amoptsprocnum;
+ /* does AM support ORDER BY indexed column's value? */
+ bool amcanorder;
+ /* does AM support ORDER BY result of an operator on indexed column? */
+ bool amcanorderbyop;
+ /* does AM support backward scanning? */
+ bool amcanbackward;
+ /* does AM support UNIQUE indexes? */
+ bool amcanunique;
+ /* does AM support multi-column indexes? */
+ bool amcanmulticol;
+ /* does AM require scans to have a constraint on the first index column? */
+ bool amoptionalkey;
+ /* does AM handle ScalarArrayOpExpr quals? */
+ bool amsearcharray;
+ /* does AM handle IS NULL/IS NOT NULL quals? */
+ bool amsearchnulls;
+ /* can index storage data type differ from column data type? */
+ bool amstorage;
+ /* can an index of this type be clustered on? */
+ bool amclusterable;
+ /* does AM handle predicate locks? */
+ bool ampredlocks;
+ /* does AM support parallel scan? */
+ bool amcanparallel;
+ /* does AM support columns included with clause INCLUDE? */
+ bool amcaninclude;
+ /* does AM use maintenance_work_mem? */
+ bool amusemaintenanceworkmem;
+ /* does AM summarize tuples, with at least all tuples in the block
+ * summarized in one summary */
+ bool amsummarizing;
+ /* OR of parallel vacuum flags */
+ uint8 amparallelvacuumoptions;
+ /* type of data stored in index, or InvalidOid if variable */
+ Oid amkeytype;
+
+ /* interface functions */
+ ambuild_function ambuild;
+ ambuildempty_function ambuildempty;
+ aminsert_function aminsert;
+ ambulkdelete_function ambulkdelete;
+ amvacuumcleanup_function amvacuumcleanup;
+ amcanreturn_function amcanreturn; /* can be NULL */
+ amcostestimate_function amcostestimate;
+ amoptions_function amoptions;
+ amproperty_function amproperty; /* can be NULL */
+ ambuildphasename_function ambuildphasename; /* can be NULL */
+ amvalidate_function amvalidate;
+ amadjustmembers_function amadjustmembers; /* can be NULL */
+ ambeginscan_function ambeginscan;
+ amrescan_function amrescan;
+ amgettuple_function amgettuple; /* can be NULL */
+ amgetbitmap_function amgetbitmap; /* can be NULL */
+ amendscan_function amendscan;
+ ammarkpos_function ammarkpos; /* can be NULL */
+ amrestrpos_function amrestrpos; /* can be NULL */
+
+ /* interface functions to support parallel index scans */
+ amestimateparallelscan_function amestimateparallelscan; /* can be NULL */
+ aminitparallelscan_function aminitparallelscan; /* can be NULL */
+ amparallelrescan_function amparallelrescan; /* can be NULL */
+} IndexAmRoutine;
+
+
+ To be useful, an index access method must also have one or more
+ operator families and
+ operator classes defined in
+ pg_opfamily,
+ pg_opclass,
+ pg_amop, and
+ pg_amproc.
+ These entries allow the planner
+ to determine what kinds of query qualifications can be used with
+ indexes of this access method. Operator families and classes are described
+ in Section 38.16, which is prerequisite material for reading
+ this chapter.
+
+ An individual index is defined by a
+ pg_class
+ entry that describes it as a physical relation, plus a
+ pg_index
+ entry that shows the logical content of the index — that is, the set
+ of index columns it has and the semantics of those columns, as captured by
+ the associated operator classes. The index columns (key values) can be
+ either simple columns of the underlying table or expressions over the table
+ rows. The index access method normally has no interest in where the index
+ key values come from (it is always handed precomputed key values) but it
+ will be very interested in the operator class information in
+ pg_index. Both of these catalog entries can be
+ accessed as part of the Relation data structure that is
+ passed to all operations on the index.
+
+ Some of the flag fields of IndexAmRoutine have nonobvious
+ implications. The requirements of amcanunique
+ are discussed in Section 64.5.
+ The amcanmulticol flag asserts that the
+ access method supports multi-key-column indexes, while
+ amoptionalkey asserts that it allows scans
+ where no indexable restriction clause is given for the first index column.
+ When amcanmulticol is false,
+ amoptionalkey essentially says whether the
+ access method supports full-index scans without any restriction clause.
+ Access methods that support multiple index columns must
+ support scans that omit restrictions on any or all of the columns after
+ the first; however they are permitted to require some restriction to
+ appear for the first index column, and this is signaled by setting
+ amoptionalkey false.
+ One reason that an index AM might set
+ amoptionalkey false is if it doesn't index
+ null values. Since most indexable operators are
+ strict and hence cannot return true for null inputs,
+ it is at first sight attractive to not store index entries for null values:
+ they could never be returned by an index scan anyway. However, this
+ argument fails when an index scan has no restriction clause for a given
+ index column. In practice this means that
+ indexes that have amoptionalkey true must
+ index nulls, since the planner might decide to use such an index
+ with no scan keys at all. A related restriction is that an index
+ access method that supports multiple index columns must
+ support indexing null values in columns after the first, because the planner
+ will assume the index can be used for queries that do not restrict
+ these columns. For example, consider an index on (a,b) and a query with
+ WHERE a = 4. The system will assume the index can be
+ used to scan for rows with a = 4, which is wrong if the
+ index omits rows where b is null.
+ It is, however, OK to omit rows where the first indexed column is null.
+ An index access method that does index nulls may also set
+ amsearchnulls, indicating that it supports
+ IS NULL and IS NOT NULL clauses as search
+ conditions.
+
+ The amcaninclude flag indicates whether the
+ access method supports “included” columns, that is it can
+ store (without processing) additional columns beyond the key column(s).
+ The requirements of the preceding paragraph apply only to the key
+ columns. In particular, the combination
+ of amcanmulticol=false
+ and amcaninclude=true is
+ sensible: it means that there can only be one key column, but there can
+ also be included column(s). Also, included columns must be allowed to be
+ null, independently of amoptionalkey.
+
+ The amsummarizing flag indicates whether the
+ access method summarizes the indexed tuples, with summarizing granularity
+ of at least per block.
+ Access methods that do not point to individual tuples, but to block ranges
+ (like BRIN), may allow the HOT optimization
+ to continue. This does not apply to attributes referenced in index
+ predicates, an update of such an attribute always disables HOT.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index-cost-estimation.html b/pgsql/doc/postgresql/html/index-cost-estimation.html
new file mode 100644
index 0000000000000000000000000000000000000000..fba0bece97884aba26e82f0a9d1f4dea67ef18ef
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index-cost-estimation.html
@@ -0,0 +1,142 @@
+
+64.6. Index Cost Estimation Functions
+ The amcostestimate function is given information describing
+ a possible index scan, including lists of WHERE and ORDER BY clauses that
+ have been determined to be usable with the index. It must return estimates
+ of the cost of accessing the index and the selectivity of the WHERE
+ clauses (that is, the fraction of parent-table rows that will be
+ retrieved during the index scan). For simple cases, nearly all the
+ work of the cost estimator can be done by calling standard routines
+ in the optimizer; the point of having an amcostestimate function is
+ to allow index access methods to provide index-type-specific knowledge,
+ in case it is possible to improve on the standard estimates.
+
+ Each amcostestimate function must have the signature:
+
+
+ The planner's information about the query being processed.
+
path
+ The index access path being considered. All fields except cost and
+ selectivity values are valid.
+
loop_count
+ The number of repetitions of the index scan that should be factored
+ into the cost estimates. This will typically be greater than one when
+ considering a parameterized scan for use in the inside of a nestloop
+ join. Note that the cost estimates should still be for just one scan;
+ a larger loop_count means that it may be appropriate
+ to allow for some caching effects across multiple scans.
+
+
+ The last five parameters are pass-by-reference outputs:
+
+
*indexStartupCost
+ Set to cost of index start-up processing
+
*indexTotalCost
+ Set to total cost of index processing
+
*indexSelectivity
+ Set to index selectivity
+
*indexCorrelation
+ Set to correlation coefficient between index scan order and
+ underlying table's order
+
*indexPages
+ Set to number of index leaf pages
+
+
+ Note that cost estimate functions must be written in C, not in SQL or
+ any available procedural language, because they must access internal
+ data structures of the planner/optimizer.
+
+ The index access costs should be computed using the parameters used by
+ src/backend/optimizer/path/costsize.c: a sequential
+ disk block fetch has cost seq_page_cost, a nonsequential fetch
+ has cost random_page_cost, and the cost of processing one index
+ row should usually be taken as cpu_index_tuple_cost. In
+ addition, an appropriate multiple of cpu_operator_cost should
+ be charged for any comparison operators invoked during index processing
+ (especially evaluation of the indexquals themselves).
+
+ The access costs should include all disk and CPU costs associated with
+ scanning the index itself, but not the costs of retrieving or
+ processing the parent-table rows that are identified by the index.
+
+ The “start-up cost” is the part of the total scan cost that
+ must be expended before we can begin to fetch the first row. For most
+ indexes this can be taken as zero, but an index type with a high start-up
+ cost might want to set it nonzero.
+
+ The indexSelectivity should be set to the estimated fraction of the parent
+ table rows that will be retrieved during the index scan. In the case
+ of a lossy query, this will typically be higher than the fraction of
+ rows that actually pass the given qual conditions.
+
+ The indexCorrelation should be set to the correlation (ranging between
+ -1.0 and 1.0) between the index order and the table order. This is used
+ to adjust the estimate for the cost of fetching rows from the parent
+ table.
+
+ The indexPages should be set to the number of leaf pages.
+ This is used to estimate the number of workers for parallel index scan.
+
+ When loop_count is greater than one, the returned numbers
+ should be averages expected for any one scan of the index.
+
Cost Estimation
+ A typical cost estimator will proceed as follows:
+
+ Estimate and return the fraction of parent-table rows that will be visited
+ based on the given qual conditions. In the absence of any index-type-specific
+ knowledge, use the standard optimizer function clauselist_selectivity():
+
+
+ Estimate the number of index rows that will be visited during the
+ scan. For many index types this is the same as indexSelectivity times
+ the number of rows in the index, but it might be more. (Note that the
+ index's size in pages and rows is available from the
+ path->indexinfo struct.)
+
+ Estimate the number of index pages that will be retrieved during the scan.
+ This might be just indexSelectivity times the index's size in pages.
+
+ Compute the index access cost. A generic estimator might do this:
+
+
+/*
+ * Our generic assumption is that the index pages will be read
+ * sequentially, so they cost seq_page_cost each, not random_page_cost.
+ * Also, we charge for evaluation of the indexquals at each index row.
+ * All the costs are assumed to be paid incrementally during the scan.
+ */
+cost_qual_eval(&index_qual_cost, path->indexquals, root);
+*indexStartupCost = index_qual_cost.startup;
+*indexTotalCost = seq_page_cost * numIndexPages +
+ (cpu_index_tuple_cost + index_qual_cost.per_tuple) * numIndexTuples;
+
+
+ However, the above does not account for amortization of index reads
+ across repeated index scans.
+
+ Estimate the index correlation. For a simple ordered index on a single
+ field, this can be retrieved from pg_statistic. If the correlation
+ is not known, the conservative estimate is zero (no correlation).
+
+ Examples of cost estimator functions can be found in
+ src/backend/utils/adt/selfuncs.c.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index-functions.html b/pgsql/doc/postgresql/html/index-functions.html
new file mode 100644
index 0000000000000000000000000000000000000000..51721d20cc3545484ca85cc3d3c2c13b19dfb563
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index-functions.html
@@ -0,0 +1,487 @@
+
+64.2. Index Access Method Functions
+ Build a new index. The index relation has been physically created,
+ but is empty. It must be filled in with whatever fixed data the
+ access method requires, plus entries for all tuples already existing
+ in the table. Ordinarily the ambuild function will call
+ table_index_build_scan() to scan the table for existing tuples
+ and compute the keys that need to be inserted into the index.
+ The function must return a palloc'd struct containing statistics about
+ the new index.
+
+
+void
+ambuildempty (Relation indexRelation);
+
+ Build an empty index, and write it to the initialization fork (INIT_FORKNUM)
+ of the given relation. This method is called only for unlogged indexes; the
+ empty index written to the initialization fork will be copied over the main
+ relation fork on each server restart.
+
+ Insert a new tuple into an existing index. The values and
+ isnull arrays give the key values to be indexed, and
+ heap_tid is the TID to be indexed.
+ If the access method supports unique indexes (its
+ amcanunique flag is true) then
+ checkUnique indicates the type of uniqueness check to
+ perform. This varies depending on whether the unique constraint is
+ deferrable; see Section 64.5 for details.
+ Normally the access method only needs the heapRelation
+ parameter when performing uniqueness checking (since then it will have to
+ look into the heap to verify tuple liveness).
+
+ The indexUnchanged Boolean value gives a hint
+ about the nature of the tuple to be indexed. When it is true,
+ the tuple is a duplicate of some existing tuple in the index. The
+ new tuple is a logically unchanged successor MVCC tuple version. This
+ happens when an UPDATE takes place that does not
+ modify any columns covered by the index, but nevertheless requires a
+ new version in the index. The index AM may use this hint to decide
+ to apply bottom-up index deletion in parts of the index where many
+ versions of the same logical row accumulate. Note that updating a non-key
+ column or a column that only appears in a partial index predicate does not
+ affect the value of indexUnchanged. The core code
+ determines each tuple's indexUnchanged value using a low
+ overhead approach that allows both false positives and false negatives.
+ Index AMs must not treat indexUnchanged as an
+ authoritative source of information about tuple visibility or versioning.
+
+ The function's Boolean result value is significant only when
+ checkUnique is UNIQUE_CHECK_PARTIAL.
+ In this case a true result means the new entry is known unique, whereas
+ false means it might be non-unique (and a deferred uniqueness check must
+ be scheduled). For other cases a constant false result is recommended.
+
+ Some indexes might not index all tuples. If the tuple is not to be
+ indexed, aminsert should just return without doing anything.
+
+ If the index AM wishes to cache data across successive index insertions
+ within an SQL statement, it can allocate space
+ in indexInfo->ii_Context and store a pointer to the
+ data in indexInfo->ii_AmCache (which will be NULL
+ initially).
+
+ Delete tuple(s) from the index. This is a “bulk delete” operation
+ that is intended to be implemented by scanning the whole index and checking
+ each entry to see if it should be deleted.
+ The passed-in callback function must be called, in the style
+ callback(TID, callback_state) returns bool,
+ to determine whether any particular index entry, as identified by its
+ referenced TID, is to be deleted. Must return either NULL or a palloc'd
+ struct containing statistics about the effects of the deletion operation.
+ It is OK to return NULL if no information needs to be passed on to
+ amvacuumcleanup.
+
+ Because of limited maintenance_work_mem,
+ ambulkdelete might need to be called more than once when many
+ tuples are to be deleted. The stats argument is the result
+ of the previous call for this index (it is NULL for the first call within a
+ VACUUM operation). This allows the AM to accumulate statistics
+ across the whole operation. Typically, ambulkdelete will
+ modify and return the same struct if the passed stats is not
+ null.
+
+ Clean up after a VACUUM operation (zero or more
+ ambulkdelete calls). This does not have to do anything
+ beyond returning index statistics, but it might perform bulk cleanup
+ such as reclaiming empty index pages. stats is whatever the
+ last ambulkdelete call returned, or NULL if
+ ambulkdelete was not called because no tuples needed to be
+ deleted. If the result is not NULL it must be a palloc'd struct.
+ The statistics it contains will be used to update pg_class,
+ and will be reported by VACUUM if VERBOSE is given.
+ It is OK to return NULL if the index was not changed at all during the
+ VACUUM operation, but otherwise correct stats should
+ be returned.
+
+ amvacuumcleanup will also be called at completion of an
+ ANALYZE operation. In this case stats is always
+ NULL and any return value will be ignored. This case can be distinguished
+ by checking info->analyze_only. It is recommended
+ that the access method do nothing except post-insert cleanup in such a
+ call, and that only in an autovacuum worker process.
+
+
+bool
+amcanreturn (Relation indexRelation, int attno);
+
+ Check whether the index can support index-only scans on
+ the given column, by returning the column's original indexed value.
+ The attribute number is 1-based, i.e., the first column's attno is 1.
+ Returns true if supported, else false.
+ This function should always return true for included columns
+ (if those are supported), since there's little point in an included
+ column that can't be retrieved.
+ If the access method does not support index-only scans at all,
+ the amcanreturn field in its IndexAmRoutine
+ struct can be set to NULL.
+
+ Parse and validate the reloptions array for an index. This is called only
+ when a non-null reloptions array exists for the index.
+ reloptions is a text array containing entries of the
+ form name=value.
+ The function should construct a bytea value, which will be copied
+ into the rd_options field of the index's relcache entry.
+ The data contents of the bytea value are open for the access
+ method to define; most of the standard access methods use struct
+ StdRdOptions.
+ When validate is true, the function should report a suitable
+ error message if any of the options are unrecognized or have invalid
+ values; when validate is false, invalid entries should be
+ silently ignored. (validate is false when loading options
+ already stored in pg_catalog; an invalid entry could only
+ be found if the access method has changed its rules for options, and in
+ that case ignoring obsolete entries is appropriate.)
+ It is OK to return NULL if default behavior is wanted.
+
+ The amproperty method allows index access methods to override
+ the default behavior of pg_index_column_has_property
+ and related functions.
+ If the access method does not have any special behavior for index property
+ inquiries, the amproperty field in
+ its IndexAmRoutine struct can be set to NULL.
+ Otherwise, the amproperty method will be called with
+ index_oid and attno both zero for
+ pg_indexam_has_property calls,
+ or with index_oid valid and attno zero for
+ pg_index_has_property calls,
+ or with index_oid valid and attno greater than
+ zero for pg_index_column_has_property calls.
+ prop is an enum value identifying the property being tested,
+ while propname is the original property name string.
+ If the core code does not recognize the property name
+ then prop is AMPROP_UNKNOWN.
+ Access methods can define custom property names by
+ checking propname for a match (use pg_strcasecmp
+ to match, for consistency with the core code); for names known to the core
+ code, it's better to inspect prop.
+ If the amproperty method returns true then
+ it has determined the property test result: it must set *res
+ to the Boolean value to return, or set *isnull
+ to true to return a NULL. (Both of the referenced variables
+ are initialized to false before the call.)
+ If the amproperty method returns false then
+ the core code will proceed with its normal logic for determining the
+ property test result.
+
+ Access methods that support ordering operators should
+ implement AMPROP_DISTANCE_ORDERABLE property testing, as the
+ core code does not know how to do that and will return NULL. It may
+ also be advantageous to implement AMPROP_RETURNABLE testing,
+ if that can be done more cheaply than by opening the index and calling
+ amcanreturn, which is the core code's default behavior.
+ The default behavior should be satisfactory for all other standard
+ properties.
+
+
+char *
+ambuildphasename (int64 phasenum);
+
+ Return the textual name of the given build phase number.
+ The phase numbers are those reported during an index build via the
+ pgstat_progress_update_param interface.
+ The phase names are then exposed in the
+ pg_stat_progress_create_index view.
+
+
+bool
+amvalidate (Oid opclassoid);
+
+ Validate the catalog entries for the specified operator class, so far as
+ the access method can reasonably do that. For example, this might include
+ testing that all required support functions are provided.
+ The amvalidate function must return false if the opclass is
+ invalid. Problems should be reported with ereport
+ messages, typically at INFO level.
+
+
+void
+amadjustmembers (Oid opfamilyoid,
+ Oid opclassoid,
+ List *operators,
+ List *functions);
+
+ Validate proposed new operator and function members of an operator family,
+ so far as the access method can reasonably do that, and set their
+ dependency types if the default is not satisfactory. This is called
+ during CREATE OPERATOR CLASS and during
+ ALTER OPERATOR FAMILY ADD; in the latter
+ case opclassoid is InvalidOid.
+ The List arguments are lists
+ of OpFamilyMember structs, as defined
+ in amapi.h.
+
+ Tests done by this function will typically be a subset of those
+ performed by amvalidate,
+ since amadjustmembers cannot assume that it is
+ seeing a complete set of members. For example, it would be reasonable
+ to check the signature of a support function, but not to check whether
+ all required support functions are provided. Any problems can be
+ reported by throwing an error.
+
+ The dependency-related fields of
+ the OpFamilyMember structs are initialized by
+ the core code to create hard dependencies on the opclass if this
+ is CREATE OPERATOR CLASS, or soft dependencies on the
+ opfamily if this is ALTER OPERATOR FAMILY ADD.
+ amadjustmembers can adjust these fields if some other
+ behavior is more appropriate. For example, GIN, GiST, and SP-GiST
+ always set operator members to have soft dependencies on the opfamily,
+ since the connection between an operator and an opclass is relatively
+ weak in these index types; so it is reasonable to allow operator members
+ to be added and removed freely. Optional support functions are typically
+ also given soft dependencies, so that they can be removed if necessary.
+
+ The purpose of an index, of course, is to support scans for tuples matching
+ an indexable WHERE condition, often called a
+ qualifier or scan key. The semantics of
+ index scanning are described more fully in Section 64.3,
+ below. An index access method can support “plain” index scans,
+ “bitmap” index scans, or both. The scan-related functions that an
+ index access method must or may provide are:
+
+
+IndexScanDesc
+ambeginscan (Relation indexRelation,
+ int nkeys,
+ int norderbys);
+
+ Prepare for an index scan. The nkeys and norderbys
+ parameters indicate the number of quals and ordering operators that will be
+ used in the scan; these may be useful for space allocation purposes.
+ Note that the actual values of the scan keys aren't provided yet.
+ The result must be a palloc'd struct.
+ For implementation reasons the index access method
+ must create this struct by calling
+ RelationGetIndexScan(). In most cases
+ ambeginscan does little beyond making that call and perhaps
+ acquiring locks;
+ the interesting parts of index-scan startup are in amrescan.
+
+
+void
+amrescan (IndexScanDesc scan,
+ ScanKey keys,
+ int nkeys,
+ ScanKey orderbys,
+ int norderbys);
+
+ Start or restart an index scan, possibly with new scan keys. (To restart
+ using previously-passed keys, NULL is passed for keys and/or
+ orderbys.) Note that it is not allowed for
+ the number of keys or order-by operators to be larger than
+ what was passed to ambeginscan. In practice the restart
+ feature is used when a new outer tuple is selected by a nested-loop join
+ and so a new key comparison value is needed, but the scan key structure
+ remains the same.
+
+ Fetch the next tuple in the given scan, moving in the given
+ direction (forward or backward in the index). Returns true if a tuple was
+ obtained, false if no matching tuples remain. In the true case the tuple
+ TID is stored into the scan structure. Note that
+ “success” means only that the index contains an entry that matches
+ the scan keys, not that the tuple necessarily still exists in the heap or
+ will pass the caller's snapshot test. On success, amgettuple
+ must also set scan->xs_recheck to true or false.
+ False means it is certain that the index entry matches the scan keys.
+ True means this is not certain, and the conditions represented by the
+ scan keys must be rechecked against the heap tuple after fetching it.
+ This provision supports “lossy” index operators.
+ Note that rechecking will extend only to the scan conditions; a partial
+ index predicate (if any) is never rechecked by amgettuple
+ callers.
+
+ If the index supports index-only
+ scans (i.e., amcanreturn returns true for any
+ of its columns),
+ then on success the AM must also check scan->xs_want_itup,
+ and if that is true it must return the originally indexed data for the
+ index entry. Columns for which amcanreturn returns
+ false can be returned as nulls.
+ The data can be returned in the form of an
+ IndexTuple pointer stored at scan->xs_itup,
+ with tuple descriptor scan->xs_itupdesc; or in the form of
+ a HeapTuple pointer stored at scan->xs_hitup,
+ with tuple descriptor scan->xs_hitupdesc. (The latter
+ format should be used when reconstructing data that might possibly not fit
+ into an IndexTuple.) In either case,
+ management of the data referenced by the pointer is the access method's
+ responsibility. The data must remain good at least until the next
+ amgettuple, amrescan, or amendscan
+ call for the scan.
+
+ The amgettuple function need only be provided if the access
+ method supports “plain” index scans. If it doesn't, the
+ amgettuple field in its IndexAmRoutine
+ struct must be set to NULL.
+
+ Fetch all tuples in the given scan and add them to the caller-supplied
+ TIDBitmap (that is, OR the set of tuple IDs into whatever set is already
+ in the bitmap). The number of tuples fetched is returned (this might be
+ just an approximate count, for instance some AMs do not detect duplicates).
+ While inserting tuple IDs into the bitmap, amgetbitmap can
+ indicate that rechecking of the scan conditions is required for specific
+ tuple IDs. This is analogous to the xs_recheck output parameter
+ of amgettuple. Note: in the current implementation, support
+ for this feature is conflated with support for lossy storage of the bitmap
+ itself, and therefore callers recheck both the scan conditions and the
+ partial index predicate (if any) for recheckable tuples. That might not
+ always be true, however.
+ amgetbitmap and
+ amgettuple cannot be used in the same index scan; there
+ are other restrictions too when using amgetbitmap, as explained
+ in Section 64.3.
+
+ The amgetbitmap function need only be provided if the access
+ method supports “bitmap” index scans. If it doesn't, the
+ amgetbitmap field in its IndexAmRoutine
+ struct must be set to NULL.
+
+
+void
+amendscan (IndexScanDesc scan);
+
+ End a scan and release resources. The scan struct itself
+ should not be freed, but any locks or pins taken internally by the
+ access method must be released, as well as any other memory allocated
+ by ambeginscan and other scan-related functions.
+
+
+void
+ammarkpos (IndexScanDesc scan);
+
+ Mark current scan position. The access method need only support one
+ remembered scan position per scan.
+
+ The ammarkpos function need only be provided if the access
+ method supports ordered scans. If it doesn't,
+ the ammarkpos field in its IndexAmRoutine
+ struct may be set to NULL.
+
+
+void
+amrestrpos (IndexScanDesc scan);
+
+ Restore the scan to the most recently marked position.
+
+ The amrestrpos function need only be provided if the access
+ method supports ordered scans. If it doesn't,
+ the amrestrpos field in its IndexAmRoutine
+ struct may be set to NULL.
+
+ In addition to supporting ordinary index scans, some types of index
+ may wish to support parallel index scans, which allow
+ multiple backends to cooperate in performing an index scan. The
+ index access method should arrange things so that each cooperating
+ process returns a subset of the tuples that would be performed by
+ an ordinary, non-parallel index scan, but in such a way that the
+ union of those subsets is equal to the set of tuples that would be
+ returned by an ordinary, non-parallel index scan. Furthermore, while
+ there need not be any global ordering of tuples returned by a parallel
+ scan, the ordering of that subset of tuples returned within each
+ cooperating backend must match the requested ordering. The following
+ functions may be implemented to support parallel index scans:
+
+
+Size
+amestimateparallelscan (void);
+
+ Estimate and return the number of bytes of dynamic shared memory which
+ the access method will be needed to perform a parallel scan. (This number
+ is in addition to, not in lieu of, the amount of space needed for
+ AM-independent data in ParallelIndexScanDescData.)
+
+ It is not necessary to implement this function for access methods which
+ do not support parallel scans or for which the number of additional bytes
+ of storage required is zero.
+
+
+void
+aminitparallelscan (void *target);
+
+ This function will be called to initialize dynamic shared memory at the
+ beginning of a parallel scan. target will point to at least
+ the number of bytes previously returned by
+ amestimateparallelscan, and this function may use that
+ amount of space to store whatever data it wishes.
+
+ It is not necessary to implement this function for access methods which
+ do not support parallel scans or in cases where the shared memory space
+ required needs no initialization.
+
+
+void
+amparallelrescan (IndexScanDesc scan);
+
+ This function, if implemented, will be called when a parallel index scan
+ must be restarted. It should reset any shared state set up by
+ aminitparallelscan such that the scan will be restarted from
+ the beginning.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index-locking.html b/pgsql/doc/postgresql/html/index-locking.html
new file mode 100644
index 0000000000000000000000000000000000000000..63fef2f9757191c1046f8cac8f287a9362e0999a
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index-locking.html
@@ -0,0 +1,91 @@
+
+64.4. Index Locking Considerations
+ Index access methods must handle concurrent updates
+ of the index by multiple processes.
+ The core PostgreSQL system obtains
+ AccessShareLock on the index during an index scan, and
+ RowExclusiveLock when updating the index (including plain
+ VACUUM). Since these lock types do not conflict, the access
+ method is responsible for handling any fine-grained locking it might need.
+ An ACCESS EXCLUSIVE lock on the index as a whole will be
+ taken only during index creation, destruction, or REINDEX
+ (SHARE UPDATE EXCLUSIVE is taken instead with
+ CONCURRENTLY).
+
+ Building an index type that supports concurrent updates usually requires
+ extensive and subtle analysis of the required behavior. For the b-tree
+ and hash index types, you can read about the design decisions involved in
+ src/backend/access/nbtree/README and
+ src/backend/access/hash/README.
+
+ Aside from the index's own internal consistency requirements, concurrent
+ updates create issues about consistency between the parent table (the
+ heap) and the index. Because
+ PostgreSQL separates accesses
+ and updates of the heap from those of the index, there are windows in
+ which the index might be inconsistent with the heap. We handle this problem
+ with the following rules:
+
+
+ A new heap entry is made before making its index entries. (Therefore
+ a concurrent index scan is likely to fail to see the heap entry.
+ This is okay because the index reader would be uninterested in an
+ uncommitted row anyway. But see Section 64.5.)
+
+ When a heap entry is to be deleted (by VACUUM), all its
+ index entries must be removed first.
+
+ An index scan must maintain a pin
+ on the index page holding the item last returned by
+ amgettuple, and ambulkdelete cannot delete
+ entries from pages that are pinned by other backends. The need
+ for this rule is explained below.
+
+
+ Without the third rule, it is possible for an index reader to
+ see an index entry just before it is removed by VACUUM, and
+ then to arrive at the corresponding heap entry after that was removed by
+ VACUUM.
+ This creates no serious problems if that item
+ number is still unused when the reader reaches it, since an empty
+ item slot will be ignored by heap_fetch(). But what if a
+ third backend has already re-used the item slot for something else?
+ When using an MVCC-compliant snapshot, there is no problem because
+ the new occupant of the slot is certain to be too new to pass the
+ snapshot test. However, with a non-MVCC-compliant snapshot (such as
+ SnapshotAny), it would be possible to accept and return
+ a row that does not in fact match the scan keys. We could defend
+ against this scenario by requiring the scan keys to be rechecked
+ against the heap row in all cases, but that is too expensive. Instead,
+ we use a pin on an index page as a proxy to indicate that the reader
+ might still be “in flight” from the index entry to the matching
+ heap entry. Making ambulkdelete block on such a pin ensures
+ that VACUUM cannot delete the heap entry before the reader
+ is done with it. This solution costs little in run time, and adds blocking
+ overhead only in the rare cases where there actually is a conflict.
+
+ This solution requires that index scans be “synchronous”: we have
+ to fetch each heap tuple immediately after scanning the corresponding index
+ entry. This is expensive for a number of reasons. An
+ “asynchronous” scan in which we collect many TIDs from the index,
+ and only visit the heap tuples sometime later, requires much less index
+ locking overhead and can allow a more efficient heap access pattern.
+ Per the above analysis, we must use the synchronous approach for
+ non-MVCC-compliant snapshots, but an asynchronous scan is workable
+ for a query using an MVCC snapshot.
+
+ In an amgetbitmap index scan, the access method does not
+ keep an index pin on any of the returned tuples. Therefore
+ it is only safe to use such scans with MVCC-compliant snapshots.
+
+ When the ampredlocks flag is not set, any scan using that
+ index access method within a serializable transaction will acquire a
+ nonblocking predicate lock on the full index. This will generate a
+ read-write conflict with the insert of any tuple into that index by a
+ concurrent serializable transaction. If certain patterns of read-write
+ conflicts are detected among a set of concurrent serializable
+ transactions, one of those transactions may be canceled to protect data
+ integrity. When the flag is set, it indicates that the index access
+ method implements finer-grained predicate locking, which will tend to
+ reduce the frequency of such transaction cancellations.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index-scanning.html b/pgsql/doc/postgresql/html/index-scanning.html
new file mode 100644
index 0000000000000000000000000000000000000000..cc596a10071bb9a07a3357e4366111aa69fdff82
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index-scanning.html
@@ -0,0 +1,123 @@
+
+64.3. Index Scanning
+ In an index scan, the index access method is responsible for regurgitating
+ the TIDs of all the tuples it has been told about that match the
+ scan keys. The access method is not involved in
+ actually fetching those tuples from the index's parent table, nor in
+ determining whether they pass the scan's visibility test or other
+ conditions.
+
+ A scan key is the internal representation of a WHERE clause of
+ the form index_keyoperator
+ constant, where the index key is one of the columns of the
+ index and the operator is one of the members of the operator family
+ associated with that index column. An index scan has zero or more scan
+ keys, which are implicitly ANDed — the returned tuples are expected
+ to satisfy all the indicated conditions.
+
+ The access method can report that the index is lossy, or
+ requires rechecks, for a particular query. This implies that the index
+ scan will return all the entries that pass the scan key, plus possibly
+ additional entries that do not. The core system's index-scan machinery
+ will then apply the index conditions again to the heap tuple to verify
+ whether or not it really should be selected. If the recheck option is not
+ specified, the index scan must return exactly the set of matching entries.
+
+ Note that it is entirely up to the access method to ensure that it
+ correctly finds all and only the entries passing all the given scan keys.
+ Also, the core system will simply hand off all the WHERE
+ clauses that match the index keys and operator families, without any
+ semantic analysis to determine whether they are redundant or
+ contradictory. As an example, given
+ WHERE x > 4 AND x > 14 where x is a b-tree
+ indexed column, it is left to the b-tree amrescan function
+ to realize that the first scan key is redundant and can be discarded.
+ The extent of preprocessing needed during amrescan will
+ depend on the extent to which the index access method needs to reduce
+ the scan keys to a “normalized” form.
+
+ Some access methods return index entries in a well-defined order, others
+ do not. There are actually two different ways that an access method can
+ support sorted output:
+
+
+ Access methods that always return entries in the natural ordering
+ of their data (such as btree) should set
+ amcanorder to true.
+ Currently, such access methods must use btree-compatible strategy
+ numbers for their equality and ordering operators.
+
+ Access methods that support ordering operators should set
+ amcanorderbyop to true.
+ This indicates that the index is capable of returning entries in
+ an order satisfying ORDER BYindex_key
+ operatorconstant. Scan modifiers
+ of that form can be passed to amrescan as described
+ previously.
+
+
+ The amgettuple function has a direction argument,
+ which can be either ForwardScanDirection (the normal case)
+ or BackwardScanDirection. If the first call after
+ amrescan specifies BackwardScanDirection, then the
+ set of matching index entries is to be scanned back-to-front rather than in
+ the normal front-to-back direction, so amgettuple must return
+ the last matching tuple in the index, rather than the first one as it
+ normally would. (This will only occur for access
+ methods that set amcanorder to true.) After the
+ first call, amgettuple must be prepared to advance the scan in
+ either direction from the most recently returned entry. (But if
+ amcanbackward is false, all subsequent
+ calls will have the same direction as the first one.)
+
+ Access methods that support ordered scans must support “marking” a
+ position in a scan and later returning to the marked position. The same
+ position might be restored multiple times. However, only one position need
+ be remembered per scan; a new ammarkpos call overrides the
+ previously marked position. An access method that does not support ordered
+ scans need not provide ammarkpos and amrestrpos
+ functions in IndexAmRoutine; set those pointers to NULL
+ instead.
+
+ Both the scan position and the mark position (if any) must be maintained
+ consistently in the face of concurrent insertions or deletions in the
+ index. It is OK if a freshly-inserted entry is not returned by a scan that
+ would have found the entry if it had existed when the scan started, or for
+ the scan to return such an entry upon rescanning or backing
+ up even though it had not been returned the first time through. Similarly,
+ a concurrent delete might or might not be reflected in the results of a scan.
+ What is important is that insertions or deletions not cause the scan to
+ miss or multiply return entries that were not themselves being inserted or
+ deleted.
+
+ If the index stores the original indexed data values (and not some lossy
+ representation of them), it is useful to
+ support index-only scans, in
+ which the index returns the actual data not just the TID of the heap tuple.
+ This will only avoid I/O if the visibility map shows that the TID is on an
+ all-visible page; else the heap tuple must be visited anyway to check
+ MVCC visibility. But that is no concern of the access method's.
+
+ Instead of using amgettuple, an index scan can be done with
+ amgetbitmap to fetch all tuples in one call. This can be
+ noticeably more efficient than amgettuple because it allows
+ avoiding lock/unlock cycles within the access method. In principle
+ amgetbitmap should have the same effects as repeated
+ amgettuple calls, but we impose several restrictions to
+ simplify matters. First of all, amgetbitmap returns all
+ tuples at once and marking or restoring scan positions isn't
+ supported. Secondly, the tuples are returned in a bitmap which doesn't
+ have any specific ordering, which is why amgetbitmap doesn't
+ take a direction argument. (Ordering operators will never be
+ supplied for such a scan, either.)
+ Also, there is no provision for index-only scans with
+ amgetbitmap, since there is no way to return the contents of
+ index tuples.
+ Finally, amgetbitmap
+ does not guarantee any locking of the returned tuples, with implications
+ spelled out in Section 64.4.
+
+ Note that it is permitted for an access method to implement only
+ amgetbitmap and not amgettuple, or vice versa,
+ if its internal implementation is unsuited to one API or the other.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index-unique-checks.html b/pgsql/doc/postgresql/html/index-unique-checks.html
new file mode 100644
index 0000000000000000000000000000000000000000..b18c6236dd78683bc48078e641f39a590994b4e8
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index-unique-checks.html
@@ -0,0 +1,109 @@
+
+64.5. Index Uniqueness Checks
+ PostgreSQL enforces SQL uniqueness constraints
+ using unique indexes, which are indexes that disallow
+ multiple entries with identical keys. An access method that supports this
+ feature sets amcanunique true.
+ (At present, only b-tree supports it.) Columns listed in the
+ INCLUDE clause are not considered when enforcing
+ uniqueness.
+
+ Because of MVCC, it is always necessary to allow duplicate entries to
+ exist physically in an index: the entries might refer to successive
+ versions of a single logical row. The behavior we actually want to
+ enforce is that no MVCC snapshot could include two rows with equal
+ index keys. This breaks down into the following cases that must be
+ checked when inserting a new row into a unique index:
+
+
+ If a conflicting valid row has been deleted by the current transaction,
+ it's okay. (In particular, since an UPDATE always deletes the old row
+ version before inserting the new version, this will allow an UPDATE on
+ a row without changing the key.)
+
+ If a conflicting row has been inserted by an as-yet-uncommitted
+ transaction, the would-be inserter must wait to see if that transaction
+ commits. If it rolls back then there is no conflict. If it commits
+ without deleting the conflicting row again, there is a uniqueness
+ violation. (In practice we just wait for the other transaction to
+ end and then redo the visibility check in toto.)
+
+ Similarly, if a conflicting valid row has been deleted by an
+ as-yet-uncommitted transaction, the would-be inserter must wait
+ for that transaction to commit or abort, and then repeat the test.
+
+
+ Furthermore, immediately before reporting a uniqueness violation
+ according to the above rules, the access method must recheck the
+ liveness of the row being inserted. If it is committed dead then
+ no violation should be reported. (This case cannot occur during the
+ ordinary scenario of inserting a row that's just been created by
+ the current transaction. It can happen during
+ CREATE UNIQUE INDEX CONCURRENTLY, however.)
+
+ We require the index access method to apply these tests itself, which
+ means that it must reach into the heap to check the commit status of
+ any row that is shown to have a duplicate key according to the index
+ contents. This is without a doubt ugly and non-modular, but it saves
+ redundant work: if we did a separate probe then the index lookup for
+ a conflicting row would be essentially repeated while finding the place to
+ insert the new row's index entry. What's more, there is no obvious way
+ to avoid race conditions unless the conflict check is an integral part
+ of insertion of the new index entry.
+
+ If the unique constraint is deferrable, there is additional complexity:
+ we need to be able to insert an index entry for a new row, but defer any
+ uniqueness-violation error until end of statement or even later. To
+ avoid unnecessary repeat searches of the index, the index access method
+ should do a preliminary uniqueness check during the initial insertion.
+ If this shows that there is definitely no conflicting live tuple, we
+ are done. Otherwise, we schedule a recheck to occur when it is time to
+ enforce the constraint. If, at the time of the recheck, both the inserted
+ tuple and some other tuple with the same key are live, then the error
+ must be reported. (Note that for this purpose, “live” actually
+ means “any tuple in the index entry's HOT chain is live”.)
+ To implement this, the aminsert function is passed a
+ checkUnique parameter having one of the following values:
+
+
+ UNIQUE_CHECK_NO indicates that no uniqueness checking
+ should be done (this is not a unique index).
+
+ UNIQUE_CHECK_YES indicates that this is a non-deferrable
+ unique index, and the uniqueness check must be done immediately, as
+ described above.
+
+ UNIQUE_CHECK_PARTIAL indicates that the unique
+ constraint is deferrable. PostgreSQL
+ will use this mode to insert each row's index entry. The access
+ method must allow duplicate entries into the index, and report any
+ potential duplicates by returning false from aminsert.
+ For each row for which false is returned, a deferred recheck will
+ be scheduled.
+
+ The access method must identify any rows which might violate the
+ unique constraint, but it is not an error for it to report false
+ positives. This allows the check to be done without waiting for other
+ transactions to finish; conflicts reported here are not treated as
+ errors and will be rechecked later, by which time they may no longer
+ be conflicts.
+
+ UNIQUE_CHECK_EXISTING indicates that this is a deferred
+ recheck of a row that was reported as a potential uniqueness violation.
+ Although this is implemented by calling aminsert, the
+ access method must not insert a new index entry in this
+ case. The index entry is already present. Rather, the access method
+ must check to see if there is another live index entry. If so, and
+ if the target row is also still live, report error.
+
+ It is recommended that in a UNIQUE_CHECK_EXISTING call,
+ the access method further verify that the target row actually does
+ have an existing entry in the index, and report error if not. This
+ is a good idea because the index tuple values passed to
+ aminsert will have been recomputed. If the index
+ definition involves functions that are not really immutable, we
+ might be checking the wrong area of the index. Checking that the
+ target row is found in the recheck verifies that we are scanning
+ for the same tuple values as were used in the original insertion.
+
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/index.html b/pgsql/doc/postgresql/html/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..5845414375bbe5fbd7c020c6252c9b3489362c88
--- /dev/null
+++ b/pgsql/doc/postgresql/html/index.html
@@ -0,0 +1,2 @@
+
+PostgreSQL 16.3 Documentation
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/indexam.html b/pgsql/doc/postgresql/html/indexam.html
new file mode 100644
index 0000000000000000000000000000000000000000..944d1c48daee4e5f23a90604b12d5fcdbe40d3fb
--- /dev/null
+++ b/pgsql/doc/postgresql/html/indexam.html
@@ -0,0 +1,35 @@
+
+Chapter 64. Index Access Method Interface Definition
Chapter 64. Index Access Method Interface Definition
+ This chapter defines the interface between the core
+ PostgreSQL system and index access
+ methods, which manage individual index types. The core system
+ knows nothing about indexes beyond what is specified here, so it is
+ possible to develop entirely new index types by writing add-on code.
+
+ All indexes in PostgreSQL are what are known
+ technically as secondary indexes; that is, the index is
+ physically separate from the table file that it describes. Each index
+ is stored as its own physical relation and so is described
+ by an entry in the pg_class catalog. The contents of an
+ index are entirely under the control of its index access method. In
+ practice, all index access methods divide indexes into standard-size
+ pages so that they can use the regular storage manager and buffer manager
+ to access the index contents. (All the existing index access methods
+ furthermore use the standard page layout described in Section 73.6, and most use the same format for index
+ tuple headers; but these decisions are not forced on an access method.)
+
+ An index is effectively a mapping from some data key values to
+ tuple identifiers, or TIDs, of row versions
+ (tuples) in the index's parent table. A TID consists of a
+ block number and an item number within that block (see Section 73.6). This is sufficient
+ information to fetch a particular row version from the table.
+ Indexes are not directly aware that under MVCC, there might be multiple
+ extant versions of the same logical row; to an index, each tuple is
+ an independent object that needs its own index entry. Thus, an
+ update of a row always creates all-new index entries for the row, even if
+ the key values did not change. (HOT
+ tuples are an exception to this
+ statement; but indexes do not deal with those, either.) Index entries for
+ dead tuples are reclaimed (by vacuuming) when the dead tuples themselves
+ are reclaimed.
+
\ No newline at end of file
diff --git a/pgsql/doc/postgresql/html/indexes-bitmap-scans.html b/pgsql/doc/postgresql/html/indexes-bitmap-scans.html
new file mode 100644
index 0000000000000000000000000000000000000000..931dcca433d550e12b7b58baa49c89e0613cccda
--- /dev/null
+++ b/pgsql/doc/postgresql/html/indexes-bitmap-scans.html
@@ -0,0 +1,61 @@
+
+11.5. Combining Multiple Indexes
+ A single index scan can only use query clauses that use the index's
+ columns with operators of its operator class and are joined with
+ AND. For example, given an index on (a, b)
+ a query condition like WHERE a = 5 AND b = 6 could
+ use the index, but a query like WHERE a = 5 OR b = 6 could not
+ directly use the index.
+
+ Fortunately,
+ PostgreSQL has the ability to combine multiple indexes
+ (including multiple uses of the same index) to handle cases that cannot
+ be implemented by single index scans. The system can form AND
+ and OR conditions across several index scans. For example,
+ a query like WHERE x = 42 OR x = 47 OR x = 53 OR x = 99
+ could be broken down into four separate scans of an index on x,
+ each scan using one of the query clauses. The results of these scans are
+ then ORed together to produce the result. Another example is that if we
+ have separate indexes on x and y, one possible
+ implementation of a query like WHERE x = 5 AND y = 6 is to
+ use each index with the appropriate query clause and then AND together
+ the index results to identify the result rows.
+
+ To combine multiple indexes, the system scans each needed index and
+ prepares a bitmap in memory giving the locations of
+ table rows that are reported as matching that index's conditions.
+ The bitmaps are then ANDed and ORed together as needed by the query.
+ Finally, the actual table rows are visited and returned. The table rows
+ are visited in physical order, because that is how the bitmap is laid
+ out; this means that any ordering of the original indexes is lost, and
+ so a separate sort step will be needed if the query has an ORDER
+ BY clause. For this reason, and because each additional index scan
+ adds extra time, the planner will sometimes choose to use a simple index
+ scan even though additional indexes are available that could have been
+ used as well.
+
+ In all but the simplest applications, there are various combinations of
+ indexes that might be useful, and the database developer must make
+ trade-offs to decide which indexes to provide. Sometimes multicolumn
+ indexes are best, but sometimes it's better to create separate indexes
+ and rely on the index-combination feature. For example, if your
+ workload includes a mix of queries that sometimes involve only column
+ x, sometimes only column y, and sometimes both
+ columns, you might choose to create two separate indexes on
+ x and y, relying on index combination to
+ process the queries that use both columns. You could also create a
+ multicolumn index on (x, y). This index would typically be
+ more efficient than index combination for queries involving both
+ columns, but as discussed in Section 11.3, it
+ would be almost useless for queries involving only y, so it
+ should not be the only index. A combination of the multicolumn index
+ and a separate index on y would serve reasonably well. For
+ queries involving only x, the multicolumn index could be
+ used, though it would be larger and hence slower than an index on
+ x alone. The last alternative is to create all three
+ indexes, but this is probably only reasonable if the table is searched
+ much more often than it is updated and all three types of query are
+ common. If one of the types of query is much less common than the
+ others, you'd probably settle for creating just the two indexes that
+ best match the common types.
+
*/
+ bool default_footer; /* allow "(xx rows)" default footer */
+ unsigned long prior_records; /* start offset for record counters */
+ const printTextFormat *line_style; /* line style (NULL for default) */
+ struct separator fieldSep; /* field separator for unaligned text mode */
+ struct separator recordSep; /* record separator for unaligned text mode */
+ char csvFieldSep[2]; /* field separator for csv format */
+ bool numericLocale; /* locale-aware numeric units separator and
+ * decimal marker */
+ char *tableAttr; /* attributes for HTML
*/
+ int encoding; /* character encoding */
+ int env_columns; /* $COLUMNS on psql start, 0 is unset */
+ int columns; /* target width for wrapped format */
+ unicode_linestyle unicode_border_linestyle;
+ unicode_linestyle unicode_column_linestyle;
+ unicode_linestyle unicode_header_linestyle;
+} printTableOpt;
+
+/*
+ * Table footers are implemented as a singly-linked list.
+ *
+ * This is so that you don't need to know the number of footers in order to
+ * initialise the printTableContent struct, which is very convenient when
+ * preparing complex footers (as in describeOneTableDetails).
+ */
+typedef struct printTableFooter
+{
+ char *data;
+ struct printTableFooter *next;
+} printTableFooter;
+
+/*
+ * The table content struct holds all the information which will be displayed
+ * by printTable().
+ */
+typedef struct printTableContent
+{
+ const printTableOpt *opt;
+ const char *title; /* May be NULL */
+ int ncolumns; /* Specified in Init() */
+ int nrows; /* Specified in Init() */
+ const char **headers; /* NULL-terminated array of header strings */
+ const char **header; /* Pointer to the last added header */
+ const char **cells; /* NULL-terminated array of cell content
+ * strings */
+ const char **cell; /* Pointer to the last added cell */
+ long cellsadded; /* Number of cells added this far */
+ bool *cellmustfree; /* true for cells that need to be free()d */
+ printTableFooter *footers; /* Pointer to the first footer */
+ printTableFooter *footer; /* Pointer to the last added footer */
+ char *aligns; /* Array of alignment specifiers; 'l' or 'r',
+ * one per column */
+ char *align; /* Pointer to the last added alignment */
+} printTableContent;
+
+typedef struct printQueryOpt
+{
+ printTableOpt topt; /* the options above */
+ char *nullPrint; /* how to print null entities */
+ char *title; /* override title */
+ char **footers; /* override footer (default is "(xx rows)") */
+ bool translate_header; /* do gettext on column headers */
+ const bool *translate_columns; /* translate_columns[i-1] => do gettext on
+ * col i */
+ int n_translate_columns; /* length of translate_columns[] */
+} printQueryOpt;
+
+
+extern PGDLLIMPORT volatile sig_atomic_t cancel_pressed;
+
+extern PGDLLIMPORT const printTextFormat pg_asciiformat;
+extern PGDLLIMPORT const printTextFormat pg_asciiformat_old;
+extern PGDLLIMPORT printTextFormat pg_utf8format; /* ideally would be const,
+ * but... */
+
+
+extern void disable_sigpipe_trap(void);
+extern void restore_sigpipe_trap(void);
+extern void set_sigpipe_trap_state(bool ignore);
+
+extern FILE *PageOutput(int lines, const printTableOpt *topt);
+extern void ClosePager(FILE *pagerpipe);
+
+extern void html_escaped_print(const char *in, FILE *fout);
+
+extern void printTableInit(printTableContent *const content,
+ const printTableOpt *opt, const char *title,
+ const int ncolumns, const int nrows);
+extern void printTableAddHeader(printTableContent *const content,
+ char *header, const bool translate, const char align);
+extern void printTableAddCell(printTableContent *const content,
+ char *cell, const bool translate, const bool mustfree);
+extern void printTableAddFooter(printTableContent *const content,
+ const char *footer);
+extern void printTableSetFooter(printTableContent *const content,
+ const char *footer);
+extern void printTableCleanup(printTableContent *const content);
+extern void printTable(const printTableContent *cont,
+ FILE *fout, bool is_pager, FILE *flog);
+extern void printQuery(const PGresult *result, const printQueryOpt *opt,
+ FILE *fout, bool is_pager, FILE *flog);
+
+extern char column_type_alignment(Oid);
+
+extern void setDecimalLocale(void);
+extern const printTextFormat *get_line_style(const printTableOpt *opt);
+extern void refresh_utf8format(const printTableOpt *opt);
+
+#endif /* PRINT_H */
diff --git a/pgsql/include/server/fe_utils/psqlscan.h b/pgsql/include/server/fe_utils/psqlscan.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a90fcab9ebe5e1fec71f3778a34175bf1abc9fd
--- /dev/null
+++ b/pgsql/include/server/fe_utils/psqlscan.h
@@ -0,0 +1,90 @@
+/*-------------------------------------------------------------------------
+ *
+ * psqlscan.h
+ * lexical scanner for SQL commands
+ *
+ * This lexer used to be part of psql, and that heritage is reflected in
+ * the file name as well as function and typedef names, though it can now
+ * be used by other frontend programs as well. It's also possible to extend
+ * this lexer with a compatible add-on lexer to handle program-specific
+ * backslash commands.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/fe_utils/psqlscan.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PSQLSCAN_H
+#define PSQLSCAN_H
+
+#include "pqexpbuffer.h"
+
+
+/* Abstract type for lexer's internal state */
+typedef struct PsqlScanStateData *PsqlScanState;
+
+/* Termination states for psql_scan() */
+typedef enum
+{
+ PSCAN_SEMICOLON, /* found command-ending semicolon */
+ PSCAN_BACKSLASH, /* found backslash command */
+ PSCAN_INCOMPLETE, /* end of line, SQL statement incomplete */
+ PSCAN_EOL /* end of line, SQL possibly complete */
+} PsqlScanResult;
+
+/* Prompt type returned by psql_scan() */
+typedef enum _promptStatus
+{
+ PROMPT_READY,
+ PROMPT_CONTINUE,
+ PROMPT_COMMENT,
+ PROMPT_SINGLEQUOTE,
+ PROMPT_DOUBLEQUOTE,
+ PROMPT_DOLLARQUOTE,
+ PROMPT_PAREN,
+ PROMPT_COPY
+} promptStatus_t;
+
+/* Quoting request types for get_variable() callback */
+typedef enum
+{
+ PQUOTE_PLAIN, /* just return the actual value */
+ PQUOTE_SQL_LITERAL, /* add quotes to make a valid SQL literal */
+ PQUOTE_SQL_IDENT, /* quote if needed to make a SQL identifier */
+ PQUOTE_SHELL_ARG /* quote if needed to be safe in a shell cmd */
+} PsqlScanQuoteType;
+
+/* Callback functions to be used by the lexer */
+typedef struct PsqlScanCallbacks
+{
+ /* Fetch value of a variable, as a free'able string; NULL if unknown */
+ /* This pointer can be NULL if no variable substitution is wanted */
+ char *(*get_variable) (const char *varname, PsqlScanQuoteType quote,
+ void *passthrough);
+} PsqlScanCallbacks;
+
+
+extern PsqlScanState psql_scan_create(const PsqlScanCallbacks *callbacks);
+extern void psql_scan_destroy(PsqlScanState state);
+
+extern void psql_scan_set_passthrough(PsqlScanState state, void *passthrough);
+
+extern void psql_scan_setup(PsqlScanState state,
+ const char *line, int line_len,
+ int encoding, bool std_strings);
+extern void psql_scan_finish(PsqlScanState state);
+
+extern PsqlScanResult psql_scan(PsqlScanState state,
+ PQExpBuffer query_buf,
+ promptStatus_t *prompt);
+
+extern void psql_scan_reset(PsqlScanState state);
+
+extern void psql_scan_reselect_sql_lexer(PsqlScanState state);
+
+extern bool psql_scan_in_quote(PsqlScanState state);
+
+#endif /* PSQLSCAN_H */
diff --git a/pgsql/include/server/fe_utils/psqlscan_int.h b/pgsql/include/server/fe_utils/psqlscan_int.h
new file mode 100644
index 0000000000000000000000000000000000000000..373e7e147631310d1f9d31b70406babd0f7771fd
--- /dev/null
+++ b/pgsql/include/server/fe_utils/psqlscan_int.h
@@ -0,0 +1,157 @@
+/*-------------------------------------------------------------------------
+ *
+ * psqlscan_int.h
+ * lexical scanner internal declarations
+ *
+ * This file declares the PsqlScanStateData structure used by psqlscan.l
+ * and shared by other lexers compatible with it, such as psqlscanslash.l.
+ *
+ * One difficult aspect of this code is that we need to work in multibyte
+ * encodings that are not ASCII-safe. A "safe" encoding is one in which each
+ * byte of a multibyte character has the high bit set (it's >= 0x80). Since
+ * all our lexing rules treat all high-bit-set characters alike, we don't
+ * really need to care whether such a byte is part of a sequence or not.
+ * In an "unsafe" encoding, we still expect the first byte of a multibyte
+ * sequence to be >= 0x80, but later bytes might not be. If we scan such
+ * a sequence as-is, the lexing rules could easily be fooled into matching
+ * such bytes to ordinary ASCII characters. Our solution for this is to
+ * substitute 0xFF for each non-first byte within the data presented to flex.
+ * The flex rules will then pass the FF's through unmolested. The
+ * psqlscan_emit() subroutine is responsible for looking back to the original
+ * string and replacing FF's with the corresponding original bytes.
+ *
+ * Another interesting thing we do here is scan different parts of the same
+ * input with physically separate flex lexers (ie, lexers written in separate
+ * .l files). We can get away with this because the only part of the
+ * persistent state of a flex lexer that depends on its parsing rule tables
+ * is the start state number, which is easy enough to manage --- usually,
+ * in fact, we just need to set it to INITIAL when changing lexers. But to
+ * make that work at all, we must use re-entrant lexers, so that all the
+ * relevant state is in the yyscan_t attached to the PsqlScanState;
+ * if we were using lexers with separate static state we would soon end up
+ * with dangling buffer pointers in one or the other. Also note that this
+ * is unlikely to work very nicely if the lexers aren't all built with the
+ * same flex version, or if they don't use the same flex options.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/fe_utils/psqlscan_int.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PSQLSCAN_INT_H
+#define PSQLSCAN_INT_H
+
+#include "fe_utils/psqlscan.h"
+
+/*
+ * These are just to allow this file to be compilable standalone for header
+ * validity checking; in actual use, this file should always be included
+ * from the body of a flex file, where these symbols are already defined.
+ */
+#ifndef YY_TYPEDEF_YY_BUFFER_STATE
+#define YY_TYPEDEF_YY_BUFFER_STATE
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+#endif
+#ifndef YY_TYPEDEF_YY_SCANNER_T
+#define YY_TYPEDEF_YY_SCANNER_T
+typedef void *yyscan_t;
+#endif
+
+/*
+ * We use a stack of flex buffers to handle substitution of psql variables.
+ * Each stacked buffer contains the as-yet-unread text from one psql variable.
+ * When we pop the stack all the way, we resume reading from the outer buffer
+ * identified by scanbufhandle.
+ */
+typedef struct StackElem
+{
+ YY_BUFFER_STATE buf; /* flex input control structure */
+ char *bufstring; /* data actually being scanned by flex */
+ char *origstring; /* copy of original data, if needed */
+ char *varname; /* name of variable providing data, or NULL */
+ struct StackElem *next;
+} StackElem;
+
+/*
+ * All working state of the lexer must be stored in PsqlScanStateData
+ * between calls. This allows us to have multiple open lexer operations,
+ * which is needed for nested include files. The lexer itself is not
+ * recursive, but it must be re-entrant.
+ */
+typedef struct PsqlScanStateData
+{
+ yyscan_t scanner; /* Flex's state for this PsqlScanState */
+
+ PQExpBuffer output_buf; /* current output buffer */
+
+ StackElem *buffer_stack; /* stack of variable expansion buffers */
+
+ /*
+ * These variables always refer to the outer buffer, never to any stacked
+ * variable-expansion buffer.
+ */
+ YY_BUFFER_STATE scanbufhandle;
+ char *scanbuf; /* start of outer-level input buffer */
+ const char *scanline; /* current input line at outer level */
+
+ /* safe_encoding, curline, refline are used by emit() to replace FFs */
+ int encoding; /* encoding being used now */
+ bool safe_encoding; /* is current encoding "safe"? */
+ bool std_strings; /* are string literals standard? */
+ const char *curline; /* actual flex input string for cur buf */
+ const char *refline; /* original data for cur buffer */
+
+ /*
+ * All this state lives across successive input lines, until explicitly
+ * reset by psql_scan_reset. start_state is adopted by yylex() on entry,
+ * and updated with its finishing state on exit.
+ */
+ int start_state; /* yylex's starting/finishing state */
+ int state_before_str_stop; /* start cond. before end quote */
+ int paren_depth; /* depth of nesting in parentheses */
+ int xcdepth; /* depth of nesting in slash-star comments */
+ char *dolqstart; /* current $foo$ quote start string */
+
+ /*
+ * State to track boundaries of BEGIN ... END blocks in function
+ * definitions, so that semicolons do not send query too early.
+ */
+ int identifier_count; /* identifiers since start of statement */
+ char identifiers[4]; /* records the first few identifiers */
+ int begin_depth; /* depth of begin/end pairs */
+
+ /*
+ * Callback functions provided by the program making use of the lexer,
+ * plus a void* callback passthrough argument.
+ */
+ const PsqlScanCallbacks *callbacks;
+ void *cb_passthrough;
+} PsqlScanStateData;
+
+
+/*
+ * Functions exported by psqlscan.l, but only meant for use within
+ * compatible lexers.
+ */
+extern void psqlscan_push_new_buffer(PsqlScanState state,
+ const char *newstr, const char *varname);
+extern void psqlscan_pop_buffer_stack(PsqlScanState state);
+extern void psqlscan_select_top_buffer(PsqlScanState state);
+extern bool psqlscan_var_is_current_source(PsqlScanState state,
+ const char *varname);
+extern YY_BUFFER_STATE psqlscan_prepare_buffer(PsqlScanState state,
+ const char *txt, int len,
+ char **txtcopy);
+extern void psqlscan_emit(PsqlScanState state, const char *txt, int len);
+extern char *psqlscan_extract_substring(PsqlScanState state,
+ const char *txt, int len);
+extern void psqlscan_escape_variable(PsqlScanState state,
+ const char *txt, int len,
+ PsqlScanQuoteType quote);
+extern void psqlscan_test_variable(PsqlScanState state,
+ const char *txt, int len);
+
+#endif /* PSQLSCAN_INT_H */
diff --git a/pgsql/include/server/fe_utils/query_utils.h b/pgsql/include/server/fe_utils/query_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..e461df9e5c566d3725e08daaa3231d8c6b5cfe58
--- /dev/null
+++ b/pgsql/include/server/fe_utils/query_utils.h
@@ -0,0 +1,26 @@
+/*-------------------------------------------------------------------------
+ *
+ * Facilities for frontend code to query a databases.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/fe_utils/query_utils.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef QUERY_UTILS_H
+#define QUERY_UTILS_H
+
+#include "postgres_fe.h"
+
+#include "libpq-fe.h"
+
+extern PGresult *executeQuery(PGconn *conn, const char *query, bool echo);
+
+extern void executeCommand(PGconn *conn, const char *query, bool echo);
+
+extern bool executeMaintenanceCommand(PGconn *conn, const char *query,
+ bool echo);
+
+#endif /* QUERY_UTILS_H */
diff --git a/pgsql/include/server/fe_utils/recovery_gen.h b/pgsql/include/server/fe_utils/recovery_gen.h
new file mode 100644
index 0000000000000000000000000000000000000000..8fe567563566d2e2ff403f40031b6fa2dd5a8b04
--- /dev/null
+++ b/pgsql/include/server/fe_utils/recovery_gen.h
@@ -0,0 +1,28 @@
+/*-------------------------------------------------------------------------
+ *
+ * Generator for recovery configuration
+ *
+ * Portions Copyright (c) 2011-2023, PostgreSQL Global Development Group
+ *
+ * src/include/fe_utils/recovery_gen.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RECOVERY_GEN_H
+#define RECOVERY_GEN_H
+
+#include "libpq-fe.h"
+#include "pqexpbuffer.h"
+
+/*
+ * recovery configuration is part of postgresql.conf in version 12 and up, and
+ * in recovery.conf before that.
+ */
+#define MINIMUM_VERSION_FOR_RECOVERY_GUC 120000
+
+extern PQExpBuffer GenerateRecoveryConfig(PGconn *pgconn,
+ char *replication_slot);
+extern void WriteRecoveryConfig(PGconn *pgconn, char *target_dir,
+ PQExpBuffer contents);
+
+#endif /* RECOVERY_GEN_H */
diff --git a/pgsql/include/server/fe_utils/simple_list.h b/pgsql/include/server/fe_utils/simple_list.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f87138654bf2d51222d2241a2aa838600511e55
--- /dev/null
+++ b/pgsql/include/server/fe_utils/simple_list.h
@@ -0,0 +1,70 @@
+/*-------------------------------------------------------------------------
+ *
+ * Simple list facilities for frontend code
+ *
+ * Data structures for simple lists of OIDs, strings, and pointers. The
+ * support for these is very primitive compared to the backend's List
+ * facilities, but it's all we need in, eg, pg_dump.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/fe_utils/simple_list.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SIMPLE_LIST_H
+#define SIMPLE_LIST_H
+
+typedef struct SimpleOidListCell
+{
+ struct SimpleOidListCell *next;
+ Oid val;
+} SimpleOidListCell;
+
+typedef struct SimpleOidList
+{
+ SimpleOidListCell *head;
+ SimpleOidListCell *tail;
+} SimpleOidList;
+
+typedef struct SimpleStringListCell
+{
+ struct SimpleStringListCell *next;
+ bool touched; /* true, when this string was searched and
+ * touched */
+ char val[FLEXIBLE_ARRAY_MEMBER]; /* null-terminated string here */
+} SimpleStringListCell;
+
+typedef struct SimpleStringList
+{
+ SimpleStringListCell *head;
+ SimpleStringListCell *tail;
+} SimpleStringList;
+
+typedef struct SimplePtrListCell
+{
+ struct SimplePtrListCell *next;
+ void *ptr;
+} SimplePtrListCell;
+
+typedef struct SimplePtrList
+{
+ SimplePtrListCell *head;
+ SimplePtrListCell *tail;
+} SimplePtrList;
+
+extern void simple_oid_list_append(SimpleOidList *list, Oid val);
+extern bool simple_oid_list_member(SimpleOidList *list, Oid val);
+extern void simple_oid_list_destroy(SimpleOidList *list);
+
+extern void simple_string_list_append(SimpleStringList *list, const char *val);
+extern bool simple_string_list_member(SimpleStringList *list, const char *val);
+extern void simple_string_list_destroy(SimpleStringList *list);
+
+extern const char *simple_string_list_not_touched(SimpleStringList *list);
+
+extern void simple_ptr_list_append(SimplePtrList *list, void *ptr);
+
+#endif /* SIMPLE_LIST_H */
diff --git a/pgsql/include/server/fe_utils/string_utils.h b/pgsql/include/server/fe_utils/string_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..e10c9090754cc2236279c79f4a55e1723af1bcb6
--- /dev/null
+++ b/pgsql/include/server/fe_utils/string_utils.h
@@ -0,0 +1,66 @@
+/*-------------------------------------------------------------------------
+ *
+ * String-processing utility routines for frontend code
+ *
+ * Utility functions that interpret backend output or quote strings for
+ * assorted contexts.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/fe_utils/string_utils.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef STRING_UTILS_H
+#define STRING_UTILS_H
+
+#include "libpq-fe.h"
+#include "pqexpbuffer.h"
+
+/* Global variables controlling behavior of fmtId() and fmtQualifiedId() */
+extern PGDLLIMPORT int quote_all_identifiers;
+extern PQExpBuffer (*getLocalPQExpBuffer) (void);
+
+/* Functions */
+extern const char *fmtId(const char *rawid);
+extern const char *fmtQualifiedId(const char *schema, const char *id);
+
+extern char *formatPGVersionNumber(int version_number, bool include_minor,
+ char *buf, size_t buflen);
+
+extern void appendStringLiteral(PQExpBuffer buf, const char *str,
+ int encoding, bool std_strings);
+extern void appendStringLiteralConn(PQExpBuffer buf, const char *str,
+ PGconn *conn);
+extern void appendStringLiteralDQ(PQExpBuffer buf, const char *str,
+ const char *dqprefix);
+extern void appendByteaLiteral(PQExpBuffer buf,
+ const unsigned char *str, size_t length,
+ bool std_strings);
+
+extern void appendShellString(PQExpBuffer buf, const char *str);
+extern bool appendShellStringNoError(PQExpBuffer buf, const char *str);
+extern void appendConnStrVal(PQExpBuffer buf, const char *str);
+extern void appendPsqlMetaConnect(PQExpBuffer buf, const char *dbname);
+
+extern bool parsePGArray(const char *atext, char ***itemarray, int *nitems);
+extern void appendPGArray(PQExpBuffer buffer, const char *value);
+
+extern bool appendReloptionsArray(PQExpBuffer buffer, const char *reloptions,
+ const char *prefix, int encoding, bool std_strings);
+
+extern bool processSQLNamePattern(PGconn *conn, PQExpBuffer buf,
+ const char *pattern,
+ bool have_where, bool force_escape,
+ const char *schemavar, const char *namevar,
+ const char *altnamevar, const char *visibilityrule,
+ PQExpBuffer dbnamebuf, int *dotcnt);
+
+extern void patternToSQLRegex(int encoding, PQExpBuffer dbnamebuf,
+ PQExpBuffer schemabuf, PQExpBuffer namebuf,
+ const char *pattern, bool force_escape,
+ bool want_literal_dbname, int *dotcnt);
+
+#endif /* STRING_UTILS_H */
diff --git a/pgsql/include/server/foreign/fdwapi.h b/pgsql/include/server/foreign/fdwapi.h
new file mode 100644
index 0000000000000000000000000000000000000000..996c62e3055912d75e541ece289f003387d01435
--- /dev/null
+++ b/pgsql/include/server/foreign/fdwapi.h
@@ -0,0 +1,294 @@
+/*-------------------------------------------------------------------------
+ *
+ * fdwapi.h
+ * API for foreign-data wrappers
+ *
+ * Copyright (c) 2010-2023, PostgreSQL Global Development Group
+ *
+ * src/include/foreign/fdwapi.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FDWAPI_H
+#define FDWAPI_H
+
+#include "access/parallel.h"
+#include "nodes/execnodes.h"
+#include "nodes/pathnodes.h"
+
+/* To avoid including explain.h here, reference ExplainState thus: */
+struct ExplainState;
+
+
+/*
+ * Callback function signatures --- see fdwhandler.sgml for more info.
+ */
+
+typedef void (*GetForeignRelSize_function) (PlannerInfo *root,
+ RelOptInfo *baserel,
+ Oid foreigntableid);
+
+typedef void (*GetForeignPaths_function) (PlannerInfo *root,
+ RelOptInfo *baserel,
+ Oid foreigntableid);
+
+typedef ForeignScan *(*GetForeignPlan_function) (PlannerInfo *root,
+ RelOptInfo *baserel,
+ Oid foreigntableid,
+ ForeignPath *best_path,
+ List *tlist,
+ List *scan_clauses,
+ Plan *outer_plan);
+
+typedef void (*BeginForeignScan_function) (ForeignScanState *node,
+ int eflags);
+
+typedef TupleTableSlot *(*IterateForeignScan_function) (ForeignScanState *node);
+
+typedef bool (*RecheckForeignScan_function) (ForeignScanState *node,
+ TupleTableSlot *slot);
+
+typedef void (*ReScanForeignScan_function) (ForeignScanState *node);
+
+typedef void (*EndForeignScan_function) (ForeignScanState *node);
+
+typedef void (*GetForeignJoinPaths_function) (PlannerInfo *root,
+ RelOptInfo *joinrel,
+ RelOptInfo *outerrel,
+ RelOptInfo *innerrel,
+ JoinType jointype,
+ JoinPathExtraData *extra);
+
+typedef void (*GetForeignUpperPaths_function) (PlannerInfo *root,
+ UpperRelationKind stage,
+ RelOptInfo *input_rel,
+ RelOptInfo *output_rel,
+ void *extra);
+
+typedef void (*AddForeignUpdateTargets_function) (PlannerInfo *root,
+ Index rtindex,
+ RangeTblEntry *target_rte,
+ Relation target_relation);
+
+typedef List *(*PlanForeignModify_function) (PlannerInfo *root,
+ ModifyTable *plan,
+ Index resultRelation,
+ int subplan_index);
+
+typedef void (*BeginForeignModify_function) (ModifyTableState *mtstate,
+ ResultRelInfo *rinfo,
+ List *fdw_private,
+ int subplan_index,
+ int eflags);
+
+typedef TupleTableSlot *(*ExecForeignInsert_function) (EState *estate,
+ ResultRelInfo *rinfo,
+ TupleTableSlot *slot,
+ TupleTableSlot *planSlot);
+
+typedef TupleTableSlot **(*ExecForeignBatchInsert_function) (EState *estate,
+ ResultRelInfo *rinfo,
+ TupleTableSlot **slots,
+ TupleTableSlot **planSlots,
+ int *numSlots);
+
+typedef int (*GetForeignModifyBatchSize_function) (ResultRelInfo *rinfo);
+
+typedef TupleTableSlot *(*ExecForeignUpdate_function) (EState *estate,
+ ResultRelInfo *rinfo,
+ TupleTableSlot *slot,
+ TupleTableSlot *planSlot);
+
+typedef TupleTableSlot *(*ExecForeignDelete_function) (EState *estate,
+ ResultRelInfo *rinfo,
+ TupleTableSlot *slot,
+ TupleTableSlot *planSlot);
+
+typedef void (*EndForeignModify_function) (EState *estate,
+ ResultRelInfo *rinfo);
+
+typedef void (*BeginForeignInsert_function) (ModifyTableState *mtstate,
+ ResultRelInfo *rinfo);
+
+typedef void (*EndForeignInsert_function) (EState *estate,
+ ResultRelInfo *rinfo);
+
+typedef int (*IsForeignRelUpdatable_function) (Relation rel);
+
+typedef bool (*PlanDirectModify_function) (PlannerInfo *root,
+ ModifyTable *plan,
+ Index resultRelation,
+ int subplan_index);
+
+typedef void (*BeginDirectModify_function) (ForeignScanState *node,
+ int eflags);
+
+typedef TupleTableSlot *(*IterateDirectModify_function) (ForeignScanState *node);
+
+typedef void (*EndDirectModify_function) (ForeignScanState *node);
+
+typedef RowMarkType (*GetForeignRowMarkType_function) (RangeTblEntry *rte,
+ LockClauseStrength strength);
+
+typedef void (*RefetchForeignRow_function) (EState *estate,
+ ExecRowMark *erm,
+ Datum rowid,
+ TupleTableSlot *slot,
+ bool *updated);
+
+typedef void (*ExplainForeignScan_function) (ForeignScanState *node,
+ struct ExplainState *es);
+
+typedef void (*ExplainForeignModify_function) (ModifyTableState *mtstate,
+ ResultRelInfo *rinfo,
+ List *fdw_private,
+ int subplan_index,
+ struct ExplainState *es);
+
+typedef void (*ExplainDirectModify_function) (ForeignScanState *node,
+ struct ExplainState *es);
+
+typedef int (*AcquireSampleRowsFunc) (Relation relation, int elevel,
+ HeapTuple *rows, int targrows,
+ double *totalrows,
+ double *totaldeadrows);
+
+typedef bool (*AnalyzeForeignTable_function) (Relation relation,
+ AcquireSampleRowsFunc *func,
+ BlockNumber *totalpages);
+
+typedef List *(*ImportForeignSchema_function) (ImportForeignSchemaStmt *stmt,
+ Oid serverOid);
+
+typedef void (*ExecForeignTruncate_function) (List *rels,
+ DropBehavior behavior,
+ bool restart_seqs);
+
+typedef Size (*EstimateDSMForeignScan_function) (ForeignScanState *node,
+ ParallelContext *pcxt);
+typedef void (*InitializeDSMForeignScan_function) (ForeignScanState *node,
+ ParallelContext *pcxt,
+ void *coordinate);
+typedef void (*ReInitializeDSMForeignScan_function) (ForeignScanState *node,
+ ParallelContext *pcxt,
+ void *coordinate);
+typedef void (*InitializeWorkerForeignScan_function) (ForeignScanState *node,
+ shm_toc *toc,
+ void *coordinate);
+typedef void (*ShutdownForeignScan_function) (ForeignScanState *node);
+typedef bool (*IsForeignScanParallelSafe_function) (PlannerInfo *root,
+ RelOptInfo *rel,
+ RangeTblEntry *rte);
+typedef List *(*ReparameterizeForeignPathByChild_function) (PlannerInfo *root,
+ List *fdw_private,
+ RelOptInfo *child_rel);
+
+typedef bool (*IsForeignPathAsyncCapable_function) (ForeignPath *path);
+
+typedef void (*ForeignAsyncRequest_function) (AsyncRequest *areq);
+
+typedef void (*ForeignAsyncConfigureWait_function) (AsyncRequest *areq);
+
+typedef void (*ForeignAsyncNotify_function) (AsyncRequest *areq);
+
+/*
+ * FdwRoutine is the struct returned by a foreign-data wrapper's handler
+ * function. It provides pointers to the callback functions needed by the
+ * planner and executor.
+ *
+ * More function pointers are likely to be added in the future. Therefore
+ * it's recommended that the handler initialize the struct with
+ * makeNode(FdwRoutine) so that all fields are set to NULL. This will
+ * ensure that no fields are accidentally left undefined.
+ */
+typedef struct FdwRoutine
+{
+ NodeTag type;
+
+ /* Functions for scanning foreign tables */
+ GetForeignRelSize_function GetForeignRelSize;
+ GetForeignPaths_function GetForeignPaths;
+ GetForeignPlan_function GetForeignPlan;
+ BeginForeignScan_function BeginForeignScan;
+ IterateForeignScan_function IterateForeignScan;
+ ReScanForeignScan_function ReScanForeignScan;
+ EndForeignScan_function EndForeignScan;
+
+ /*
+ * Remaining functions are optional. Set the pointer to NULL for any that
+ * are not provided.
+ */
+
+ /* Functions for remote-join planning */
+ GetForeignJoinPaths_function GetForeignJoinPaths;
+
+ /* Functions for remote upper-relation (post scan/join) planning */
+ GetForeignUpperPaths_function GetForeignUpperPaths;
+
+ /* Functions for updating foreign tables */
+ AddForeignUpdateTargets_function AddForeignUpdateTargets;
+ PlanForeignModify_function PlanForeignModify;
+ BeginForeignModify_function BeginForeignModify;
+ ExecForeignInsert_function ExecForeignInsert;
+ ExecForeignBatchInsert_function ExecForeignBatchInsert;
+ GetForeignModifyBatchSize_function GetForeignModifyBatchSize;
+ ExecForeignUpdate_function ExecForeignUpdate;
+ ExecForeignDelete_function ExecForeignDelete;
+ EndForeignModify_function EndForeignModify;
+ BeginForeignInsert_function BeginForeignInsert;
+ EndForeignInsert_function EndForeignInsert;
+ IsForeignRelUpdatable_function IsForeignRelUpdatable;
+ PlanDirectModify_function PlanDirectModify;
+ BeginDirectModify_function BeginDirectModify;
+ IterateDirectModify_function IterateDirectModify;
+ EndDirectModify_function EndDirectModify;
+
+ /* Functions for SELECT FOR UPDATE/SHARE row locking */
+ GetForeignRowMarkType_function GetForeignRowMarkType;
+ RefetchForeignRow_function RefetchForeignRow;
+ RecheckForeignScan_function RecheckForeignScan;
+
+ /* Support functions for EXPLAIN */
+ ExplainForeignScan_function ExplainForeignScan;
+ ExplainForeignModify_function ExplainForeignModify;
+ ExplainDirectModify_function ExplainDirectModify;
+
+ /* Support functions for ANALYZE */
+ AnalyzeForeignTable_function AnalyzeForeignTable;
+
+ /* Support functions for IMPORT FOREIGN SCHEMA */
+ ImportForeignSchema_function ImportForeignSchema;
+
+ /* Support functions for TRUNCATE */
+ ExecForeignTruncate_function ExecForeignTruncate;
+
+ /* Support functions for parallelism under Gather node */
+ IsForeignScanParallelSafe_function IsForeignScanParallelSafe;
+ EstimateDSMForeignScan_function EstimateDSMForeignScan;
+ InitializeDSMForeignScan_function InitializeDSMForeignScan;
+ ReInitializeDSMForeignScan_function ReInitializeDSMForeignScan;
+ InitializeWorkerForeignScan_function InitializeWorkerForeignScan;
+ ShutdownForeignScan_function ShutdownForeignScan;
+
+ /* Support functions for path reparameterization. */
+ ReparameterizeForeignPathByChild_function ReparameterizeForeignPathByChild;
+
+ /* Support functions for asynchronous execution */
+ IsForeignPathAsyncCapable_function IsForeignPathAsyncCapable;
+ ForeignAsyncRequest_function ForeignAsyncRequest;
+ ForeignAsyncConfigureWait_function ForeignAsyncConfigureWait;
+ ForeignAsyncNotify_function ForeignAsyncNotify;
+} FdwRoutine;
+
+
+/* Functions in foreign/foreign.c */
+extern FdwRoutine *GetFdwRoutine(Oid fdwhandler);
+extern Oid GetForeignServerIdByRelId(Oid relid);
+extern FdwRoutine *GetFdwRoutineByServerId(Oid serverid);
+extern FdwRoutine *GetFdwRoutineByRelId(Oid relid);
+extern FdwRoutine *GetFdwRoutineForRelation(Relation relation, bool makecopy);
+extern bool IsImportableForeignTable(const char *tablename,
+ ImportForeignSchemaStmt *stmt);
+extern Path *GetExistingLocalJoinPath(RelOptInfo *joinrel);
+
+#endif /* FDWAPI_H */
diff --git a/pgsql/include/server/foreign/foreign.h b/pgsql/include/server/foreign/foreign.h
new file mode 100644
index 0000000000000000000000000000000000000000..5256d4d91f5b718364e4af97e8250e1256948c56
--- /dev/null
+++ b/pgsql/include/server/foreign/foreign.h
@@ -0,0 +1,85 @@
+/*-------------------------------------------------------------------------
+ *
+ * foreign.h
+ * support for foreign-data wrappers, servers and user mappings.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/foreign/foreign.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FOREIGN_H
+#define FOREIGN_H
+
+#include "nodes/parsenodes.h"
+
+
+/* Helper for obtaining username for user mapping */
+#define MappingUserName(userid) \
+ (OidIsValid(userid) ? GetUserNameFromId(userid, false) : "public")
+
+
+typedef struct ForeignDataWrapper
+{
+ Oid fdwid; /* FDW Oid */
+ Oid owner; /* FDW owner user Oid */
+ char *fdwname; /* Name of the FDW */
+ Oid fdwhandler; /* Oid of handler function, or 0 */
+ Oid fdwvalidator; /* Oid of validator function, or 0 */
+ List *options; /* fdwoptions as DefElem list */
+} ForeignDataWrapper;
+
+typedef struct ForeignServer
+{
+ Oid serverid; /* server Oid */
+ Oid fdwid; /* foreign-data wrapper */
+ Oid owner; /* server owner user Oid */
+ char *servername; /* name of the server */
+ char *servertype; /* server type, optional */
+ char *serverversion; /* server version, optional */
+ List *options; /* srvoptions as DefElem list */
+} ForeignServer;
+
+typedef struct UserMapping
+{
+ Oid umid; /* Oid of user mapping */
+ Oid userid; /* local user Oid */
+ Oid serverid; /* server Oid */
+ List *options; /* useoptions as DefElem list */
+} UserMapping;
+
+typedef struct ForeignTable
+{
+ Oid relid; /* relation Oid */
+ Oid serverid; /* server Oid */
+ List *options; /* ftoptions as DefElem list */
+} ForeignTable;
+
+/* Flags for GetForeignServerExtended */
+#define FSV_MISSING_OK 0x01
+
+/* Flags for GetForeignDataWrapperExtended */
+#define FDW_MISSING_OK 0x01
+
+
+extern ForeignServer *GetForeignServer(Oid serverid);
+extern ForeignServer *GetForeignServerExtended(Oid serverid,
+ bits16 flags);
+extern ForeignServer *GetForeignServerByName(const char *srvname,
+ bool missing_ok);
+extern UserMapping *GetUserMapping(Oid userid, Oid serverid);
+extern ForeignDataWrapper *GetForeignDataWrapper(Oid fdwid);
+extern ForeignDataWrapper *GetForeignDataWrapperExtended(Oid fdwid,
+ bits16 flags);
+extern ForeignDataWrapper *GetForeignDataWrapperByName(const char *fdwname,
+ bool missing_ok);
+extern ForeignTable *GetForeignTable(Oid relid);
+
+extern List *GetForeignColumnOptions(Oid relid, AttrNumber attnum);
+
+extern Oid get_foreign_data_wrapper_oid(const char *fdwname, bool missing_ok);
+extern Oid get_foreign_server_oid(const char *servername, bool missing_ok);
+
+#endif /* FOREIGN_H */
diff --git a/pgsql/include/server/jit/jit.h b/pgsql/include/server/jit/jit.h
new file mode 100644
index 0000000000000000000000000000000000000000..14f2e36b3711b55557ec4270d5a22ee28a384d72
--- /dev/null
+++ b/pgsql/include/server/jit/jit.h
@@ -0,0 +1,105 @@
+/*-------------------------------------------------------------------------
+ * jit.h
+ * Provider independent JIT infrastructure.
+ *
+ * Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * src/include/jit/jit.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef JIT_H
+#define JIT_H
+
+#include "executor/instrument.h"
+#include "utils/resowner.h"
+
+
+/* Flags determining what kind of JIT operations to perform */
+#define PGJIT_NONE 0
+#define PGJIT_PERFORM (1 << 0)
+#define PGJIT_OPT3 (1 << 1)
+#define PGJIT_INLINE (1 << 2)
+#define PGJIT_EXPR (1 << 3)
+#define PGJIT_DEFORM (1 << 4)
+
+
+typedef struct JitInstrumentation
+{
+ /* number of emitted functions */
+ size_t created_functions;
+
+ /* accumulated time to generate code */
+ instr_time generation_counter;
+
+ /* accumulated time for inlining */
+ instr_time inlining_counter;
+
+ /* accumulated time for optimization */
+ instr_time optimization_counter;
+
+ /* accumulated time for code emission */
+ instr_time emission_counter;
+} JitInstrumentation;
+
+/*
+ * DSM structure for accumulating jit instrumentation of all workers.
+ */
+typedef struct SharedJitInstrumentation
+{
+ int num_workers;
+ JitInstrumentation jit_instr[FLEXIBLE_ARRAY_MEMBER];
+} SharedJitInstrumentation;
+
+typedef struct JitContext
+{
+ /* see PGJIT_* above */
+ int flags;
+
+ ResourceOwner resowner;
+
+ JitInstrumentation instr;
+} JitContext;
+
+typedef struct JitProviderCallbacks JitProviderCallbacks;
+
+extern PGDLLEXPORT void _PG_jit_provider_init(JitProviderCallbacks *cb);
+typedef void (*JitProviderInit) (JitProviderCallbacks *cb);
+typedef void (*JitProviderResetAfterErrorCB) (void);
+typedef void (*JitProviderReleaseContextCB) (JitContext *context);
+struct ExprState;
+typedef bool (*JitProviderCompileExprCB) (struct ExprState *state);
+
+struct JitProviderCallbacks
+{
+ JitProviderResetAfterErrorCB reset_after_error;
+ JitProviderReleaseContextCB release_context;
+ JitProviderCompileExprCB compile_expr;
+};
+
+
+/* GUCs */
+extern PGDLLIMPORT bool jit_enabled;
+extern PGDLLIMPORT char *jit_provider;
+extern PGDLLIMPORT bool jit_debugging_support;
+extern PGDLLIMPORT bool jit_dump_bitcode;
+extern PGDLLIMPORT bool jit_expressions;
+extern PGDLLIMPORT bool jit_profiling_support;
+extern PGDLLIMPORT bool jit_tuple_deforming;
+extern PGDLLIMPORT double jit_above_cost;
+extern PGDLLIMPORT double jit_inline_above_cost;
+extern PGDLLIMPORT double jit_optimize_above_cost;
+
+
+extern void jit_reset_after_error(void);
+extern void jit_release_context(JitContext *context);
+
+/*
+ * Functions for attempting to JIT code. Callers must accept that these might
+ * not be able to perform JIT (i.e. return false).
+ */
+extern bool jit_compile_expr(struct ExprState *state);
+extern void InstrJitAgg(JitInstrumentation *dst, JitInstrumentation *add);
+
+
+#endif /* JIT_H */
diff --git a/pgsql/include/server/jit/llvmjit.h b/pgsql/include/server/jit/llvmjit.h
new file mode 100644
index 0000000000000000000000000000000000000000..2c02b788505410a07be4f73a0725d17388f8db4b
--- /dev/null
+++ b/pgsql/include/server/jit/llvmjit.h
@@ -0,0 +1,161 @@
+/*-------------------------------------------------------------------------
+ * llvmjit.h
+ * LLVM JIT provider.
+ *
+ * Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * src/include/jit/llvmjit.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LLVMJIT_H
+#define LLVMJIT_H
+
+/*
+ * To avoid breaking cpluspluscheck, allow including the file even when LLVM
+ * is not available.
+ */
+#ifdef USE_LLVM
+
+#include
+
+
+/*
+ * File needs to be includable by both C and C++ code, and include other
+ * headers doing the same. Therefore wrap C portion in our own extern "C" if
+ * in C++ mode.
+ */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "access/tupdesc.h"
+#include "fmgr.h"
+#include "jit/jit.h"
+#include "nodes/pg_list.h"
+
+typedef struct LLVMJitContext
+{
+ JitContext base;
+
+ /* number of modules created */
+ size_t module_generation;
+
+ /*
+ * The LLVM Context used by this JIT context. An LLVM context is reused
+ * across many compilations, but occasionally reset to prevent it using
+ * too much memory due to more and more types accumulating.
+ */
+ LLVMContextRef llvm_context;
+
+ /* current, "open for write", module */
+ LLVMModuleRef module;
+
+ /* is there any pending code that needs to be emitted */
+ bool compiled;
+
+ /* # of objects emitted, used to generate non-conflicting names */
+ int counter;
+
+ /* list of handles for code emitted via Orc */
+ List *handles;
+} LLVMJitContext;
+
+/* llvm module containing information about types */
+extern PGDLLIMPORT LLVMModuleRef llvm_types_module;
+
+/* type and struct definitions */
+extern PGDLLIMPORT LLVMTypeRef TypeParamBool;
+extern PGDLLIMPORT LLVMTypeRef TypePGFunction;
+extern PGDLLIMPORT LLVMTypeRef TypeSizeT;
+extern PGDLLIMPORT LLVMTypeRef TypeStorageBool;
+
+extern PGDLLIMPORT LLVMTypeRef StructNullableDatum;
+extern PGDLLIMPORT LLVMTypeRef StructTupleDescData;
+extern PGDLLIMPORT LLVMTypeRef StructHeapTupleData;
+extern PGDLLIMPORT LLVMTypeRef StructHeapTupleHeaderData;
+extern PGDLLIMPORT LLVMTypeRef StructMinimalTupleData;
+extern PGDLLIMPORT LLVMTypeRef StructTupleTableSlot;
+extern PGDLLIMPORT LLVMTypeRef StructHeapTupleTableSlot;
+extern PGDLLIMPORT LLVMTypeRef StructMinimalTupleTableSlot;
+extern PGDLLIMPORT LLVMTypeRef StructMemoryContextData;
+extern PGDLLIMPORT LLVMTypeRef StructFunctionCallInfoData;
+extern PGDLLIMPORT LLVMTypeRef StructExprContext;
+extern PGDLLIMPORT LLVMTypeRef StructExprEvalStep;
+extern PGDLLIMPORT LLVMTypeRef StructExprState;
+extern PGDLLIMPORT LLVMTypeRef StructAggState;
+extern PGDLLIMPORT LLVMTypeRef StructAggStatePerTransData;
+extern PGDLLIMPORT LLVMTypeRef StructAggStatePerGroupData;
+extern PGDLLIMPORT LLVMTypeRef StructPlanState;
+
+extern PGDLLIMPORT LLVMValueRef AttributeTemplate;
+extern PGDLLIMPORT LLVMValueRef ExecEvalBoolSubroutineTemplate;
+extern PGDLLIMPORT LLVMValueRef ExecEvalSubroutineTemplate;
+
+
+extern void llvm_enter_fatal_on_oom(void);
+extern void llvm_leave_fatal_on_oom(void);
+extern bool llvm_in_fatal_on_oom(void);
+extern void llvm_reset_after_error(void);
+extern void llvm_assert_in_fatal_section(void);
+
+extern LLVMJitContext *llvm_create_context(int jitFlags);
+extern LLVMModuleRef llvm_mutable_module(LLVMJitContext *context);
+extern char *llvm_expand_funcname(LLVMJitContext *context, const char *basename);
+extern void *llvm_get_function(LLVMJitContext *context, const char *funcname);
+extern void llvm_split_symbol_name(const char *name, char **modname, char **funcname);
+extern LLVMTypeRef llvm_pg_var_type(const char *varname);
+extern LLVMTypeRef llvm_pg_var_func_type(const char *varname);
+extern LLVMValueRef llvm_pg_func(LLVMModuleRef mod, const char *funcname);
+extern void llvm_copy_attributes(LLVMValueRef from, LLVMValueRef to);
+extern LLVMValueRef llvm_function_reference(LLVMJitContext *context,
+ LLVMBuilderRef builder,
+ LLVMModuleRef mod,
+ FunctionCallInfo fcinfo);
+
+extern void llvm_inline_reset_caches(void);
+extern void llvm_inline(LLVMModuleRef mod);
+
+/*
+ ****************************************************************************
+ * Code generation functions.
+ ****************************************************************************
+ */
+extern bool llvm_compile_expr(struct ExprState *state);
+struct TupleTableSlotOps;
+extern LLVMValueRef slot_compile_deform(struct LLVMJitContext *context, TupleDesc desc,
+ const struct TupleTableSlotOps *ops, int natts);
+
+/*
+ ****************************************************************************
+ * Extensions / Backward compatibility section of the LLVM C API
+ * Error handling related functions.
+ ****************************************************************************
+ */
+#if defined(HAVE_DECL_LLVMGETHOSTCPUNAME) && !HAVE_DECL_LLVMGETHOSTCPUNAME
+/** Get the host CPU as a string. The result needs to be disposed with
+ LLVMDisposeMessage. */
+extern char *LLVMGetHostCPUName(void);
+#endif
+
+#if defined(HAVE_DECL_LLVMGETHOSTCPUFEATURES) && !HAVE_DECL_LLVMGETHOSTCPUFEATURES
+/** Get the host CPU features as a string. The result needs to be disposed
+ with LLVMDisposeMessage. */
+extern char *LLVMGetHostCPUFeatures(void);
+#endif
+
+extern unsigned LLVMGetAttributeCountAtIndexPG(LLVMValueRef F, uint32 Idx);
+extern LLVMTypeRef LLVMGetFunctionReturnType(LLVMValueRef r);
+extern LLVMTypeRef LLVMGetFunctionType(LLVMValueRef r);
+
+#if LLVM_MAJOR_VERSION < 8
+extern LLVMTypeRef LLVMGlobalGetValueType(LLVMValueRef g);
+#endif
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* USE_LLVM */
+#endif /* LLVMJIT_H */
diff --git a/pgsql/include/server/jit/llvmjit_emit.h b/pgsql/include/server/jit/llvmjit_emit.h
new file mode 100644
index 0000000000000000000000000000000000000000..b1f0ea56c08566cae9c0972f44359f2d6780a1f1
--- /dev/null
+++ b/pgsql/include/server/jit/llvmjit_emit.h
@@ -0,0 +1,336 @@
+/*
+ * llvmjit_emit.h
+ * Helpers to make emitting LLVM IR a bit more concise and pgindent proof.
+ *
+ * Copyright (c) 2018-2023, PostgreSQL Global Development Group
+ *
+ * src/include/jit/llvmjit_emit.h
+ */
+#ifndef LLVMJIT_EMIT_H
+#define LLVMJIT_EMIT_H
+
+/*
+ * To avoid breaking cpluspluscheck, allow including the file even when LLVM
+ * is not available.
+ */
+#ifdef USE_LLVM
+
+#include
+#include
+
+#include "jit/llvmjit.h"
+
+
+/*
+ * Emit a non-LLVM pointer as an LLVM constant.
+ */
+static inline LLVMValueRef
+l_ptr_const(void *ptr, LLVMTypeRef type)
+{
+ LLVMValueRef c = LLVMConstInt(TypeSizeT, (uintptr_t) ptr, false);
+
+ return LLVMConstIntToPtr(c, type);
+}
+
+/*
+ * Emit pointer.
+ */
+static inline LLVMTypeRef
+l_ptr(LLVMTypeRef t)
+{
+ return LLVMPointerType(t, 0);
+}
+
+/*
+ * Emit constant integer.
+ */
+static inline LLVMValueRef
+l_int8_const(LLVMContextRef lc, int8 i)
+{
+ return LLVMConstInt(LLVMInt8TypeInContext(lc), i, false);
+}
+
+/*
+ * Emit constant integer.
+ */
+static inline LLVMValueRef
+l_int16_const(LLVMContextRef lc, int16 i)
+{
+ return LLVMConstInt(LLVMInt16TypeInContext(lc), i, false);
+}
+
+/*
+ * Emit constant integer.
+ */
+static inline LLVMValueRef
+l_int32_const(LLVMContextRef lc, int32 i)
+{
+ return LLVMConstInt(LLVMInt32TypeInContext(lc), i, false);
+}
+
+/*
+ * Emit constant integer.
+ */
+static inline LLVMValueRef
+l_int64_const(LLVMContextRef lc, int64 i)
+{
+ return LLVMConstInt(LLVMInt64TypeInContext(lc), i, false);
+}
+
+/*
+ * Emit constant integer.
+ */
+static inline LLVMValueRef
+l_sizet_const(size_t i)
+{
+ return LLVMConstInt(TypeSizeT, i, false);
+}
+
+/*
+ * Emit constant boolean, as used for storage (e.g. global vars, structs).
+ */
+static inline LLVMValueRef
+l_sbool_const(bool i)
+{
+ return LLVMConstInt(TypeStorageBool, (int) i, false);
+}
+
+/*
+ * Emit constant boolean, as used for parameters (e.g. function parameters).
+ */
+static inline LLVMValueRef
+l_pbool_const(bool i)
+{
+ return LLVMConstInt(TypeParamBool, (int) i, false);
+}
+
+static inline LLVMValueRef
+l_struct_gep(LLVMBuilderRef b, LLVMTypeRef t, LLVMValueRef v, int32 idx, const char *name)
+{
+#if LLVM_VERSION_MAJOR < 16
+ return LLVMBuildStructGEP(b, v, idx, "");
+#else
+ return LLVMBuildStructGEP2(b, t, v, idx, "");
+#endif
+}
+
+static inline LLVMValueRef
+l_gep(LLVMBuilderRef b, LLVMTypeRef t, LLVMValueRef v, LLVMValueRef *indices, int32 nindices, const char *name)
+{
+#if LLVM_VERSION_MAJOR < 16
+ return LLVMBuildGEP(b, v, indices, nindices, name);
+#else
+ return LLVMBuildGEP2(b, t, v, indices, nindices, name);
+#endif
+}
+
+static inline LLVMValueRef
+l_load(LLVMBuilderRef b, LLVMTypeRef t, LLVMValueRef v, const char *name)
+{
+#if LLVM_VERSION_MAJOR < 16
+ return LLVMBuildLoad(b, v, name);
+#else
+ return LLVMBuildLoad2(b, t, v, name);
+#endif
+}
+
+static inline LLVMValueRef
+l_call(LLVMBuilderRef b, LLVMTypeRef t, LLVMValueRef fn, LLVMValueRef *args, int32 nargs, const char *name)
+{
+#if LLVM_VERSION_MAJOR < 16
+ return LLVMBuildCall(b, fn, args, nargs, name);
+#else
+ return LLVMBuildCall2(b, t, fn, args, nargs, name);
+#endif
+}
+
+/*
+ * Load a pointer member idx from a struct.
+ */
+static inline LLVMValueRef
+l_load_struct_gep(LLVMBuilderRef b, LLVMTypeRef t, LLVMValueRef v, int32 idx, const char *name)
+{
+ return l_load(b,
+ LLVMStructGetTypeAtIndex(t, idx),
+ l_struct_gep(b, t, v, idx, ""),
+ name);
+}
+
+/*
+ * Load value of a pointer, after applying one index operation.
+ */
+static inline LLVMValueRef
+l_load_gep1(LLVMBuilderRef b, LLVMTypeRef t, LLVMValueRef v, LLVMValueRef idx, const char *name)
+{
+ return l_load(b, t, l_gep(b, t, v, &idx, 1, ""), name);
+}
+
+/* separate, because pg_attribute_printf(2, 3) can't appear in definition */
+static inline LLVMBasicBlockRef l_bb_before_v(LLVMBasicBlockRef r, const char *fmt,...) pg_attribute_printf(2, 3);
+
+/*
+ * Insert a new basic block, just before r, the name being determined by fmt
+ * and arguments.
+ */
+static inline LLVMBasicBlockRef
+l_bb_before_v(LLVMBasicBlockRef r, const char *fmt,...)
+{
+ char buf[512];
+ va_list args;
+ LLVMContextRef lc;
+
+ va_start(args, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, args);
+ va_end(args);
+
+ lc = LLVMGetTypeContext(LLVMTypeOf(LLVMGetBasicBlockParent(r)));
+
+ return LLVMInsertBasicBlockInContext(lc, r, buf);
+}
+
+/* separate, because pg_attribute_printf(2, 3) can't appear in definition */
+static inline LLVMBasicBlockRef l_bb_append_v(LLVMValueRef f, const char *fmt,...) pg_attribute_printf(2, 3);
+
+/*
+ * Insert a new basic block after previous basic blocks, the name being
+ * determined by fmt and arguments.
+ */
+static inline LLVMBasicBlockRef
+l_bb_append_v(LLVMValueRef f, const char *fmt,...)
+{
+ char buf[512];
+ va_list args;
+ LLVMContextRef lc;
+
+ va_start(args, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, args);
+ va_end(args);
+
+ lc = LLVMGetTypeContext(LLVMTypeOf(f));
+
+ return LLVMAppendBasicBlockInContext(lc, f, buf);
+}
+
+/*
+ * Mark a callsite as readonly.
+ */
+static inline void
+l_callsite_ro(LLVMValueRef f)
+{
+ const char argname[] = "readonly";
+ LLVMAttributeRef ref;
+
+ ref = LLVMCreateStringAttribute(LLVMGetTypeContext(LLVMTypeOf(f)),
+ argname,
+ sizeof(argname) - 1,
+ NULL, 0);
+
+ LLVMAddCallSiteAttribute(f, LLVMAttributeFunctionIndex, ref);
+}
+
+/*
+ * Mark a callsite as alwaysinline.
+ */
+static inline void
+l_callsite_alwaysinline(LLVMValueRef f)
+{
+ const char argname[] = "alwaysinline";
+ int id;
+ LLVMAttributeRef attr;
+
+ id = LLVMGetEnumAttributeKindForName(argname,
+ sizeof(argname) - 1);
+ attr = LLVMCreateEnumAttribute(LLVMGetTypeContext(LLVMTypeOf(f)), id, 0);
+ LLVMAddCallSiteAttribute(f, LLVMAttributeFunctionIndex, attr);
+}
+
+/*
+ * Emit code to switch memory context.
+ */
+static inline LLVMValueRef
+l_mcxt_switch(LLVMModuleRef mod, LLVMBuilderRef b, LLVMValueRef nc)
+{
+ const char *cmc = "CurrentMemoryContext";
+ LLVMValueRef cur;
+ LLVMValueRef ret;
+
+ if (!(cur = LLVMGetNamedGlobal(mod, cmc)))
+ cur = LLVMAddGlobal(mod, l_ptr(StructMemoryContextData), cmc);
+ ret = l_load(b, l_ptr(StructMemoryContextData), cur, cmc);
+ LLVMBuildStore(b, nc, cur);
+
+ return ret;
+}
+
+/*
+ * Return pointer to the argno'th argument nullness.
+ */
+static inline LLVMValueRef
+l_funcnullp(LLVMBuilderRef b, LLVMValueRef v_fcinfo, size_t argno)
+{
+ LLVMValueRef v_args;
+ LLVMValueRef v_argn;
+
+ v_args = l_struct_gep(b,
+ StructFunctionCallInfoData,
+ v_fcinfo,
+ FIELDNO_FUNCTIONCALLINFODATA_ARGS,
+ "");
+ v_argn = l_struct_gep(b,
+ LLVMArrayType(StructNullableDatum, 0),
+ v_args,
+ argno,
+ "");
+ return l_struct_gep(b,
+ StructNullableDatum,
+ v_argn,
+ FIELDNO_NULLABLE_DATUM_ISNULL,
+ "");
+}
+
+/*
+ * Return pointer to the argno'th argument datum.
+ */
+static inline LLVMValueRef
+l_funcvaluep(LLVMBuilderRef b, LLVMValueRef v_fcinfo, size_t argno)
+{
+ LLVMValueRef v_args;
+ LLVMValueRef v_argn;
+
+ v_args = l_struct_gep(b,
+ StructFunctionCallInfoData,
+ v_fcinfo,
+ FIELDNO_FUNCTIONCALLINFODATA_ARGS,
+ "");
+ v_argn = l_struct_gep(b,
+ LLVMArrayType(StructNullableDatum, 0),
+ v_args,
+ argno,
+ "");
+ return l_struct_gep(b,
+ StructNullableDatum,
+ v_argn,
+ FIELDNO_NULLABLE_DATUM_DATUM,
+ "");
+}
+
+/*
+ * Return argno'th argument nullness.
+ */
+static inline LLVMValueRef
+l_funcnull(LLVMBuilderRef b, LLVMValueRef v_fcinfo, size_t argno)
+{
+ return l_load(b, TypeStorageBool, l_funcnullp(b, v_fcinfo, argno), "");
+}
+
+/*
+ * Return argno'th argument datum.
+ */
+static inline LLVMValueRef
+l_funcvalue(LLVMBuilderRef b, LLVMValueRef v_fcinfo, size_t argno)
+{
+ return l_load(b, TypeSizeT, l_funcvaluep(b, v_fcinfo, argno), "");
+}
+
+#endif /* USE_LLVM */
+#endif
diff --git a/pgsql/include/server/lib/binaryheap.h b/pgsql/include/server/lib/binaryheap.h
new file mode 100644
index 0000000000000000000000000000000000000000..52f7b06b253e525c8610483c5fef03e7dab00c16
--- /dev/null
+++ b/pgsql/include/server/lib/binaryheap.h
@@ -0,0 +1,54 @@
+/*
+ * binaryheap.h
+ *
+ * A simple binary heap implementation
+ *
+ * Portions Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ * src/include/lib/binaryheap.h
+ */
+
+#ifndef BINARYHEAP_H
+#define BINARYHEAP_H
+
+/*
+ * For a max-heap, the comparator must return <0 iff a < b, 0 iff a == b,
+ * and >0 iff a > b. For a min-heap, the conditions are reversed.
+ */
+typedef int (*binaryheap_comparator) (Datum a, Datum b, void *arg);
+
+/*
+ * binaryheap
+ *
+ * bh_size how many nodes are currently in "nodes"
+ * bh_space how many nodes can be stored in "nodes"
+ * bh_has_heap_property no unordered operations since last heap build
+ * bh_compare comparison function to define the heap property
+ * bh_arg user data for comparison function
+ * bh_nodes variable-length array of "space" nodes
+ */
+typedef struct binaryheap
+{
+ int bh_size;
+ int bh_space;
+ bool bh_has_heap_property; /* debugging cross-check */
+ binaryheap_comparator bh_compare;
+ void *bh_arg;
+ Datum bh_nodes[FLEXIBLE_ARRAY_MEMBER];
+} binaryheap;
+
+extern binaryheap *binaryheap_allocate(int capacity,
+ binaryheap_comparator compare,
+ void *arg);
+extern void binaryheap_reset(binaryheap *heap);
+extern void binaryheap_free(binaryheap *heap);
+extern void binaryheap_add_unordered(binaryheap *heap, Datum d);
+extern void binaryheap_build(binaryheap *heap);
+extern void binaryheap_add(binaryheap *heap, Datum d);
+extern Datum binaryheap_first(binaryheap *heap);
+extern Datum binaryheap_remove_first(binaryheap *heap);
+extern void binaryheap_replace_first(binaryheap *heap, Datum d);
+
+#define binaryheap_empty(h) ((h)->bh_size == 0)
+
+#endif /* BINARYHEAP_H */
diff --git a/pgsql/include/server/lib/bipartite_match.h b/pgsql/include/server/lib/bipartite_match.h
new file mode 100644
index 0000000000000000000000000000000000000000..8fbbcaeb5000eb12ce3fff671cec56980a06d644
--- /dev/null
+++ b/pgsql/include/server/lib/bipartite_match.h
@@ -0,0 +1,46 @@
+/*
+ * bipartite_match.h
+ *
+ * Copyright (c) 2015-2023, PostgreSQL Global Development Group
+ *
+ * src/include/lib/bipartite_match.h
+ */
+#ifndef BIPARTITE_MATCH_H
+#define BIPARTITE_MATCH_H
+
+/*
+ * Given a bipartite graph consisting of nodes U numbered 1..nU, nodes V
+ * numbered 1..nV, and an adjacency map of undirected edges in the form
+ * adjacency[u] = [k, v1, v2, v3, ... vk], we wish to find a "maximum
+ * cardinality matching", which is defined as follows: a matching is a subset
+ * of the original edges such that no node has more than one edge, and a
+ * matching has maximum cardinality if there exists no other matching with a
+ * greater number of edges.
+ *
+ * This matching has various applications in graph theory, but the motivating
+ * example here is Dilworth's theorem: a partially-ordered set can be divided
+ * into the minimum number of chains (i.e. subsets X where x1 < x2 < x3 ...) by
+ * a bipartite graph construction. This gives us a polynomial-time solution to
+ * the problem of planning a collection of grouping sets with the provably
+ * minimal number of sort operations.
+ */
+typedef struct BipartiteMatchState
+{
+ /* inputs: */
+ int u_size; /* size of U */
+ int v_size; /* size of V */
+ short **adjacency; /* adjacency[u] = [k, v1,v2,v3,...,vk] */
+ /* outputs: */
+ int matching; /* number of edges in matching */
+ short *pair_uv; /* pair_uv[u] -> v */
+ short *pair_vu; /* pair_vu[v] -> u */
+ /* private state for matching algorithm: */
+ short *distance; /* distance[u] */
+ short *queue; /* queue storage for breadth search */
+} BipartiteMatchState;
+
+extern BipartiteMatchState *BipartiteMatch(int u_size, int v_size, short **adjacency);
+
+extern void BipartiteMatchFree(BipartiteMatchState *state);
+
+#endif /* BIPARTITE_MATCH_H */
diff --git a/pgsql/include/server/lib/bloomfilter.h b/pgsql/include/server/lib/bloomfilter.h
new file mode 100644
index 0000000000000000000000000000000000000000..5a98c09ab8aba606c666a6ed201afd822230714a
--- /dev/null
+++ b/pgsql/include/server/lib/bloomfilter.h
@@ -0,0 +1,27 @@
+/*-------------------------------------------------------------------------
+ *
+ * bloomfilter.h
+ * Space-efficient set membership testing
+ *
+ * Copyright (c) 2018-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/lib/bloomfilter.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BLOOMFILTER_H
+#define BLOOMFILTER_H
+
+typedef struct bloom_filter bloom_filter;
+
+extern bloom_filter *bloom_create(int64 total_elems, int bloom_work_mem,
+ uint64 seed);
+extern void bloom_free(bloom_filter *filter);
+extern void bloom_add_element(bloom_filter *filter, unsigned char *elem,
+ size_t len);
+extern bool bloom_lacks_element(bloom_filter *filter, unsigned char *elem,
+ size_t len);
+extern double bloom_prop_bits_set(bloom_filter *filter);
+
+#endif /* BLOOMFILTER_H */
diff --git a/pgsql/include/server/lib/dshash.h b/pgsql/include/server/lib/dshash.h
new file mode 100644
index 0000000000000000000000000000000000000000..ece5552122683fc16ca097eee965ed1f4fc557ea
--- /dev/null
+++ b/pgsql/include/server/lib/dshash.h
@@ -0,0 +1,115 @@
+/*-------------------------------------------------------------------------
+ *
+ * dshash.h
+ * Concurrent hash tables backed by dynamic shared memory areas.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/lib/dshash.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DSHASH_H
+#define DSHASH_H
+
+#include "utils/dsa.h"
+
+/* The opaque type representing a hash table. */
+struct dshash_table;
+typedef struct dshash_table dshash_table;
+
+/* A handle for a dshash_table which can be shared with other processes. */
+typedef dsa_pointer dshash_table_handle;
+
+/* Sentinel value to use for invalid dshash_table handles. */
+#define DSHASH_HANDLE_INVALID ((dshash_table_handle) InvalidDsaPointer)
+
+/* The type for hash values. */
+typedef uint32 dshash_hash;
+
+/* A function type for comparing keys. */
+typedef int (*dshash_compare_function) (const void *a, const void *b,
+ size_t size, void *arg);
+
+/* A function type for computing hash values for keys. */
+typedef dshash_hash (*dshash_hash_function) (const void *v, size_t size,
+ void *arg);
+
+/*
+ * The set of parameters needed to create or attach to a hash table. The
+ * members tranche_id and tranche_name do not need to be initialized when
+ * attaching to an existing hash table.
+ *
+ * Compare and hash functions must be supplied even when attaching, because we
+ * can't safely share function pointers between backends in general. Either
+ * the arg variants or the non-arg variants should be supplied; the other
+ * function pointers should be NULL. If the arg variants are supplied then the
+ * user data pointer supplied to the create and attach functions will be
+ * passed to the hash and compare functions.
+ */
+typedef struct dshash_parameters
+{
+ size_t key_size; /* Size of the key (initial bytes of entry) */
+ size_t entry_size; /* Total size of entry */
+ dshash_compare_function compare_function; /* Compare function */
+ dshash_hash_function hash_function; /* Hash function */
+ int tranche_id; /* The tranche ID to use for locks */
+} dshash_parameters;
+
+/* Forward declaration of private types for use only by dshash.c. */
+struct dshash_table_item;
+typedef struct dshash_table_item dshash_table_item;
+
+/*
+ * Sequential scan state. The detail is exposed to let users know the storage
+ * size but it should be considered as an opaque type by callers.
+ */
+typedef struct dshash_seq_status
+{
+ dshash_table *hash_table; /* dshash table working on */
+ int curbucket; /* bucket number we are at */
+ int nbuckets; /* total number of buckets in the dshash */
+ dshash_table_item *curitem; /* item we are currently at */
+ dsa_pointer pnextitem; /* dsa-pointer to the next item */
+ int curpartition; /* partition number we are at */
+ bool exclusive; /* locking mode */
+} dshash_seq_status;
+
+/* Creating, sharing and destroying from hash tables. */
+extern dshash_table *dshash_create(dsa_area *area,
+ const dshash_parameters *params,
+ void *arg);
+extern dshash_table *dshash_attach(dsa_area *area,
+ const dshash_parameters *params,
+ dshash_table_handle handle,
+ void *arg);
+extern void dshash_detach(dshash_table *hash_table);
+extern dshash_table_handle dshash_get_hash_table_handle(dshash_table *hash_table);
+extern void dshash_destroy(dshash_table *hash_table);
+
+/* Finding, creating, deleting entries. */
+extern void *dshash_find(dshash_table *hash_table,
+ const void *key, bool exclusive);
+extern void *dshash_find_or_insert(dshash_table *hash_table,
+ const void *key, bool *found);
+extern bool dshash_delete_key(dshash_table *hash_table, const void *key);
+extern void dshash_delete_entry(dshash_table *hash_table, void *entry);
+extern void dshash_release_lock(dshash_table *hash_table, void *entry);
+
+/* seq scan support */
+extern void dshash_seq_init(dshash_seq_status *status, dshash_table *hash_table,
+ bool exclusive);
+extern void *dshash_seq_next(dshash_seq_status *status);
+extern void dshash_seq_term(dshash_seq_status *status);
+extern void dshash_delete_current(dshash_seq_status *status);
+
+/* Convenience hash and compare functions wrapping memcmp and tag_hash. */
+extern int dshash_memcmp(const void *a, const void *b, size_t size, void *arg);
+extern dshash_hash dshash_memhash(const void *v, size_t size, void *arg);
+
+/* Debugging support. */
+extern void dshash_dump(dshash_table *hash_table);
+
+#endif /* DSHASH_H */
diff --git a/pgsql/include/server/lib/hyperloglog.h b/pgsql/include/server/lib/hyperloglog.h
new file mode 100644
index 0000000000000000000000000000000000000000..f4150f0e85a7455eeed02f56f53bde8286004da0
--- /dev/null
+++ b/pgsql/include/server/lib/hyperloglog.h
@@ -0,0 +1,68 @@
+/*
+ * hyperloglog.h
+ *
+ * A simple HyperLogLog cardinality estimator implementation
+ *
+ * Portions Copyright (c) 2014-2023, PostgreSQL Global Development Group
+ *
+ * Based on Hideaki Ohno's C++ implementation. The copyright terms of Ohno's
+ * original version (the MIT license) follow.
+ *
+ * src/include/lib/hyperloglog.h
+ */
+
+/*
+ * Copyright (c) 2013 Hideaki Ohno
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the 'Software'), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef HYPERLOGLOG_H
+#define HYPERLOGLOG_H
+
+/*
+ * HyperLogLog is an approximate technique for computing the number of distinct
+ * entries in a set. Importantly, it does this by using a fixed amount of
+ * memory. See the 2007 paper "HyperLogLog: the analysis of a near-optimal
+ * cardinality estimation algorithm" for more.
+ *
+ * hyperLogLogState
+ *
+ * registerWidth register width, in bits ("k")
+ * nRegisters number of registers
+ * alphaMM alpha * m ^ 2 (see initHyperLogLog())
+ * hashesArr array of hashes
+ * arrSize size of hashesArr
+ */
+typedef struct hyperLogLogState
+{
+ uint8 registerWidth;
+ Size nRegisters;
+ double alphaMM;
+ uint8 *hashesArr;
+ Size arrSize;
+} hyperLogLogState;
+
+extern void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth);
+extern void initHyperLogLogError(hyperLogLogState *cState, double error);
+extern void addHyperLogLog(hyperLogLogState *cState, uint32 hash);
+extern double estimateHyperLogLog(hyperLogLogState *cState);
+extern void freeHyperLogLog(hyperLogLogState *cState);
+
+#endif /* HYPERLOGLOG_H */
diff --git a/pgsql/include/server/lib/ilist.h b/pgsql/include/server/lib/ilist.h
new file mode 100644
index 0000000000000000000000000000000000000000..095107a99c47a84054e846e50e439b149736951f
--- /dev/null
+++ b/pgsql/include/server/lib/ilist.h
@@ -0,0 +1,1159 @@
+/*-------------------------------------------------------------------------
+ *
+ * ilist.h
+ * integrated/inline doubly- and singly-linked lists
+ *
+ * These list types are useful when there are only a predetermined set of
+ * lists that an object could be in. List links are embedded directly into
+ * the objects, and thus no extra memory management overhead is required.
+ * (Of course, if only a small proportion of existing objects are in a list,
+ * the link fields in the remainder would be wasted space. But usually,
+ * it saves space to not have separately-allocated list nodes.)
+ *
+ * The doubly-linked list comes in 2 forms. dlist_head defines a head of a
+ * doubly-linked list of dlist_nodes, whereas dclist_head defines the head of
+ * a doubly-linked list of dlist_nodes with an additional 'count' field to
+ * keep track of how many items are contained within the given list. For
+ * simplicity, dlist_head and dclist_head share the same node and iterator
+ * types. The functions to manipulate a dlist_head always have a name
+ * starting with "dlist", whereas functions to manipulate a dclist_head have a
+ * name starting with "dclist". dclist_head comes with an additional function
+ * (dclist_count) to return the number of entries in the list. dclists are
+ * able to store a maximum of PG_UINT32_MAX elements. It is up to the caller
+ * to ensure no more than this many items are added to a dclist.
+ *
+ * None of the functions here allocate any memory; they just manipulate
+ * externally managed memory. With the exception doubly-linked count lists
+ * providing the ability to obtain the number of items in the list, the APIs
+ * for singly and both doubly linked lists are identical as far as
+ * capabilities of both allow.
+ *
+ * Each list has a list header, which exists even when the list is empty.
+ * An empty singly-linked list has a NULL pointer in its header.
+ *
+ * For both doubly-linked list types, there are two valid ways to represent an
+ * empty list. The head's 'next' pointer can either be NULL or the head's
+ * 'next' and 'prev' links can both point back to the list head (circular).
+ * (If a dlist is modified and then all its elements are deleted, it will be
+ * in the circular state.). We prefer circular dlists because there are some
+ * operations that can be done without branches (and thus faster) on lists
+ * that use circular representation. However, it is often convenient to
+ * initialize list headers to zeroes rather than setting them up with an
+ * explicit initialization function, so we also allow the NULL initialization.
+ *
+ * EXAMPLES
+ *
+ * Here's a simple example demonstrating how this can be used. Let's assume
+ * we want to store information about the tables contained in a database.
+ *
+ * #include "lib/ilist.h"
+ *
+ * // Define struct for the databases including a list header that will be
+ * // used to access the nodes in the table list later on.
+ * typedef struct my_database
+ * {
+ * char *datname;
+ * dlist_head tables;
+ * // ...
+ * } my_database;
+ *
+ * // Define struct for the tables. Note the list_node element which stores
+ * // prev/next list links. The list_node element need not be first.
+ * typedef struct my_table
+ * {
+ * char *tablename;
+ * dlist_node list_node;
+ * perm_t permissions;
+ * // ...
+ * } my_table;
+ *
+ * // create a database
+ * my_database *db = create_database();
+ *
+ * // and add a few tables to its table list
+ * dlist_push_head(&db->tables, &create_table(db, "a")->list_node);
+ * ...
+ * dlist_push_head(&db->tables, &create_table(db, "b")->list_node);
+ *
+ *
+ * To iterate over the table list, we allocate an iterator variable and use
+ * a specialized looping construct. Inside a dlist_foreach, the iterator's
+ * 'cur' field can be used to access the current element. iter.cur points to
+ * a 'dlist_node', but most of the time what we want is the actual table
+ * information; dlist_container() gives us that, like so:
+ *
+ * dlist_iter iter;
+ * dlist_foreach(iter, &db->tables)
+ * {
+ * my_table *tbl = dlist_container(my_table, list_node, iter.cur);
+ * printf("we have a table: %s in database %s\n",
+ * tbl->tablename, db->datname);
+ * }
+ *
+ *
+ * While a simple iteration is useful, we sometimes also want to manipulate
+ * the list while iterating. There is a different iterator element and looping
+ * construct for that. Suppose we want to delete tables that meet a certain
+ * criterion:
+ *
+ * dlist_mutable_iter miter;
+ * dlist_foreach_modify(miter, &db->tables)
+ * {
+ * my_table *tbl = dlist_container(my_table, list_node, miter.cur);
+ *
+ * if (!tbl->to_be_deleted)
+ * continue; // don't touch this one
+ *
+ * // unlink the current table from the linked list
+ * dlist_delete(miter.cur);
+ * // as these lists never manage memory, we can still access the table
+ * // after it's been unlinked
+ * drop_table(db, tbl);
+ * }
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/lib/ilist.h
+ *-------------------------------------------------------------------------
+ */
+#ifndef ILIST_H
+#define ILIST_H
+
+/*
+ * Enable for extra debugging. This is rather expensive, so it's not enabled by
+ * default even when USE_ASSERT_CHECKING.
+ */
+/* #define ILIST_DEBUG */
+
+/*
+ * Node of a doubly linked list.
+ *
+ * Embed this in structs that need to be part of a doubly linked list.
+ */
+typedef struct dlist_node dlist_node;
+struct dlist_node
+{
+ dlist_node *prev;
+ dlist_node *next;
+};
+
+/*
+ * Head of a doubly linked list.
+ *
+ * Non-empty lists are internally circularly linked. Circular lists have the
+ * advantage of not needing any branches in the most common list manipulations.
+ * An empty list can also be represented as a pair of NULL pointers, making
+ * initialization easier.
+ */
+typedef struct dlist_head
+{
+ /*
+ * head.next either points to the first element of the list; to &head if
+ * it's a circular empty list; or to NULL if empty and not circular.
+ *
+ * head.prev either points to the last element of the list; to &head if
+ * it's a circular empty list; or to NULL if empty and not circular.
+ */
+ dlist_node head;
+} dlist_head;
+
+
+/*
+ * Doubly linked list iterator type for dlist_head and dclist_head types.
+ *
+ * Used as state in dlist_foreach() and dlist_reverse_foreach() (and the
+ * dclist variant thereof).
+ *
+ * To get the current element of the iteration use the 'cur' member.
+ *
+ * Iterations using this are *not* allowed to change the list while iterating!
+ *
+ * NB: We use an extra "end" field here to avoid multiple evaluations of
+ * arguments in the dlist_foreach() and dclist_foreach() macros.
+ */
+typedef struct dlist_iter
+{
+ dlist_node *cur; /* current element */
+ dlist_node *end; /* last node we'll iterate to */
+} dlist_iter;
+
+/*
+ * Doubly linked list iterator for both dlist_head and dclist_head types.
+ * This iterator type allows some modifications while iterating.
+ *
+ * Used as state in dlist_foreach_modify() and dclist_foreach_modify().
+ *
+ * To get the current element of the iteration use the 'cur' member.
+ *
+ * Iterations using this are only allowed to change the list at the current
+ * point of iteration. It is fine to delete the current node, but it is *not*
+ * fine to insert or delete adjacent nodes.
+ *
+ * NB: We need a separate type for mutable iterations so that we can store
+ * the 'next' node of the current node in case it gets deleted or modified.
+ */
+typedef struct dlist_mutable_iter
+{
+ dlist_node *cur; /* current element */
+ dlist_node *next; /* next node we'll iterate to */
+ dlist_node *end; /* last node we'll iterate to */
+} dlist_mutable_iter;
+
+/*
+ * Head of a doubly linked list with a count of the number of items
+ *
+ * This internally makes use of a dlist to implement the actual list. When
+ * items are added or removed from the list the count is updated to reflect
+ * the current number of items in the list.
+ */
+typedef struct dclist_head
+{
+ dlist_head dlist; /* the actual list header */
+ uint32 count; /* the number of items in the list */
+} dclist_head;
+
+/*
+ * Node of a singly linked list.
+ *
+ * Embed this in structs that need to be part of a singly linked list.
+ */
+typedef struct slist_node slist_node;
+struct slist_node
+{
+ slist_node *next;
+};
+
+/*
+ * Head of a singly linked list.
+ *
+ * Singly linked lists are not circularly linked, in contrast to doubly linked
+ * lists; we just set head.next to NULL if empty. This doesn't incur any
+ * additional branches in the usual manipulations.
+ */
+typedef struct slist_head
+{
+ slist_node head;
+} slist_head;
+
+/*
+ * Singly linked list iterator.
+ *
+ * Used as state in slist_foreach(). To get the current element of the
+ * iteration use the 'cur' member.
+ *
+ * It's allowed to modify the list while iterating, with the exception of
+ * deleting the iterator's current node; deletion of that node requires
+ * care if the iteration is to be continued afterward. (Doing so and also
+ * deleting or inserting adjacent list elements might misbehave; also, if
+ * the user frees the current node's storage, continuing the iteration is
+ * not safe.)
+ *
+ * NB: this wouldn't really need to be an extra struct, we could use an
+ * slist_node * directly. We prefer a separate type for consistency.
+ */
+typedef struct slist_iter
+{
+ slist_node *cur;
+} slist_iter;
+
+/*
+ * Singly linked list iterator allowing some modifications while iterating.
+ *
+ * Used as state in slist_foreach_modify(). To get the current element of the
+ * iteration use the 'cur' member.
+ *
+ * The only list modification allowed while iterating is to remove the current
+ * node via slist_delete_current() (*not* slist_delete()). Insertion or
+ * deletion of nodes adjacent to the current node would misbehave.
+ */
+typedef struct slist_mutable_iter
+{
+ slist_node *cur; /* current element */
+ slist_node *next; /* next node we'll iterate to */
+ slist_node *prev; /* prev node, for deletions */
+} slist_mutable_iter;
+
+
+/* Static initializers */
+#define DLIST_STATIC_INIT(name) {{&(name).head, &(name).head}}
+#define DCLIST_STATIC_INIT(name) {{{&(name).dlist.head, &(name).dlist.head}}, 0}
+#define SLIST_STATIC_INIT(name) {{NULL}}
+
+
+/* Prototypes for functions too big to be inline */
+
+/* Caution: this is O(n); consider using slist_delete_current() instead */
+extern void slist_delete(slist_head *head, const slist_node *node);
+
+#ifdef ILIST_DEBUG
+extern void dlist_member_check(const dlist_head *head, const dlist_node *node);
+extern void dlist_check(const dlist_head *head);
+extern void slist_check(const slist_head *head);
+#else
+/*
+ * These seemingly useless casts to void are here to keep the compiler quiet
+ * about the argument being unused in many functions in a non-debug compile,
+ * in which functions the only point of passing the list head pointer is to be
+ * able to run these checks.
+ */
+#define dlist_member_check(head, node) ((void) (head))
+#define dlist_check(head) ((void) (head))
+#define slist_check(head) ((void) (head))
+#endif /* ILIST_DEBUG */
+
+/* doubly linked list implementation */
+
+/*
+ * Initialize a doubly linked list.
+ * Previous state will be thrown away without any cleanup.
+ */
+static inline void
+dlist_init(dlist_head *head)
+{
+ head->head.next = head->head.prev = &head->head;
+}
+
+/*
+ * Initialize a doubly linked list element.
+ *
+ * This is only needed when dlist_node_is_detached() may be needed.
+ */
+static inline void
+dlist_node_init(dlist_node *node)
+{
+ node->next = node->prev = NULL;
+}
+
+/*
+ * Is the list empty?
+ *
+ * An empty list has either its first 'next' pointer set to NULL, or to itself.
+ */
+static inline bool
+dlist_is_empty(const dlist_head *head)
+{
+ dlist_check(head);
+
+ return head->head.next == NULL || head->head.next == &(head->head);
+}
+
+/*
+ * Insert a node at the beginning of the list.
+ */
+static inline void
+dlist_push_head(dlist_head *head, dlist_node *node)
+{
+ if (head->head.next == NULL) /* convert NULL header to circular */
+ dlist_init(head);
+
+ node->next = head->head.next;
+ node->prev = &head->head;
+ node->next->prev = node;
+ head->head.next = node;
+
+ dlist_check(head);
+}
+
+/*
+ * Insert a node at the end of the list.
+ */
+static inline void
+dlist_push_tail(dlist_head *head, dlist_node *node)
+{
+ if (head->head.next == NULL) /* convert NULL header to circular */
+ dlist_init(head);
+
+ node->next = &head->head;
+ node->prev = head->head.prev;
+ node->prev->next = node;
+ head->head.prev = node;
+
+ dlist_check(head);
+}
+
+/*
+ * Insert a node after another *in the same list*
+ */
+static inline void
+dlist_insert_after(dlist_node *after, dlist_node *node)
+{
+ node->prev = after;
+ node->next = after->next;
+ after->next = node;
+ node->next->prev = node;
+}
+
+/*
+ * Insert a node before another *in the same list*
+ */
+static inline void
+dlist_insert_before(dlist_node *before, dlist_node *node)
+{
+ node->prev = before->prev;
+ node->next = before;
+ before->prev = node;
+ node->prev->next = node;
+}
+
+/*
+ * Delete 'node' from its list (it must be in one).
+ */
+static inline void
+dlist_delete(dlist_node *node)
+{
+ node->prev->next = node->next;
+ node->next->prev = node->prev;
+}
+
+/*
+ * Like dlist_delete(), but also sets next/prev to NULL to signal not being in
+ * a list.
+ */
+static inline void
+dlist_delete_thoroughly(dlist_node *node)
+{
+ node->prev->next = node->next;
+ node->next->prev = node->prev;
+ node->next = NULL;
+ node->prev = NULL;
+}
+
+/*
+ * Same as dlist_delete, but performs checks in ILIST_DEBUG builds to ensure
+ * that 'node' belongs to 'head'.
+ */
+static inline void
+dlist_delete_from(dlist_head *head, dlist_node *node)
+{
+ dlist_member_check(head, node);
+ dlist_delete(node);
+}
+
+/*
+ * Like dlist_delete_from, but also sets next/prev to NULL to signal not
+ * being in a list.
+ */
+static inline void
+dlist_delete_from_thoroughly(dlist_head *head, dlist_node *node)
+{
+ dlist_member_check(head, node);
+ dlist_delete_thoroughly(node);
+}
+
+/*
+ * Remove and return the first node from a list (there must be one).
+ */
+static inline dlist_node *
+dlist_pop_head_node(dlist_head *head)
+{
+ dlist_node *node;
+
+ Assert(!dlist_is_empty(head));
+ node = head->head.next;
+ dlist_delete(node);
+ return node;
+}
+
+/*
+ * Move element from its current position in the list to the head position in
+ * the same list.
+ *
+ * Undefined behaviour if 'node' is not already part of the list.
+ */
+static inline void
+dlist_move_head(dlist_head *head, dlist_node *node)
+{
+ /* fast path if it's already at the head */
+ if (head->head.next == node)
+ return;
+
+ dlist_delete(node);
+ dlist_push_head(head, node);
+
+ dlist_check(head);
+}
+
+/*
+ * Move element from its current position in the list to the tail position in
+ * the same list.
+ *
+ * Undefined behaviour if 'node' is not already part of the list.
+ */
+static inline void
+dlist_move_tail(dlist_head *head, dlist_node *node)
+{
+ /* fast path if it's already at the tail */
+ if (head->head.prev == node)
+ return;
+
+ dlist_delete(node);
+ dlist_push_tail(head, node);
+
+ dlist_check(head);
+}
+
+/*
+ * Check whether 'node' has a following node.
+ * Caution: unreliable if 'node' is not in the list.
+ */
+static inline bool
+dlist_has_next(const dlist_head *head, const dlist_node *node)
+{
+ return node->next != &head->head;
+}
+
+/*
+ * Check whether 'node' has a preceding node.
+ * Caution: unreliable if 'node' is not in the list.
+ */
+static inline bool
+dlist_has_prev(const dlist_head *head, const dlist_node *node)
+{
+ return node->prev != &head->head;
+}
+
+/*
+ * Check if node is detached. A node is only detached if it either has been
+ * initialized with dlist_init_node(), or deleted with
+ * dlist_delete_thoroughly() / dlist_delete_from_thoroughly() /
+ * dclist_delete_from_thoroughly().
+ */
+static inline bool
+dlist_node_is_detached(const dlist_node *node)
+{
+ Assert((node->next == NULL && node->prev == NULL) ||
+ (node->next != NULL && node->prev != NULL));
+
+ return node->next == NULL;
+}
+
+/*
+ * Return the next node in the list (there must be one).
+ */
+static inline dlist_node *
+dlist_next_node(dlist_head *head, dlist_node *node)
+{
+ Assert(dlist_has_next(head, node));
+ return node->next;
+}
+
+/*
+ * Return previous node in the list (there must be one).
+ */
+static inline dlist_node *
+dlist_prev_node(dlist_head *head, dlist_node *node)
+{
+ Assert(dlist_has_prev(head, node));
+ return node->prev;
+}
+
+/* internal support function to get address of head element's struct */
+static inline void *
+dlist_head_element_off(dlist_head *head, size_t off)
+{
+ Assert(!dlist_is_empty(head));
+ return (char *) head->head.next - off;
+}
+
+/*
+ * Return the first node in the list (there must be one).
+ */
+static inline dlist_node *
+dlist_head_node(dlist_head *head)
+{
+ return (dlist_node *) dlist_head_element_off(head, 0);
+}
+
+/* internal support function to get address of tail element's struct */
+static inline void *
+dlist_tail_element_off(dlist_head *head, size_t off)
+{
+ Assert(!dlist_is_empty(head));
+ return (char *) head->head.prev - off;
+}
+
+/*
+ * Return the last node in the list (there must be one).
+ */
+static inline dlist_node *
+dlist_tail_node(dlist_head *head)
+{
+ return (dlist_node *) dlist_tail_element_off(head, 0);
+}
+
+/*
+ * Return the containing struct of 'type' where 'membername' is the dlist_node
+ * pointed at by 'ptr'.
+ *
+ * This is used to convert a dlist_node * back to its containing struct.
+ */
+#define dlist_container(type, membername, ptr) \
+ (AssertVariableIsOfTypeMacro(ptr, dlist_node *), \
+ AssertVariableIsOfTypeMacro(((type *) NULL)->membername, dlist_node), \
+ ((type *) ((char *) (ptr) - offsetof(type, membername))))
+
+/*
+ * Return the address of the first element in the list.
+ *
+ * The list must not be empty.
+ */
+#define dlist_head_element(type, membername, lhead) \
+ (AssertVariableIsOfTypeMacro(((type *) NULL)->membername, dlist_node), \
+ (type *) dlist_head_element_off(lhead, offsetof(type, membername)))
+
+/*
+ * Return the address of the last element in the list.
+ *
+ * The list must not be empty.
+ */
+#define dlist_tail_element(type, membername, lhead) \
+ (AssertVariableIsOfTypeMacro(((type *) NULL)->membername, dlist_node), \
+ ((type *) dlist_tail_element_off(lhead, offsetof(type, membername))))
+
+/*
+ * Iterate through the list pointed at by 'lhead' storing the state in 'iter'.
+ *
+ * Access the current element with iter.cur.
+ *
+ * It is *not* allowed to manipulate the list during iteration.
+ */
+#define dlist_foreach(iter, lhead) \
+ for (AssertVariableIsOfTypeMacro(iter, dlist_iter), \
+ AssertVariableIsOfTypeMacro(lhead, dlist_head *), \
+ (iter).end = &(lhead)->head, \
+ (iter).cur = (iter).end->next ? (iter).end->next : (iter).end; \
+ (iter).cur != (iter).end; \
+ (iter).cur = (iter).cur->next)
+
+/*
+ * Iterate through the list pointed at by 'lhead' storing the state in 'iter'.
+ *
+ * Access the current element with iter.cur.
+ *
+ * Iterations using this are only allowed to change the list at the current
+ * point of iteration. It is fine to delete the current node, but it is *not*
+ * fine to insert or delete adjacent nodes.
+ */
+#define dlist_foreach_modify(iter, lhead) \
+ for (AssertVariableIsOfTypeMacro(iter, dlist_mutable_iter), \
+ AssertVariableIsOfTypeMacro(lhead, dlist_head *), \
+ (iter).end = &(lhead)->head, \
+ (iter).cur = (iter).end->next ? (iter).end->next : (iter).end, \
+ (iter).next = (iter).cur->next; \
+ (iter).cur != (iter).end; \
+ (iter).cur = (iter).next, (iter).next = (iter).cur->next)
+
+/*
+ * Iterate through the list in reverse order.
+ *
+ * It is *not* allowed to manipulate the list during iteration.
+ */
+#define dlist_reverse_foreach(iter, lhead) \
+ for (AssertVariableIsOfTypeMacro(iter, dlist_iter), \
+ AssertVariableIsOfTypeMacro(lhead, dlist_head *), \
+ (iter).end = &(lhead)->head, \
+ (iter).cur = (iter).end->prev ? (iter).end->prev : (iter).end; \
+ (iter).cur != (iter).end; \
+ (iter).cur = (iter).cur->prev)
+
+/* doubly-linked count list implementation */
+
+/*
+ * dclist_init
+ * Initialize a doubly linked count list.
+ *
+ * Previous state will be thrown away without any cleanup.
+ */
+static inline void
+dclist_init(dclist_head *head)
+{
+ dlist_init(&head->dlist);
+ head->count = 0;
+}
+
+/*
+ * dclist_is_empty
+ * Returns true if the list is empty, otherwise false.
+ */
+static inline bool
+dclist_is_empty(const dclist_head *head)
+{
+ Assert(dlist_is_empty(&head->dlist) == (head->count == 0));
+ return (head->count == 0);
+}
+
+/*
+ * dclist_push_head
+ * Insert a node at the beginning of the list.
+ */
+static inline void
+dclist_push_head(dclist_head *head, dlist_node *node)
+{
+ if (head->dlist.head.next == NULL) /* convert NULL header to circular */
+ dclist_init(head);
+
+ dlist_push_head(&head->dlist, node);
+ head->count++;
+
+ Assert(head->count > 0); /* count overflow check */
+}
+
+/*
+ * dclist_push_tail
+ * Insert a node at the end of the list.
+ */
+static inline void
+dclist_push_tail(dclist_head *head, dlist_node *node)
+{
+ if (head->dlist.head.next == NULL) /* convert NULL header to circular */
+ dclist_init(head);
+
+ dlist_push_tail(&head->dlist, node);
+ head->count++;
+
+ Assert(head->count > 0); /* count overflow check */
+}
+
+/*
+ * dclist_insert_after
+ * Insert a node after another *in the same list*
+ *
+ * Caution: 'after' must be a member of 'head'.
+ */
+static inline void
+dclist_insert_after(dclist_head *head, dlist_node *after, dlist_node *node)
+{
+ dlist_member_check(&head->dlist, after);
+ Assert(head->count > 0); /* must be at least 1 already */
+
+ dlist_insert_after(after, node);
+ head->count++;
+
+ Assert(head->count > 0); /* count overflow check */
+}
+
+/*
+ * dclist_insert_before
+ * Insert a node before another *in the same list*
+ *
+ * Caution: 'before' must be a member of 'head'.
+ */
+static inline void
+dclist_insert_before(dclist_head *head, dlist_node *before, dlist_node *node)
+{
+ dlist_member_check(&head->dlist, before);
+ Assert(head->count > 0); /* must be at least 1 already */
+
+ dlist_insert_before(before, node);
+ head->count++;
+
+ Assert(head->count > 0); /* count overflow check */
+}
+
+/*
+ * dclist_delete_from
+ * Deletes 'node' from 'head'.
+ *
+ * Caution: 'node' must be a member of 'head'.
+ */
+static inline void
+dclist_delete_from(dclist_head *head, dlist_node *node)
+{
+ Assert(head->count > 0);
+
+ dlist_delete_from(&head->dlist, node);
+ head->count--;
+}
+
+/*
+ * Like dclist_delete_from(), but also sets next/prev to NULL to signal not
+ * being in a list.
+ */
+static inline void
+dclist_delete_from_thoroughly(dclist_head *head, dlist_node *node)
+{
+ Assert(head->count > 0);
+
+ dlist_delete_from_thoroughly(&head->dlist, node);
+ head->count--;
+}
+
+/*
+ * dclist_pop_head_node
+ * Remove and return the first node from a list (there must be one).
+ */
+static inline dlist_node *
+dclist_pop_head_node(dclist_head *head)
+{
+ dlist_node *node;
+
+ Assert(head->count > 0);
+
+ node = dlist_pop_head_node(&head->dlist);
+ head->count--;
+ return node;
+}
+
+/*
+ * dclist_move_head
+ * Move 'node' from its current position in the list to the head position
+ * in 'head'.
+ *
+ * Caution: 'node' must be a member of 'head'.
+ */
+static inline void
+dclist_move_head(dclist_head *head, dlist_node *node)
+{
+ dlist_member_check(&head->dlist, node);
+ Assert(head->count > 0);
+
+ dlist_move_head(&head->dlist, node);
+}
+
+/*
+ * dclist_move_tail
+ * Move 'node' from its current position in the list to the tail position
+ * in 'head'.
+ *
+ * Caution: 'node' must be a member of 'head'.
+ */
+static inline void
+dclist_move_tail(dclist_head *head, dlist_node *node)
+{
+ dlist_member_check(&head->dlist, node);
+ Assert(head->count > 0);
+
+ dlist_move_tail(&head->dlist, node);
+}
+
+/*
+ * dclist_has_next
+ * Check whether 'node' has a following node.
+ *
+ * Caution: 'node' must be a member of 'head'.
+ */
+static inline bool
+dclist_has_next(const dclist_head *head, const dlist_node *node)
+{
+ dlist_member_check(&head->dlist, node);
+ Assert(head->count > 0);
+
+ return dlist_has_next(&head->dlist, node);
+}
+
+/*
+ * dclist_has_prev
+ * Check whether 'node' has a preceding node.
+ *
+ * Caution: 'node' must be a member of 'head'.
+ */
+static inline bool
+dclist_has_prev(const dclist_head *head, const dlist_node *node)
+{
+ dlist_member_check(&head->dlist, node);
+ Assert(head->count > 0);
+
+ return dlist_has_prev(&head->dlist, node);
+}
+
+/*
+ * dclist_next_node
+ * Return the next node in the list (there must be one).
+ */
+static inline dlist_node *
+dclist_next_node(dclist_head *head, dlist_node *node)
+{
+ Assert(head->count > 0);
+
+ return dlist_next_node(&head->dlist, node);
+}
+
+/*
+ * dclist_prev_node
+ * Return the prev node in the list (there must be one).
+ */
+static inline dlist_node *
+dclist_prev_node(dclist_head *head, dlist_node *node)
+{
+ Assert(head->count > 0);
+
+ return dlist_prev_node(&head->dlist, node);
+}
+
+/* internal support function to get address of head element's struct */
+static inline void *
+dclist_head_element_off(dclist_head *head, size_t off)
+{
+ Assert(!dclist_is_empty(head));
+
+ return (char *) head->dlist.head.next - off;
+}
+
+/*
+ * dclist_head_node
+ * Return the first node in the list (there must be one).
+ */
+static inline dlist_node *
+dclist_head_node(dclist_head *head)
+{
+ Assert(head->count > 0);
+
+ return (dlist_node *) dlist_head_element_off(&head->dlist, 0);
+}
+
+/* internal support function to get address of tail element's struct */
+static inline void *
+dclist_tail_element_off(dclist_head *head, size_t off)
+{
+ Assert(!dclist_is_empty(head));
+
+ return (char *) head->dlist.head.prev - off;
+}
+
+/*
+ * Return the last node in the list (there must be one).
+ */
+static inline dlist_node *
+dclist_tail_node(dclist_head *head)
+{
+ Assert(head->count > 0);
+
+ return (dlist_node *) dlist_tail_element_off(&head->dlist, 0);
+}
+
+/*
+ * dclist_count
+ * Returns the stored number of entries in 'head'
+ */
+static inline uint32
+dclist_count(const dclist_head *head)
+{
+ Assert(dlist_is_empty(&head->dlist) == (head->count == 0));
+
+ return head->count;
+}
+
+/*
+ * Return the containing struct of 'type' where 'membername' is the dlist_node
+ * pointed at by 'ptr'.
+ *
+ * This is used to convert a dlist_node * back to its containing struct.
+ *
+ * Note: This is effectively just the same as dlist_container, so reuse that.
+ */
+#define dclist_container(type, membername, ptr) \
+ dlist_container(type, membername, ptr)
+
+ /*
+ * Return the address of the first element in the list.
+ *
+ * The list must not be empty.
+ */
+#define dclist_head_element(type, membername, lhead) \
+ (AssertVariableIsOfTypeMacro(((type *) NULL)->membername, dlist_node), \
+ (type *) dclist_head_element_off(lhead, offsetof(type, membername)))
+
+ /*
+ * Return the address of the last element in the list.
+ *
+ * The list must not be empty.
+ */
+#define dclist_tail_element(type, membername, lhead) \
+ (AssertVariableIsOfTypeMacro(((type *) NULL)->membername, dlist_node), \
+ ((type *) dclist_tail_element_off(lhead, offsetof(type, membername))))
+
+
+/* Iterators for dclists */
+#define dclist_foreach(iter, lhead) \
+ dlist_foreach(iter, &((lhead)->dlist))
+
+#define dclist_foreach_modify(iter, lhead) \
+ dlist_foreach_modify(iter, &((lhead)->dlist))
+
+#define dclist_reverse_foreach(iter, lhead) \
+ dlist_reverse_foreach(iter, &((lhead)->dlist))
+
+/* singly linked list implementation */
+
+/*
+ * Initialize a singly linked list.
+ * Previous state will be thrown away without any cleanup.
+ */
+static inline void
+slist_init(slist_head *head)
+{
+ head->head.next = NULL;
+}
+
+/*
+ * Is the list empty?
+ */
+static inline bool
+slist_is_empty(const slist_head *head)
+{
+ slist_check(head);
+
+ return head->head.next == NULL;
+}
+
+/*
+ * Insert a node at the beginning of the list.
+ */
+static inline void
+slist_push_head(slist_head *head, slist_node *node)
+{
+ node->next = head->head.next;
+ head->head.next = node;
+
+ slist_check(head);
+}
+
+/*
+ * Insert a node after another *in the same list*
+ */
+static inline void
+slist_insert_after(slist_node *after, slist_node *node)
+{
+ node->next = after->next;
+ after->next = node;
+}
+
+/*
+ * Remove and return the first node from a list (there must be one).
+ */
+static inline slist_node *
+slist_pop_head_node(slist_head *head)
+{
+ slist_node *node;
+
+ Assert(!slist_is_empty(head));
+ node = head->head.next;
+ head->head.next = node->next;
+ slist_check(head);
+ return node;
+}
+
+/*
+ * Check whether 'node' has a following node.
+ */
+static inline bool
+slist_has_next(const slist_head *head, const slist_node *node)
+{
+ slist_check(head);
+
+ return node->next != NULL;
+}
+
+/*
+ * Return the next node in the list (there must be one).
+ */
+static inline slist_node *
+slist_next_node(slist_head *head, slist_node *node)
+{
+ Assert(slist_has_next(head, node));
+ return node->next;
+}
+
+/* internal support function to get address of head element's struct */
+static inline void *
+slist_head_element_off(slist_head *head, size_t off)
+{
+ Assert(!slist_is_empty(head));
+ return (char *) head->head.next - off;
+}
+
+/*
+ * Return the first node in the list (there must be one).
+ */
+static inline slist_node *
+slist_head_node(slist_head *head)
+{
+ return (slist_node *) slist_head_element_off(head, 0);
+}
+
+/*
+ * Delete the list element the iterator currently points to.
+ *
+ * Caution: this modifies iter->cur, so don't use that again in the current
+ * loop iteration.
+ */
+static inline void
+slist_delete_current(slist_mutable_iter *iter)
+{
+ /*
+ * Update previous element's forward link. If the iteration is at the
+ * first list element, iter->prev will point to the list header's "head"
+ * field, so we don't need a special case for that.
+ */
+ iter->prev->next = iter->next;
+
+ /*
+ * Reset cur to prev, so that prev will continue to point to the prior
+ * valid list element after slist_foreach_modify() advances to the next.
+ */
+ iter->cur = iter->prev;
+}
+
+/*
+ * Return the containing struct of 'type' where 'membername' is the slist_node
+ * pointed at by 'ptr'.
+ *
+ * This is used to convert a slist_node * back to its containing struct.
+ */
+#define slist_container(type, membername, ptr) \
+ (AssertVariableIsOfTypeMacro(ptr, slist_node *), \
+ AssertVariableIsOfTypeMacro(((type *) NULL)->membername, slist_node), \
+ ((type *) ((char *) (ptr) - offsetof(type, membername))))
+
+/*
+ * Return the address of the first element in the list.
+ *
+ * The list must not be empty.
+ */
+#define slist_head_element(type, membername, lhead) \
+ (AssertVariableIsOfTypeMacro(((type *) NULL)->membername, slist_node), \
+ (type *) slist_head_element_off(lhead, offsetof(type, membername)))
+
+/*
+ * Iterate through the list pointed at by 'lhead' storing the state in 'iter'.
+ *
+ * Access the current element with iter.cur.
+ *
+ * It's allowed to modify the list while iterating, with the exception of
+ * deleting the iterator's current node; deletion of that node requires
+ * care if the iteration is to be continued afterward. (Doing so and also
+ * deleting or inserting adjacent list elements might misbehave; also, if
+ * the user frees the current node's storage, continuing the iteration is
+ * not safe.)
+ */
+#define slist_foreach(iter, lhead) \
+ for (AssertVariableIsOfTypeMacro(iter, slist_iter), \
+ AssertVariableIsOfTypeMacro(lhead, slist_head *), \
+ (iter).cur = (lhead)->head.next; \
+ (iter).cur != NULL; \
+ (iter).cur = (iter).cur->next)
+
+/*
+ * Iterate through the list pointed at by 'lhead' storing the state in 'iter'.
+ *
+ * Access the current element with iter.cur.
+ *
+ * The only list modification allowed while iterating is to remove the current
+ * node via slist_delete_current() (*not* slist_delete()). Insertion or
+ * deletion of nodes adjacent to the current node would misbehave.
+ */
+#define slist_foreach_modify(iter, lhead) \
+ for (AssertVariableIsOfTypeMacro(iter, slist_mutable_iter), \
+ AssertVariableIsOfTypeMacro(lhead, slist_head *), \
+ (iter).prev = &(lhead)->head, \
+ (iter).cur = (iter).prev->next, \
+ (iter).next = (iter).cur ? (iter).cur->next : NULL; \
+ (iter).cur != NULL; \
+ (iter).prev = (iter).cur, \
+ (iter).cur = (iter).next, \
+ (iter).next = (iter).next ? (iter).next->next : NULL)
+
+#endif /* ILIST_H */
diff --git a/pgsql/include/server/lib/integerset.h b/pgsql/include/server/lib/integerset.h
new file mode 100644
index 0000000000000000000000000000000000000000..d7f711ee8b6b483e5d4ba8ecc8ce64ea07143f70
--- /dev/null
+++ b/pgsql/include/server/lib/integerset.h
@@ -0,0 +1,24 @@
+/*
+ * integerset.h
+ * In-memory data structure to hold a large set of integers efficiently
+ *
+ * Portions Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ * src/include/lib/integerset.h
+ */
+#ifndef INTEGERSET_H
+#define INTEGERSET_H
+
+typedef struct IntegerSet IntegerSet;
+
+extern IntegerSet *intset_create(void);
+extern void intset_add_member(IntegerSet *intset, uint64 x);
+extern bool intset_is_member(IntegerSet *intset, uint64 x);
+
+extern uint64 intset_num_entries(IntegerSet *intset);
+extern uint64 intset_memory_usage(IntegerSet *intset);
+
+extern void intset_begin_iterate(IntegerSet *intset);
+extern bool intset_iterate_next(IntegerSet *intset, uint64 *next);
+
+#endif /* INTEGERSET_H */
diff --git a/pgsql/include/server/lib/knapsack.h b/pgsql/include/server/lib/knapsack.h
new file mode 100644
index 0000000000000000000000000000000000000000..04427ba7b5c1ed935e13561bc3e5ea35d346b731
--- /dev/null
+++ b/pgsql/include/server/lib/knapsack.h
@@ -0,0 +1,16 @@
+/*
+ * knapsack.h
+ *
+ * Copyright (c) 2017-2023, PostgreSQL Global Development Group
+ *
+ * src/include/lib/knapsack.h
+ */
+#ifndef KNAPSACK_H
+#define KNAPSACK_H
+
+#include "nodes/bitmapset.h"
+
+extern Bitmapset *DiscreteKnapsack(int max_weight, int num_items,
+ int *item_weights, double *item_values);
+
+#endif /* KNAPSACK_H */
diff --git a/pgsql/include/server/lib/pairingheap.h b/pgsql/include/server/lib/pairingheap.h
new file mode 100644
index 0000000000000000000000000000000000000000..5691e10342d63be2397d67a44e82caa97bef368d
--- /dev/null
+++ b/pgsql/include/server/lib/pairingheap.h
@@ -0,0 +1,102 @@
+/*
+ * pairingheap.h
+ *
+ * A Pairing Heap implementation
+ *
+ * Portions Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ * src/include/lib/pairingheap.h
+ */
+
+#ifndef PAIRINGHEAP_H
+#define PAIRINGHEAP_H
+
+#include "lib/stringinfo.h"
+
+/* Enable if you need the pairingheap_dump() debug function */
+/* #define PAIRINGHEAP_DEBUG */
+
+/*
+ * This represents an element stored in the heap. Embed this in a larger
+ * struct containing the actual data you're storing.
+ *
+ * A node can have multiple children, which form a double-linked list.
+ * first_child points to the node's first child, and the subsequent children
+ * can be found by following the next_sibling pointers. The last child has
+ * next_sibling == NULL. The prev_or_parent pointer points to the node's
+ * previous sibling, or if the node is its parent's first child, to the
+ * parent.
+ */
+typedef struct pairingheap_node
+{
+ struct pairingheap_node *first_child;
+ struct pairingheap_node *next_sibling;
+ struct pairingheap_node *prev_or_parent;
+} pairingheap_node;
+
+/*
+ * Return the containing struct of 'type' where 'membername' is the
+ * pairingheap_node pointed at by 'ptr'.
+ *
+ * This is used to convert a pairingheap_node * back to its containing struct.
+ */
+#define pairingheap_container(type, membername, ptr) \
+ (AssertVariableIsOfTypeMacro(ptr, pairingheap_node *), \
+ AssertVariableIsOfTypeMacro(((type *) NULL)->membername, pairingheap_node), \
+ ((type *) ((char *) (ptr) - offsetof(type, membername))))
+
+/*
+ * Like pairingheap_container, but used when the pointer is 'const ptr'
+ */
+#define pairingheap_const_container(type, membername, ptr) \
+ (AssertVariableIsOfTypeMacro(ptr, const pairingheap_node *), \
+ AssertVariableIsOfTypeMacro(((type *) NULL)->membername, pairingheap_node), \
+ ((const type *) ((const char *) (ptr) - offsetof(type, membername))))
+
+/*
+ * For a max-heap, the comparator must return <0 iff a < b, 0 iff a == b,
+ * and >0 iff a > b. For a min-heap, the conditions are reversed.
+ */
+typedef int (*pairingheap_comparator) (const pairingheap_node *a,
+ const pairingheap_node *b,
+ void *arg);
+
+/*
+ * A pairing heap.
+ *
+ * You can use pairingheap_allocate() to create a new palloc'd heap, or embed
+ * this in a larger struct, set ph_compare and ph_arg directly and initialize
+ * ph_root to NULL.
+ */
+typedef struct pairingheap
+{
+ pairingheap_comparator ph_compare; /* comparison function */
+ void *ph_arg; /* opaque argument to ph_compare */
+ pairingheap_node *ph_root; /* current root of the heap */
+} pairingheap;
+
+extern pairingheap *pairingheap_allocate(pairingheap_comparator compare,
+ void *arg);
+extern void pairingheap_free(pairingheap *heap);
+extern void pairingheap_add(pairingheap *heap, pairingheap_node *node);
+extern pairingheap_node *pairingheap_first(pairingheap *heap);
+extern pairingheap_node *pairingheap_remove_first(pairingheap *heap);
+extern void pairingheap_remove(pairingheap *heap, pairingheap_node *node);
+
+#ifdef PAIRINGHEAP_DEBUG
+extern char *pairingheap_dump(pairingheap *heap,
+ void (*dumpfunc) (pairingheap_node *node, StringInfo buf, void *opaque),
+ void *opaque);
+#endif
+
+/* Resets the heap to be empty. */
+#define pairingheap_reset(h) ((h)->ph_root = NULL)
+
+/* Is the heap empty? */
+#define pairingheap_is_empty(h) ((h)->ph_root == NULL)
+
+/* Is there exactly one node in the heap? */
+#define pairingheap_is_singular(h) \
+ ((h)->ph_root && (h)->ph_root->first_child == NULL)
+
+#endif /* PAIRINGHEAP_H */
diff --git a/pgsql/include/server/lib/qunique.h b/pgsql/include/server/lib/qunique.h
new file mode 100644
index 0000000000000000000000000000000000000000..30b67c794f67db91d27148e02bf6255ebcfa9f2d
--- /dev/null
+++ b/pgsql/include/server/lib/qunique.h
@@ -0,0 +1,67 @@
+/*-------------------------------------------------------------------------
+ *
+ * qunique.h
+ * inline array unique functions
+ * Portions Copyright (c) 2019-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/lib/qunique.h
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef QUNIQUE_H
+#define QUNIQUE_H
+
+/*
+ * Remove duplicates from a pre-sorted array, according to a user-supplied
+ * comparator. Usually the array should have been sorted with qsort() using
+ * the same arguments. Return the new size.
+ */
+static inline size_t
+qunique(void *array, size_t elements, size_t width,
+ int (*compare) (const void *, const void *))
+{
+ char *bytes = (char *) array;
+ size_t i,
+ j;
+
+ if (elements <= 1)
+ return elements;
+
+ for (i = 1, j = 0; i < elements; ++i)
+ {
+ if (compare(bytes + i * width, bytes + j * width) != 0 &&
+ ++j != i)
+ memcpy(bytes + j * width, bytes + i * width, width);
+ }
+
+ return j + 1;
+}
+
+/*
+ * Like qunique(), but takes a comparator with an extra user data argument
+ * which is passed through, for compatibility with qsort_arg().
+ */
+static inline size_t
+qunique_arg(void *array, size_t elements, size_t width,
+ int (*compare) (const void *, const void *, void *),
+ void *arg)
+{
+ char *bytes = (char *) array;
+ size_t i,
+ j;
+
+ if (elements <= 1)
+ return elements;
+
+ for (i = 1, j = 0; i < elements; ++i)
+ {
+ if (compare(bytes + i * width, bytes + j * width, arg) != 0 &&
+ ++j != i)
+ memcpy(bytes + j * width, bytes + i * width, width);
+ }
+
+ return j + 1;
+}
+
+#endif /* QUNIQUE_H */
diff --git a/pgsql/include/server/lib/rbtree.h b/pgsql/include/server/lib/rbtree.h
new file mode 100644
index 0000000000000000000000000000000000000000..b339d6ea6fe4267e343ee6a97edfdb2f243777a1
--- /dev/null
+++ b/pgsql/include/server/lib/rbtree.h
@@ -0,0 +1,81 @@
+/*-------------------------------------------------------------------------
+ *
+ * rbtree.h
+ * interface for PostgreSQL generic Red-Black binary tree package
+ *
+ * Copyright (c) 2009-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/lib/rbtree.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RBTREE_H
+#define RBTREE_H
+
+/*
+ * RBTNode is intended to be used as the first field of a larger struct,
+ * whose additional fields carry whatever payload data the caller needs
+ * for a tree entry. (The total size of that larger struct is passed to
+ * rbt_create.) RBTNode is declared here to support this usage, but
+ * callers must treat it as an opaque struct.
+ */
+typedef struct RBTNode
+{
+ char color; /* node's current color, red or black */
+ struct RBTNode *left; /* left child, or RBTNIL if none */
+ struct RBTNode *right; /* right child, or RBTNIL if none */
+ struct RBTNode *parent; /* parent, or NULL (not RBTNIL!) if none */
+} RBTNode;
+
+/* Opaque struct representing a whole tree */
+typedef struct RBTree RBTree;
+
+/* Available tree iteration orderings */
+typedef enum RBTOrderControl
+{
+ LeftRightWalk, /* inorder: left child, node, right child */
+ RightLeftWalk /* reverse inorder: right, node, left */
+} RBTOrderControl;
+
+/*
+ * RBTreeIterator holds state while traversing a tree. This is declared
+ * here so that callers can stack-allocate this, but must otherwise be
+ * treated as an opaque struct.
+ */
+typedef struct RBTreeIterator RBTreeIterator;
+
+struct RBTreeIterator
+{
+ RBTree *rbt;
+ RBTNode *(*iterate) (RBTreeIterator *iter);
+ RBTNode *last_visited;
+ bool is_over;
+};
+
+/* Support functions to be provided by caller */
+typedef int (*rbt_comparator) (const RBTNode *a, const RBTNode *b, void *arg);
+typedef void (*rbt_combiner) (RBTNode *existing, const RBTNode *newdata, void *arg);
+typedef RBTNode *(*rbt_allocfunc) (void *arg);
+typedef void (*rbt_freefunc) (RBTNode *x, void *arg);
+
+extern RBTree *rbt_create(Size node_size,
+ rbt_comparator comparator,
+ rbt_combiner combiner,
+ rbt_allocfunc allocfunc,
+ rbt_freefunc freefunc,
+ void *arg);
+
+extern RBTNode *rbt_find(RBTree *rbt, const RBTNode *data);
+extern RBTNode *rbt_find_great(RBTree *rbt, const RBTNode *data, bool equal_match);
+extern RBTNode *rbt_find_less(RBTree *rbt, const RBTNode *data, bool equal_match);
+extern RBTNode *rbt_leftmost(RBTree *rbt);
+
+extern RBTNode *rbt_insert(RBTree *rbt, const RBTNode *data, bool *isNew);
+extern void rbt_delete(RBTree *rbt, RBTNode *node);
+
+extern void rbt_begin_iterate(RBTree *rbt, RBTOrderControl ctrl,
+ RBTreeIterator *iter);
+extern RBTNode *rbt_iterate(RBTreeIterator *iter);
+
+#endif /* RBTREE_H */
diff --git a/pgsql/include/server/lib/simplehash.h b/pgsql/include/server/lib/simplehash.h
new file mode 100644
index 0000000000000000000000000000000000000000..1dc817ac8d9d15ba387f1b9eacacb12c943109f4
--- /dev/null
+++ b/pgsql/include/server/lib/simplehash.h
@@ -0,0 +1,1187 @@
+/*
+ * simplehash.h
+ *
+ * When included this file generates a "templated" (by way of macros)
+ * open-addressing hash table implementation specialized to user-defined
+ * types.
+ *
+ * It's probably not worthwhile to generate such a specialized implementation
+ * for hash tables that aren't performance or space sensitive.
+ *
+ * Compared to dynahash, simplehash has the following benefits:
+ *
+ * - Due to the "templated" code generation has known structure sizes and no
+ * indirect function calls (which show up substantially in dynahash
+ * profiles). These features considerably increase speed for small
+ * entries.
+ * - Open addressing has better CPU cache behavior than dynahash's chained
+ * hashtables.
+ * - The generated interface is type-safe and easier to use than dynahash,
+ * though at the cost of more complex setup.
+ * - Allocates memory in a MemoryContext or another allocator with a
+ * malloc/free style interface (which isn't easily usable in a shared
+ * memory context)
+ * - Does not require the overhead of a separate memory context.
+ *
+ * Usage notes:
+ *
+ * To generate a hash-table and associated functions for a use case several
+ * macros have to be #define'ed before this file is included. Including
+ * the file #undef's all those, so a new hash table can be generated
+ * afterwards.
+ * The relevant parameters are:
+ * - SH_PREFIX - prefix for all symbol names generated. A prefix of 'foo'
+ * will result in hash table type 'foo_hash' and functions like
+ * 'foo_insert'/'foo_lookup' and so forth.
+ * - SH_ELEMENT_TYPE - type of the contained elements
+ * - SH_KEY_TYPE - type of the hashtable's key
+ * - SH_DECLARE - if defined function prototypes and type declarations are
+ * generated
+ * - SH_DEFINE - if defined function definitions are generated
+ * - SH_SCOPE - in which scope (e.g. extern, static inline) do function
+ * declarations reside
+ * - SH_RAW_ALLOCATOR - if defined, memory contexts are not used; instead,
+ * use this to allocate bytes. The allocator must zero the returned space.
+ * - SH_USE_NONDEFAULT_ALLOCATOR - if defined no element allocator functions
+ * are defined, so you can supply your own
+ * The following parameters are only relevant when SH_DEFINE is defined:
+ * - SH_KEY - name of the element in SH_ELEMENT_TYPE containing the hash key
+ * - SH_EQUAL(table, a, b) - compare two table keys
+ * - SH_HASH_KEY(table, key) - generate hash for the key
+ * - SH_STORE_HASH - if defined the hash is stored in the elements
+ * - SH_GET_HASH(tb, a) - return the field to store the hash in
+ *
+ * The element type is required to contain a "status" member that can store
+ * the range of values defined in the SH_STATUS enum.
+ *
+ * While SH_STORE_HASH (and subsequently SH_GET_HASH) are optional, because
+ * the hash table implementation needs to compare hashes to move elements
+ * (particularly when growing the hash), it's preferable, if possible, to
+ * store the element's hash in the element's data type. If the hash is so
+ * stored, the hash table will also compare hashes before calling SH_EQUAL
+ * when comparing two keys.
+ *
+ * For convenience the hash table create functions accept a void pointer
+ * that will be stored in the hash table type's member private_data. This
+ * allows callbacks to reference caller provided data.
+ *
+ * For examples of usage look at tidbitmap.c (file local definition) and
+ * execnodes.h/execGrouping.c (exposed declaration, file local
+ * implementation).
+ *
+ * Hash table design:
+ *
+ * The hash table design chosen is a variant of linear open-addressing. The
+ * reason for doing so is that linear addressing is CPU cache & pipeline
+ * friendly. The biggest disadvantage of simple linear addressing schemes
+ * are highly variable lookup times due to clustering, and deletions
+ * leaving a lot of tombstones around. To address these issues a variant
+ * of "robin hood" hashing is employed. Robin hood hashing optimizes
+ * chaining lengths by moving elements close to their optimal bucket
+ * ("rich" elements), out of the way if a to-be-inserted element is further
+ * away from its optimal position (i.e. it's "poor"). While that can make
+ * insertions slower, the average lookup performance is a lot better, and
+ * higher fill factors can be used in a still performant manner. To avoid
+ * tombstones - which normally solve the issue that a deleted node's
+ * presence is relevant to determine whether a lookup needs to continue
+ * looking or is done - buckets following a deleted element are shifted
+ * backwards, unless they're empty or already at their optimal position.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/lib/simplehash.h
+ */
+
+#include "port/pg_bitutils.h"
+
+/* helpers */
+#define SH_MAKE_PREFIX(a) CppConcat(a,_)
+#define SH_MAKE_NAME(name) SH_MAKE_NAME_(SH_MAKE_PREFIX(SH_PREFIX),name)
+#define SH_MAKE_NAME_(a,b) CppConcat(a,b)
+
+/* name macros for: */
+
+/* type declarations */
+#define SH_TYPE SH_MAKE_NAME(hash)
+#define SH_STATUS SH_MAKE_NAME(status)
+#define SH_STATUS_EMPTY SH_MAKE_NAME(SH_EMPTY)
+#define SH_STATUS_IN_USE SH_MAKE_NAME(SH_IN_USE)
+#define SH_ITERATOR SH_MAKE_NAME(iterator)
+
+/* function declarations */
+#define SH_CREATE SH_MAKE_NAME(create)
+#define SH_DESTROY SH_MAKE_NAME(destroy)
+#define SH_RESET SH_MAKE_NAME(reset)
+#define SH_INSERT SH_MAKE_NAME(insert)
+#define SH_INSERT_HASH SH_MAKE_NAME(insert_hash)
+#define SH_DELETE_ITEM SH_MAKE_NAME(delete_item)
+#define SH_DELETE SH_MAKE_NAME(delete)
+#define SH_LOOKUP SH_MAKE_NAME(lookup)
+#define SH_LOOKUP_HASH SH_MAKE_NAME(lookup_hash)
+#define SH_GROW SH_MAKE_NAME(grow)
+#define SH_START_ITERATE SH_MAKE_NAME(start_iterate)
+#define SH_START_ITERATE_AT SH_MAKE_NAME(start_iterate_at)
+#define SH_ITERATE SH_MAKE_NAME(iterate)
+#define SH_ALLOCATE SH_MAKE_NAME(allocate)
+#define SH_FREE SH_MAKE_NAME(free)
+#define SH_STAT SH_MAKE_NAME(stat)
+
+/* internal helper functions (no externally visible prototypes) */
+#define SH_COMPUTE_PARAMETERS SH_MAKE_NAME(compute_parameters)
+#define SH_NEXT SH_MAKE_NAME(next)
+#define SH_PREV SH_MAKE_NAME(prev)
+#define SH_DISTANCE_FROM_OPTIMAL SH_MAKE_NAME(distance)
+#define SH_INITIAL_BUCKET SH_MAKE_NAME(initial_bucket)
+#define SH_ENTRY_HASH SH_MAKE_NAME(entry_hash)
+#define SH_INSERT_HASH_INTERNAL SH_MAKE_NAME(insert_hash_internal)
+#define SH_LOOKUP_HASH_INTERNAL SH_MAKE_NAME(lookup_hash_internal)
+
+/* generate forward declarations necessary to use the hash table */
+#ifdef SH_DECLARE
+
+/* type definitions */
+typedef struct SH_TYPE
+{
+ /*
+ * Size of data / bucket array, 64 bits to handle UINT32_MAX sized hash
+ * tables. Note that the maximum number of elements is lower
+ * (SH_MAX_FILLFACTOR)
+ */
+ uint64 size;
+
+ /* how many elements have valid contents */
+ uint32 members;
+
+ /* mask for bucket and size calculations, based on size */
+ uint32 sizemask;
+
+ /* boundary after which to grow hashtable */
+ uint32 grow_threshold;
+
+ /* hash buckets */
+ SH_ELEMENT_TYPE *data;
+
+#ifndef SH_RAW_ALLOCATOR
+ /* memory context to use for allocations */
+ MemoryContext ctx;
+#endif
+
+ /* user defined data, useful for callbacks */
+ void *private_data;
+} SH_TYPE;
+
+typedef enum SH_STATUS
+{
+ SH_STATUS_EMPTY = 0x00,
+ SH_STATUS_IN_USE = 0x01
+} SH_STATUS;
+
+typedef struct SH_ITERATOR
+{
+ uint32 cur; /* current element */
+ uint32 end;
+ bool done; /* iterator exhausted? */
+} SH_ITERATOR;
+
+/* externally visible function prototypes */
+#ifdef SH_RAW_ALLOCATOR
+/* _hash _create(uint32 nelements, void *private_data) */
+SH_SCOPE SH_TYPE *SH_CREATE(uint32 nelements, void *private_data);
+#else
+/*
+ * _hash _create(MemoryContext ctx, uint32 nelements,
+ * void *private_data)
+ */
+SH_SCOPE SH_TYPE *SH_CREATE(MemoryContext ctx, uint32 nelements,
+ void *private_data);
+#endif
+
+/* void _destroy(_hash *tb) */
+SH_SCOPE void SH_DESTROY(SH_TYPE * tb);
+
+/* void _reset(_hash *tb) */
+SH_SCOPE void SH_RESET(SH_TYPE * tb);
+
+/* void _grow(_hash *tb, uint64 newsize) */
+SH_SCOPE void SH_GROW(SH_TYPE * tb, uint64 newsize);
+
+/* *_insert(_hash *tb, key, bool *found) */
+SH_SCOPE SH_ELEMENT_TYPE *SH_INSERT(SH_TYPE * tb, SH_KEY_TYPE key, bool *found);
+
+/*
+ * *_insert_hash(_hash *tb, key, uint32 hash,
+ * bool *found)
+ */
+SH_SCOPE SH_ELEMENT_TYPE *SH_INSERT_HASH(SH_TYPE * tb, SH_KEY_TYPE key,
+ uint32 hash, bool *found);
+
+/* *_lookup(_hash *tb, key) */
+SH_SCOPE SH_ELEMENT_TYPE *SH_LOOKUP(SH_TYPE * tb, SH_KEY_TYPE key);
+
+/* *_lookup_hash(_hash *tb, key, uint32 hash) */
+SH_SCOPE SH_ELEMENT_TYPE *SH_LOOKUP_HASH(SH_TYPE * tb, SH_KEY_TYPE key,
+ uint32 hash);
+
+/* void _delete_item(_hash *tb, *entry) */
+SH_SCOPE void SH_DELETE_ITEM(SH_TYPE * tb, SH_ELEMENT_TYPE * entry);
+
+/* bool _delete(_hash *tb, key) */
+SH_SCOPE bool SH_DELETE(SH_TYPE * tb, SH_KEY_TYPE key);
+
+/* void _start_iterate(_hash *tb, _iterator *iter) */
+SH_SCOPE void SH_START_ITERATE(SH_TYPE * tb, SH_ITERATOR * iter);
+
+/*
+ * void _start_iterate_at(_hash *tb, _iterator *iter,
+ * uint32 at)
+ */
+SH_SCOPE void SH_START_ITERATE_AT(SH_TYPE * tb, SH_ITERATOR * iter, uint32 at);
+
+/* *_iterate(_hash *tb, _iterator *iter) */
+SH_SCOPE SH_ELEMENT_TYPE *SH_ITERATE(SH_TYPE * tb, SH_ITERATOR * iter);
+
+/* void _stat(_hash *tb */
+SH_SCOPE void SH_STAT(SH_TYPE * tb);
+
+#endif /* SH_DECLARE */
+
+
+/* generate implementation of the hash table */
+#ifdef SH_DEFINE
+
+#ifndef SH_RAW_ALLOCATOR
+#include "utils/memutils.h"
+#endif
+
+/* max data array size,we allow up to PG_UINT32_MAX buckets, including 0 */
+#define SH_MAX_SIZE (((uint64) PG_UINT32_MAX) + 1)
+
+/* normal fillfactor, unless already close to maximum */
+#ifndef SH_FILLFACTOR
+#define SH_FILLFACTOR (0.9)
+#endif
+/* increase fillfactor if we otherwise would error out */
+#define SH_MAX_FILLFACTOR (0.98)
+/* grow if actual and optimal location bigger than */
+#ifndef SH_GROW_MAX_DIB
+#define SH_GROW_MAX_DIB 25
+#endif
+/* grow if more than elements to move when inserting */
+#ifndef SH_GROW_MAX_MOVE
+#define SH_GROW_MAX_MOVE 150
+#endif
+#ifndef SH_GROW_MIN_FILLFACTOR
+/* but do not grow due to SH_GROW_MAX_* if below */
+#define SH_GROW_MIN_FILLFACTOR 0.1
+#endif
+
+#ifdef SH_STORE_HASH
+#define SH_COMPARE_KEYS(tb, ahash, akey, b) (ahash == SH_GET_HASH(tb, b) && SH_EQUAL(tb, b->SH_KEY, akey))
+#else
+#define SH_COMPARE_KEYS(tb, ahash, akey, b) (SH_EQUAL(tb, b->SH_KEY, akey))
+#endif
+
+/*
+ * Wrap the following definitions in include guards, to avoid multiple
+ * definition errors if this header is included more than once. The rest of
+ * the file deliberately has no include guards, because it can be included
+ * with different parameters to define functions and types with non-colliding
+ * names.
+ */
+#ifndef SIMPLEHASH_H
+#define SIMPLEHASH_H
+
+#ifdef FRONTEND
+#define sh_error(...) pg_fatal(__VA_ARGS__)
+#define sh_log(...) pg_log_info(__VA_ARGS__)
+#else
+#define sh_error(...) elog(ERROR, __VA_ARGS__)
+#define sh_log(...) elog(LOG, __VA_ARGS__)
+#endif
+
+#endif
+
+/*
+ * Compute sizing parameters for hashtable. Called when creating and growing
+ * the hashtable.
+ */
+static inline void
+SH_COMPUTE_PARAMETERS(SH_TYPE * tb, uint64 newsize)
+{
+ uint64 size;
+
+ /* supporting zero sized hashes would complicate matters */
+ size = Max(newsize, 2);
+
+ /* round up size to the next power of 2, that's how bucketing works */
+ size = pg_nextpower2_64(size);
+ Assert(size <= SH_MAX_SIZE);
+
+ /*
+ * Verify that allocation of ->data is possible on this platform, without
+ * overflowing Size.
+ */
+ if (unlikely((((uint64) sizeof(SH_ELEMENT_TYPE)) * size) >= SIZE_MAX / 2))
+ sh_error("hash table too large");
+
+ /* now set size */
+ tb->size = size;
+ tb->sizemask = (uint32) (size - 1);
+
+ /*
+ * Compute the next threshold at which we need to grow the hash table
+ * again.
+ */
+ if (tb->size == SH_MAX_SIZE)
+ tb->grow_threshold = ((double) tb->size) * SH_MAX_FILLFACTOR;
+ else
+ tb->grow_threshold = ((double) tb->size) * SH_FILLFACTOR;
+}
+
+/* return the optimal bucket for the hash */
+static inline uint32
+SH_INITIAL_BUCKET(SH_TYPE * tb, uint32 hash)
+{
+ return hash & tb->sizemask;
+}
+
+/* return next bucket after the current, handling wraparound */
+static inline uint32
+SH_NEXT(SH_TYPE * tb, uint32 curelem, uint32 startelem)
+{
+ curelem = (curelem + 1) & tb->sizemask;
+
+ Assert(curelem != startelem);
+
+ return curelem;
+}
+
+/* return bucket before the current, handling wraparound */
+static inline uint32
+SH_PREV(SH_TYPE * tb, uint32 curelem, uint32 startelem)
+{
+ curelem = (curelem - 1) & tb->sizemask;
+
+ Assert(curelem != startelem);
+
+ return curelem;
+}
+
+/* return distance between bucket and its optimal position */
+static inline uint32
+SH_DISTANCE_FROM_OPTIMAL(SH_TYPE * tb, uint32 optimal, uint32 bucket)
+{
+ if (optimal <= bucket)
+ return bucket - optimal;
+ else
+ return (tb->size + bucket) - optimal;
+}
+
+static inline uint32
+SH_ENTRY_HASH(SH_TYPE * tb, SH_ELEMENT_TYPE * entry)
+{
+#ifdef SH_STORE_HASH
+ return SH_GET_HASH(tb, entry);
+#else
+ return SH_HASH_KEY(tb, entry->SH_KEY);
+#endif
+}
+
+/* default memory allocator function */
+static inline void *SH_ALLOCATE(SH_TYPE * type, Size size);
+static inline void SH_FREE(SH_TYPE * type, void *pointer);
+
+#ifndef SH_USE_NONDEFAULT_ALLOCATOR
+
+/* default memory allocator function */
+static inline void *
+SH_ALLOCATE(SH_TYPE * type, Size size)
+{
+#ifdef SH_RAW_ALLOCATOR
+ return SH_RAW_ALLOCATOR(size);
+#else
+ return MemoryContextAllocExtended(type->ctx, size,
+ MCXT_ALLOC_HUGE | MCXT_ALLOC_ZERO);
+#endif
+}
+
+/* default memory free function */
+static inline void
+SH_FREE(SH_TYPE * type, void *pointer)
+{
+ pfree(pointer);
+}
+
+#endif
+
+/*
+ * Create a hash table with enough space for `nelements` distinct members.
+ * Memory for the hash table is allocated from the passed-in context. If
+ * desired, the array of elements can be allocated using a passed-in allocator;
+ * this could be useful in order to place the array of elements in a shared
+ * memory, or in a context that will outlive the rest of the hash table.
+ * Memory other than for the array of elements will still be allocated from
+ * the passed-in context.
+ */
+#ifdef SH_RAW_ALLOCATOR
+SH_SCOPE SH_TYPE *
+SH_CREATE(uint32 nelements, void *private_data)
+#else
+SH_SCOPE SH_TYPE *
+SH_CREATE(MemoryContext ctx, uint32 nelements, void *private_data)
+#endif
+{
+ SH_TYPE *tb;
+ uint64 size;
+
+#ifdef SH_RAW_ALLOCATOR
+ tb = (SH_TYPE *) SH_RAW_ALLOCATOR(sizeof(SH_TYPE));
+#else
+ tb = (SH_TYPE *) MemoryContextAllocZero(ctx, sizeof(SH_TYPE));
+ tb->ctx = ctx;
+#endif
+ tb->private_data = private_data;
+
+ /* increase nelements by fillfactor, want to store nelements elements */
+ size = Min((double) SH_MAX_SIZE, ((double) nelements) / SH_FILLFACTOR);
+
+ SH_COMPUTE_PARAMETERS(tb, size);
+
+ tb->data = (SH_ELEMENT_TYPE *) SH_ALLOCATE(tb, sizeof(SH_ELEMENT_TYPE) * tb->size);
+
+ return tb;
+}
+
+/* destroy a previously created hash table */
+SH_SCOPE void
+SH_DESTROY(SH_TYPE * tb)
+{
+ SH_FREE(tb, tb->data);
+ pfree(tb);
+}
+
+/* reset the contents of a previously created hash table */
+SH_SCOPE void
+SH_RESET(SH_TYPE * tb)
+{
+ memset(tb->data, 0, sizeof(SH_ELEMENT_TYPE) * tb->size);
+ tb->members = 0;
+}
+
+/*
+ * Grow a hash table to at least `newsize` buckets.
+ *
+ * Usually this will automatically be called by insertions/deletions, when
+ * necessary. But resizing to the exact input size can be advantageous
+ * performance-wise, when known at some point.
+ */
+SH_SCOPE void
+SH_GROW(SH_TYPE * tb, uint64 newsize)
+{
+ uint64 oldsize = tb->size;
+ SH_ELEMENT_TYPE *olddata = tb->data;
+ SH_ELEMENT_TYPE *newdata;
+ uint32 i;
+ uint32 startelem = 0;
+ uint32 copyelem;
+
+ Assert(oldsize == pg_nextpower2_64(oldsize));
+ Assert(oldsize != SH_MAX_SIZE);
+ Assert(oldsize < newsize);
+
+ /* compute parameters for new table */
+ SH_COMPUTE_PARAMETERS(tb, newsize);
+
+ tb->data = (SH_ELEMENT_TYPE *) SH_ALLOCATE(tb, sizeof(SH_ELEMENT_TYPE) * tb->size);
+
+ newdata = tb->data;
+
+ /*
+ * Copy entries from the old data to newdata. We theoretically could use
+ * SH_INSERT here, to avoid code duplication, but that's more general than
+ * we need. We neither want tb->members increased, nor do we need to do
+ * deal with deleted elements, nor do we need to compare keys. So a
+ * special-cased implementation is lot faster. As resizing can be time
+ * consuming and frequent, that's worthwhile to optimize.
+ *
+ * To be able to simply move entries over, we have to start not at the
+ * first bucket (i.e olddata[0]), but find the first bucket that's either
+ * empty, or is occupied by an entry at its optimal position. Such a
+ * bucket has to exist in any table with a load factor under 1, as not all
+ * buckets are occupied, i.e. there always has to be an empty bucket. By
+ * starting at such a bucket we can move the entries to the larger table,
+ * without having to deal with conflicts.
+ */
+
+ /* search for the first element in the hash that's not wrapped around */
+ for (i = 0; i < oldsize; i++)
+ {
+ SH_ELEMENT_TYPE *oldentry = &olddata[i];
+ uint32 hash;
+ uint32 optimal;
+
+ if (oldentry->status != SH_STATUS_IN_USE)
+ {
+ startelem = i;
+ break;
+ }
+
+ hash = SH_ENTRY_HASH(tb, oldentry);
+ optimal = SH_INITIAL_BUCKET(tb, hash);
+
+ if (optimal == i)
+ {
+ startelem = i;
+ break;
+ }
+ }
+
+ /* and copy all elements in the old table */
+ copyelem = startelem;
+ for (i = 0; i < oldsize; i++)
+ {
+ SH_ELEMENT_TYPE *oldentry = &olddata[copyelem];
+
+ if (oldentry->status == SH_STATUS_IN_USE)
+ {
+ uint32 hash;
+ uint32 startelem2;
+ uint32 curelem;
+ SH_ELEMENT_TYPE *newentry;
+
+ hash = SH_ENTRY_HASH(tb, oldentry);
+ startelem2 = SH_INITIAL_BUCKET(tb, hash);
+ curelem = startelem2;
+
+ /* find empty element to put data into */
+ while (true)
+ {
+ newentry = &newdata[curelem];
+
+ if (newentry->status == SH_STATUS_EMPTY)
+ {
+ break;
+ }
+
+ curelem = SH_NEXT(tb, curelem, startelem2);
+ }
+
+ /* copy entry to new slot */
+ memcpy(newentry, oldentry, sizeof(SH_ELEMENT_TYPE));
+ }
+
+ /* can't use SH_NEXT here, would use new size */
+ copyelem++;
+ if (copyelem >= oldsize)
+ {
+ copyelem = 0;
+ }
+ }
+
+ SH_FREE(tb, olddata);
+}
+
+/*
+ * This is a separate static inline function, so it can be reliably be inlined
+ * into its wrapper functions even if SH_SCOPE is extern.
+ */
+static inline SH_ELEMENT_TYPE *
+SH_INSERT_HASH_INTERNAL(SH_TYPE * tb, SH_KEY_TYPE key, uint32 hash, bool *found)
+{
+ uint32 startelem;
+ uint32 curelem;
+ SH_ELEMENT_TYPE *data;
+ uint32 insertdist;
+
+restart:
+ insertdist = 0;
+
+ /*
+ * We do the grow check even if the key is actually present, to avoid
+ * doing the check inside the loop. This also lets us avoid having to
+ * re-find our position in the hashtable after resizing.
+ *
+ * Note that this also reached when resizing the table due to
+ * SH_GROW_MAX_DIB / SH_GROW_MAX_MOVE.
+ */
+ if (unlikely(tb->members >= tb->grow_threshold))
+ {
+ if (unlikely(tb->size == SH_MAX_SIZE))
+ sh_error("hash table size exceeded");
+
+ /*
+ * When optimizing, it can be very useful to print these out.
+ */
+ /* SH_STAT(tb); */
+ SH_GROW(tb, tb->size * 2);
+ /* SH_STAT(tb); */
+ }
+
+ /* perform insert, start bucket search at optimal location */
+ data = tb->data;
+ startelem = SH_INITIAL_BUCKET(tb, hash);
+ curelem = startelem;
+ while (true)
+ {
+ uint32 curdist;
+ uint32 curhash;
+ uint32 curoptimal;
+ SH_ELEMENT_TYPE *entry = &data[curelem];
+
+ /* any empty bucket can directly be used */
+ if (entry->status == SH_STATUS_EMPTY)
+ {
+ tb->members++;
+ entry->SH_KEY = key;
+#ifdef SH_STORE_HASH
+ SH_GET_HASH(tb, entry) = hash;
+#endif
+ entry->status = SH_STATUS_IN_USE;
+ *found = false;
+ return entry;
+ }
+
+ /*
+ * If the bucket is not empty, we either found a match (in which case
+ * we're done), or we have to decide whether to skip over or move the
+ * colliding entry. When the colliding element's distance to its
+ * optimal position is smaller than the to-be-inserted entry's, we
+ * shift the colliding entry (and its followers) forward by one.
+ */
+
+ if (SH_COMPARE_KEYS(tb, hash, key, entry))
+ {
+ Assert(entry->status == SH_STATUS_IN_USE);
+ *found = true;
+ return entry;
+ }
+
+ curhash = SH_ENTRY_HASH(tb, entry);
+ curoptimal = SH_INITIAL_BUCKET(tb, curhash);
+ curdist = SH_DISTANCE_FROM_OPTIMAL(tb, curoptimal, curelem);
+
+ if (insertdist > curdist)
+ {
+ SH_ELEMENT_TYPE *lastentry = entry;
+ uint32 emptyelem = curelem;
+ uint32 moveelem;
+ int32 emptydist = 0;
+
+ /* find next empty bucket */
+ while (true)
+ {
+ SH_ELEMENT_TYPE *emptyentry;
+
+ emptyelem = SH_NEXT(tb, emptyelem, startelem);
+ emptyentry = &data[emptyelem];
+
+ if (emptyentry->status == SH_STATUS_EMPTY)
+ {
+ lastentry = emptyentry;
+ break;
+ }
+
+ /*
+ * To avoid negative consequences from overly imbalanced
+ * hashtables, grow the hashtable if collisions would require
+ * us to move a lot of entries. The most likely cause of such
+ * imbalance is filling a (currently) small table, from a
+ * currently big one, in hash-table order. Don't grow if the
+ * hashtable would be too empty, to prevent quick space
+ * explosion for some weird edge cases.
+ */
+ if (unlikely(++emptydist > SH_GROW_MAX_MOVE) &&
+ ((double) tb->members / tb->size) >= SH_GROW_MIN_FILLFACTOR)
+ {
+ tb->grow_threshold = 0;
+ goto restart;
+ }
+ }
+
+ /* shift forward, starting at last occupied element */
+
+ /*
+ * TODO: This could be optimized to be one memcpy in many cases,
+ * excepting wrapping around at the end of ->data. Hasn't shown up
+ * in profiles so far though.
+ */
+ moveelem = emptyelem;
+ while (moveelem != curelem)
+ {
+ SH_ELEMENT_TYPE *moveentry;
+
+ moveelem = SH_PREV(tb, moveelem, startelem);
+ moveentry = &data[moveelem];
+
+ memcpy(lastentry, moveentry, sizeof(SH_ELEMENT_TYPE));
+ lastentry = moveentry;
+ }
+
+ /* and fill the now empty spot */
+ tb->members++;
+
+ entry->SH_KEY = key;
+#ifdef SH_STORE_HASH
+ SH_GET_HASH(tb, entry) = hash;
+#endif
+ entry->status = SH_STATUS_IN_USE;
+ *found = false;
+ return entry;
+ }
+
+ curelem = SH_NEXT(tb, curelem, startelem);
+ insertdist++;
+
+ /*
+ * To avoid negative consequences from overly imbalanced hashtables,
+ * grow the hashtable if collisions lead to large runs. The most
+ * likely cause of such imbalance is filling a (currently) small
+ * table, from a currently big one, in hash-table order. Don't grow
+ * if the hashtable would be too empty, to prevent quick space
+ * explosion for some weird edge cases.
+ */
+ if (unlikely(insertdist > SH_GROW_MAX_DIB) &&
+ ((double) tb->members / tb->size) >= SH_GROW_MIN_FILLFACTOR)
+ {
+ tb->grow_threshold = 0;
+ goto restart;
+ }
+ }
+}
+
+/*
+ * Insert the key key into the hash-table, set *found to true if the key
+ * already exists, false otherwise. Returns the hash-table entry in either
+ * case.
+ */
+SH_SCOPE SH_ELEMENT_TYPE *
+SH_INSERT(SH_TYPE * tb, SH_KEY_TYPE key, bool *found)
+{
+ uint32 hash = SH_HASH_KEY(tb, key);
+
+ return SH_INSERT_HASH_INTERNAL(tb, key, hash, found);
+}
+
+/*
+ * Insert the key key into the hash-table using an already-calculated
+ * hash. Set *found to true if the key already exists, false
+ * otherwise. Returns the hash-table entry in either case.
+ */
+SH_SCOPE SH_ELEMENT_TYPE *
+SH_INSERT_HASH(SH_TYPE * tb, SH_KEY_TYPE key, uint32 hash, bool *found)
+{
+ return SH_INSERT_HASH_INTERNAL(tb, key, hash, found);
+}
+
+/*
+ * This is a separate static inline function, so it can be reliably be inlined
+ * into its wrapper functions even if SH_SCOPE is extern.
+ */
+static inline SH_ELEMENT_TYPE *
+SH_LOOKUP_HASH_INTERNAL(SH_TYPE * tb, SH_KEY_TYPE key, uint32 hash)
+{
+ const uint32 startelem = SH_INITIAL_BUCKET(tb, hash);
+ uint32 curelem = startelem;
+
+ while (true)
+ {
+ SH_ELEMENT_TYPE *entry = &tb->data[curelem];
+
+ if (entry->status == SH_STATUS_EMPTY)
+ {
+ return NULL;
+ }
+
+ Assert(entry->status == SH_STATUS_IN_USE);
+
+ if (SH_COMPARE_KEYS(tb, hash, key, entry))
+ return entry;
+
+ /*
+ * TODO: we could stop search based on distance. If the current
+ * buckets's distance-from-optimal is smaller than what we've skipped
+ * already, the entry doesn't exist. Probably only do so if
+ * SH_STORE_HASH is defined, to avoid re-computing hashes?
+ */
+
+ curelem = SH_NEXT(tb, curelem, startelem);
+ }
+}
+
+/*
+ * Lookup entry in hash table. Returns NULL if key not present.
+ */
+SH_SCOPE SH_ELEMENT_TYPE *
+SH_LOOKUP(SH_TYPE * tb, SH_KEY_TYPE key)
+{
+ uint32 hash = SH_HASH_KEY(tb, key);
+
+ return SH_LOOKUP_HASH_INTERNAL(tb, key, hash);
+}
+
+/*
+ * Lookup entry in hash table using an already-calculated hash.
+ *
+ * Returns NULL if key not present.
+ */
+SH_SCOPE SH_ELEMENT_TYPE *
+SH_LOOKUP_HASH(SH_TYPE * tb, SH_KEY_TYPE key, uint32 hash)
+{
+ return SH_LOOKUP_HASH_INTERNAL(tb, key, hash);
+}
+
+/*
+ * Delete entry from hash table by key. Returns whether to-be-deleted key was
+ * present.
+ */
+SH_SCOPE bool
+SH_DELETE(SH_TYPE * tb, SH_KEY_TYPE key)
+{
+ uint32 hash = SH_HASH_KEY(tb, key);
+ uint32 startelem = SH_INITIAL_BUCKET(tb, hash);
+ uint32 curelem = startelem;
+
+ while (true)
+ {
+ SH_ELEMENT_TYPE *entry = &tb->data[curelem];
+
+ if (entry->status == SH_STATUS_EMPTY)
+ return false;
+
+ if (entry->status == SH_STATUS_IN_USE &&
+ SH_COMPARE_KEYS(tb, hash, key, entry))
+ {
+ SH_ELEMENT_TYPE *lastentry = entry;
+
+ tb->members--;
+
+ /*
+ * Backward shift following elements till either an empty element
+ * or an element at its optimal position is encountered.
+ *
+ * While that sounds expensive, the average chain length is short,
+ * and deletions would otherwise require tombstones.
+ */
+ while (true)
+ {
+ SH_ELEMENT_TYPE *curentry;
+ uint32 curhash;
+ uint32 curoptimal;
+
+ curelem = SH_NEXT(tb, curelem, startelem);
+ curentry = &tb->data[curelem];
+
+ if (curentry->status != SH_STATUS_IN_USE)
+ {
+ lastentry->status = SH_STATUS_EMPTY;
+ break;
+ }
+
+ curhash = SH_ENTRY_HASH(tb, curentry);
+ curoptimal = SH_INITIAL_BUCKET(tb, curhash);
+
+ /* current is at optimal position, done */
+ if (curoptimal == curelem)
+ {
+ lastentry->status = SH_STATUS_EMPTY;
+ break;
+ }
+
+ /* shift */
+ memcpy(lastentry, curentry, sizeof(SH_ELEMENT_TYPE));
+
+ lastentry = curentry;
+ }
+
+ return true;
+ }
+
+ /* TODO: return false; if distance too big */
+
+ curelem = SH_NEXT(tb, curelem, startelem);
+ }
+}
+
+/*
+ * Delete entry from hash table by entry pointer
+ */
+SH_SCOPE void
+SH_DELETE_ITEM(SH_TYPE * tb, SH_ELEMENT_TYPE * entry)
+{
+ SH_ELEMENT_TYPE *lastentry = entry;
+ uint32 hash = SH_ENTRY_HASH(tb, entry);
+ uint32 startelem = SH_INITIAL_BUCKET(tb, hash);
+ uint32 curelem;
+
+ /* Calculate the index of 'entry' */
+ curelem = entry - &tb->data[0];
+
+ tb->members--;
+
+ /*
+ * Backward shift following elements till either an empty element or an
+ * element at its optimal position is encountered.
+ *
+ * While that sounds expensive, the average chain length is short, and
+ * deletions would otherwise require tombstones.
+ */
+ while (true)
+ {
+ SH_ELEMENT_TYPE *curentry;
+ uint32 curhash;
+ uint32 curoptimal;
+
+ curelem = SH_NEXT(tb, curelem, startelem);
+ curentry = &tb->data[curelem];
+
+ if (curentry->status != SH_STATUS_IN_USE)
+ {
+ lastentry->status = SH_STATUS_EMPTY;
+ break;
+ }
+
+ curhash = SH_ENTRY_HASH(tb, curentry);
+ curoptimal = SH_INITIAL_BUCKET(tb, curhash);
+
+ /* current is at optimal position, done */
+ if (curoptimal == curelem)
+ {
+ lastentry->status = SH_STATUS_EMPTY;
+ break;
+ }
+
+ /* shift */
+ memcpy(lastentry, curentry, sizeof(SH_ELEMENT_TYPE));
+
+ lastentry = curentry;
+ }
+}
+
+/*
+ * Initialize iterator.
+ */
+SH_SCOPE void
+SH_START_ITERATE(SH_TYPE * tb, SH_ITERATOR * iter)
+{
+ uint64 startelem = PG_UINT64_MAX;
+
+ /*
+ * Search for the first empty element. As deletions during iterations are
+ * supported, we want to start/end at an element that cannot be affected
+ * by elements being shifted.
+ */
+ for (uint32 i = 0; i < tb->size; i++)
+ {
+ SH_ELEMENT_TYPE *entry = &tb->data[i];
+
+ if (entry->status != SH_STATUS_IN_USE)
+ {
+ startelem = i;
+ break;
+ }
+ }
+
+ /* we should have found an empty element */
+ Assert(startelem < SH_MAX_SIZE);
+
+ /*
+ * Iterate backwards, that allows the current element to be deleted, even
+ * if there are backward shifts
+ */
+ iter->cur = startelem;
+ iter->end = iter->cur;
+ iter->done = false;
+}
+
+/*
+ * Initialize iterator to a specific bucket. That's really only useful for
+ * cases where callers are partially iterating over the hashspace, and that
+ * iteration deletes and inserts elements based on visited entries. Doing that
+ * repeatedly could lead to an unbalanced keyspace when always starting at the
+ * same position.
+ */
+SH_SCOPE void
+SH_START_ITERATE_AT(SH_TYPE * tb, SH_ITERATOR * iter, uint32 at)
+{
+ /*
+ * Iterate backwards, that allows the current element to be deleted, even
+ * if there are backward shifts.
+ */
+ iter->cur = at & tb->sizemask; /* ensure at is within a valid range */
+ iter->end = iter->cur;
+ iter->done = false;
+}
+
+/*
+ * Iterate over all entries in the hash-table. Return the next occupied entry,
+ * or NULL if done.
+ *
+ * During iteration the current entry in the hash table may be deleted,
+ * without leading to elements being skipped or returned twice. Additionally
+ * the rest of the table may be modified (i.e. there can be insertions or
+ * deletions), but if so, there's neither a guarantee that all nodes are
+ * visited at least once, nor a guarantee that a node is visited at most once.
+ */
+SH_SCOPE SH_ELEMENT_TYPE *
+SH_ITERATE(SH_TYPE * tb, SH_ITERATOR * iter)
+{
+ while (!iter->done)
+ {
+ SH_ELEMENT_TYPE *elem;
+
+ elem = &tb->data[iter->cur];
+
+ /* next element in backward direction */
+ iter->cur = (iter->cur - 1) & tb->sizemask;
+
+ if ((iter->cur & tb->sizemask) == (iter->end & tb->sizemask))
+ iter->done = true;
+ if (elem->status == SH_STATUS_IN_USE)
+ {
+ return elem;
+ }
+ }
+
+ return NULL;
+}
+
+/*
+ * Report some statistics about the state of the hashtable. For
+ * debugging/profiling purposes only.
+ */
+SH_SCOPE void
+SH_STAT(SH_TYPE * tb)
+{
+ uint32 max_chain_length = 0;
+ uint32 total_chain_length = 0;
+ double avg_chain_length;
+ double fillfactor;
+ uint32 i;
+
+ uint32 *collisions = (uint32 *) palloc0(tb->size * sizeof(uint32));
+ uint32 total_collisions = 0;
+ uint32 max_collisions = 0;
+ double avg_collisions;
+
+ for (i = 0; i < tb->size; i++)
+ {
+ uint32 hash;
+ uint32 optimal;
+ uint32 dist;
+ SH_ELEMENT_TYPE *elem;
+
+ elem = &tb->data[i];
+
+ if (elem->status != SH_STATUS_IN_USE)
+ continue;
+
+ hash = SH_ENTRY_HASH(tb, elem);
+ optimal = SH_INITIAL_BUCKET(tb, hash);
+ dist = SH_DISTANCE_FROM_OPTIMAL(tb, optimal, i);
+
+ if (dist > max_chain_length)
+ max_chain_length = dist;
+ total_chain_length += dist;
+
+ collisions[optimal]++;
+ }
+
+ for (i = 0; i < tb->size; i++)
+ {
+ uint32 curcoll = collisions[i];
+
+ if (curcoll == 0)
+ continue;
+
+ /* single contained element is not a collision */
+ curcoll--;
+ total_collisions += curcoll;
+ if (curcoll > max_collisions)
+ max_collisions = curcoll;
+ }
+
+ /* large enough to be worth freeing, even if just used for debugging */
+ pfree(collisions);
+
+ if (tb->members > 0)
+ {
+ fillfactor = tb->members / ((double) tb->size);
+ avg_chain_length = ((double) total_chain_length) / tb->members;
+ avg_collisions = ((double) total_collisions) / tb->members;
+ }
+ else
+ {
+ fillfactor = 0;
+ avg_chain_length = 0;
+ avg_collisions = 0;
+ }
+
+ sh_log("size: " UINT64_FORMAT ", members: %u, filled: %f, total chain: %u, max chain: %u, avg chain: %f, total_collisions: %u, max_collisions: %u, avg_collisions: %f",
+ tb->size, tb->members, fillfactor, total_chain_length, max_chain_length, avg_chain_length,
+ total_collisions, max_collisions, avg_collisions);
+}
+
+#endif /* SH_DEFINE */
+
+
+/* undefine external parameters, so next hash table can be defined */
+#undef SH_PREFIX
+#undef SH_KEY_TYPE
+#undef SH_KEY
+#undef SH_ELEMENT_TYPE
+#undef SH_HASH_KEY
+#undef SH_SCOPE
+#undef SH_DECLARE
+#undef SH_DEFINE
+#undef SH_GET_HASH
+#undef SH_STORE_HASH
+#undef SH_USE_NONDEFAULT_ALLOCATOR
+#undef SH_EQUAL
+
+/* undefine locally declared macros */
+#undef SH_MAKE_PREFIX
+#undef SH_MAKE_NAME
+#undef SH_MAKE_NAME_
+#undef SH_FILLFACTOR
+#undef SH_MAX_FILLFACTOR
+#undef SH_GROW_MAX_DIB
+#undef SH_GROW_MAX_MOVE
+#undef SH_GROW_MIN_FILLFACTOR
+#undef SH_MAX_SIZE
+
+/* types */
+#undef SH_TYPE
+#undef SH_STATUS
+#undef SH_STATUS_EMPTY
+#undef SH_STATUS_IN_USE
+#undef SH_ITERATOR
+
+/* external function names */
+#undef SH_CREATE
+#undef SH_DESTROY
+#undef SH_RESET
+#undef SH_INSERT
+#undef SH_INSERT_HASH
+#undef SH_DELETE_ITEM
+#undef SH_DELETE
+#undef SH_LOOKUP
+#undef SH_LOOKUP_HASH
+#undef SH_GROW
+#undef SH_START_ITERATE
+#undef SH_START_ITERATE_AT
+#undef SH_ITERATE
+#undef SH_ALLOCATE
+#undef SH_FREE
+#undef SH_STAT
+
+/* internal function names */
+#undef SH_COMPUTE_PARAMETERS
+#undef SH_COMPARE_KEYS
+#undef SH_INITIAL_BUCKET
+#undef SH_NEXT
+#undef SH_PREV
+#undef SH_DISTANCE_FROM_OPTIMAL
+#undef SH_ENTRY_HASH
+#undef SH_INSERT_HASH_INTERNAL
+#undef SH_LOOKUP_HASH_INTERNAL
diff --git a/pgsql/include/server/lib/sort_template.h b/pgsql/include/server/lib/sort_template.h
new file mode 100644
index 0000000000000000000000000000000000000000..1edd05c7d366b2b150803ab5429d13ce1124c9f8
--- /dev/null
+++ b/pgsql/include/server/lib/sort_template.h
@@ -0,0 +1,432 @@
+/*-------------------------------------------------------------------------
+ *
+ * sort_template.h
+ *
+ * A template for a sort algorithm that supports varying degrees of
+ * specialization.
+ *
+ * Copyright (c) 2021-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1992-1994, Regents of the University of California
+ *
+ * Usage notes:
+ *
+ * To generate functions specialized for a type, the following parameter
+ * macros should be #define'd before this file is included.
+ *
+ * - ST_SORT - the name of a sort function to be generated
+ * - ST_ELEMENT_TYPE - type of the referenced elements
+ * - ST_DECLARE - if defined the functions and types are declared
+ * - ST_DEFINE - if defined the functions and types are defined
+ * - ST_SCOPE - scope (e.g. extern, static inline) for functions
+ * - ST_CHECK_FOR_INTERRUPTS - if defined the sort is interruptible
+ *
+ * Instead of ST_ELEMENT_TYPE, ST_ELEMENT_TYPE_VOID can be defined. Then
+ * the generated functions will automatically gain an "element_size"
+ * parameter. This allows us to generate a traditional qsort function.
+ *
+ * One of the following macros must be defined, to show how to compare
+ * elements. The first two options are arbitrary expressions depending
+ * on whether an extra pass-through argument is desired, and the third
+ * option should be defined if the sort function should receive a
+ * function pointer at runtime.
+ *
+ * - ST_COMPARE(a, b) - a simple comparison expression
+ * - ST_COMPARE(a, b, arg) - variant that takes an extra argument
+ * - ST_COMPARE_RUNTIME_POINTER - sort function takes a function pointer
+ *
+ * To say that the comparator and therefore also sort function should
+ * receive an extra pass-through argument, specify the type of the
+ * argument.
+ *
+ * - ST_COMPARE_ARG_TYPE - type of extra argument
+ *
+ * The prototype of the generated sort function is:
+ *
+ * void ST_SORT(ST_ELEMENT_TYPE *data, size_t n,
+ * [size_t element_size,]
+ * [ST_SORT_compare_function compare,]
+ * [ST_COMPARE_ARG_TYPE *arg]);
+ *
+ * ST_SORT_compare_function is a function pointer of the following type:
+ *
+ * int (*)(const ST_ELEMENT_TYPE *a, const ST_ELEMENT_TYPE *b,
+ * [ST_COMPARE_ARG_TYPE *arg])
+ *
+ * HISTORY
+ *
+ * Modifications from vanilla NetBSD source:
+ * - Add do ... while() macro fix
+ * - Remove __inline, _DIAGASSERTs, __P
+ * - Remove ill-considered "swap_cnt" switch to insertion sort, in favor
+ * of a simple check for presorted input.
+ * - Take care to recurse on the smaller partition, to bound stack usage
+ * - Convert into a header that can generate specialized functions
+ *
+ * IDENTIFICATION
+ * src/include/lib/sort_template.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* $NetBSD: qsort.c,v 1.13 2003/08/07 16:43:42 agc Exp $ */
+
+/*-
+ * Copyright (c) 1992, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Qsort routine based on J. L. Bentley and M. D. McIlroy,
+ * "Engineering a sort function",
+ * Software--Practice and Experience 23 (1993) 1249-1265.
+ *
+ * We have modified their original by adding a check for already-sorted
+ * input, which seems to be a win per discussions on pgsql-hackers around
+ * 2006-03-21.
+ *
+ * Also, we recurse on the smaller partition and iterate on the larger one,
+ * which ensures we cannot recurse more than log(N) levels (since the
+ * partition recursed to is surely no more than half of the input). Bentley
+ * and McIlroy explicitly rejected doing this on the grounds that it's "not
+ * worth the effort", but we have seen crashes in the field due to stack
+ * overrun, so that judgment seems wrong.
+ */
+
+#define ST_MAKE_PREFIX(a) CppConcat(a,_)
+#define ST_MAKE_NAME(a,b) ST_MAKE_NAME_(ST_MAKE_PREFIX(a),b)
+#define ST_MAKE_NAME_(a,b) CppConcat(a,b)
+
+/*
+ * If the element type is void, we'll also need an element_size argument
+ * because we don't know the size.
+ */
+#ifdef ST_ELEMENT_TYPE_VOID
+#define ST_ELEMENT_TYPE void
+#define ST_SORT_PROTO_ELEMENT_SIZE , size_t element_size
+#define ST_SORT_INVOKE_ELEMENT_SIZE , element_size
+#else
+#define ST_SORT_PROTO_ELEMENT_SIZE
+#define ST_SORT_INVOKE_ELEMENT_SIZE
+#endif
+
+/*
+ * If the user wants to be able to pass in compare functions at runtime,
+ * we'll need to make that an argument of the sort and med3 functions.
+ */
+#ifdef ST_COMPARE_RUNTIME_POINTER
+/*
+ * The type of the comparator function pointer that ST_SORT will take, unless
+ * you've already declared a type name manually and want to use that instead of
+ * having a new one defined.
+ */
+#ifndef ST_COMPARATOR_TYPE_NAME
+#define ST_COMPARATOR_TYPE_NAME ST_MAKE_NAME(ST_SORT, compare_function)
+#endif
+#define ST_COMPARE compare
+#ifndef ST_COMPARE_ARG_TYPE
+#define ST_SORT_PROTO_COMPARE , ST_COMPARATOR_TYPE_NAME compare
+#define ST_SORT_INVOKE_COMPARE , compare
+#else
+#define ST_SORT_PROTO_COMPARE , ST_COMPARATOR_TYPE_NAME compare
+#define ST_SORT_INVOKE_COMPARE , compare
+#endif
+#else
+#define ST_SORT_PROTO_COMPARE
+#define ST_SORT_INVOKE_COMPARE
+#endif
+
+/*
+ * If the user wants to use a compare function or expression that takes an
+ * extra argument, we'll need to make that an argument of the sort, compare and
+ * med3 functions.
+ */
+#ifdef ST_COMPARE_ARG_TYPE
+#define ST_SORT_PROTO_ARG , ST_COMPARE_ARG_TYPE *arg
+#define ST_SORT_INVOKE_ARG , arg
+#else
+#define ST_SORT_PROTO_ARG
+#define ST_SORT_INVOKE_ARG
+#endif
+
+#ifdef ST_DECLARE
+
+#ifdef ST_COMPARE_RUNTIME_POINTER
+typedef int (*ST_COMPARATOR_TYPE_NAME) (const ST_ELEMENT_TYPE *,
+ const ST_ELEMENT_TYPE * ST_SORT_PROTO_ARG);
+#endif
+
+/* Declare the sort function. Note optional arguments at end. */
+ST_SCOPE void ST_SORT(ST_ELEMENT_TYPE * first, size_t n
+ ST_SORT_PROTO_ELEMENT_SIZE
+ ST_SORT_PROTO_COMPARE
+ ST_SORT_PROTO_ARG);
+
+#endif
+
+#ifdef ST_DEFINE
+
+/* sort private helper functions */
+#define ST_MED3 ST_MAKE_NAME(ST_SORT, med3)
+#define ST_SWAP ST_MAKE_NAME(ST_SORT, swap)
+#define ST_SWAPN ST_MAKE_NAME(ST_SORT, swapn)
+
+/* Users expecting to run very large sorts may need them to be interruptible. */
+#ifdef ST_CHECK_FOR_INTERRUPTS
+#define DO_CHECK_FOR_INTERRUPTS() CHECK_FOR_INTERRUPTS()
+#else
+#define DO_CHECK_FOR_INTERRUPTS()
+#endif
+
+/*
+ * Create wrapper macros that know how to invoke compare, med3 and sort with
+ * the right arguments.
+ */
+#ifdef ST_COMPARE_RUNTIME_POINTER
+#define DO_COMPARE(a_, b_) ST_COMPARE((a_), (b_) ST_SORT_INVOKE_ARG)
+#elif defined(ST_COMPARE_ARG_TYPE)
+#define DO_COMPARE(a_, b_) ST_COMPARE((a_), (b_), arg)
+#else
+#define DO_COMPARE(a_, b_) ST_COMPARE((a_), (b_))
+#endif
+#define DO_MED3(a_, b_, c_) \
+ ST_MED3((a_), (b_), (c_) \
+ ST_SORT_INVOKE_COMPARE \
+ ST_SORT_INVOKE_ARG)
+#define DO_SORT(a_, n_) \
+ ST_SORT((a_), (n_) \
+ ST_SORT_INVOKE_ELEMENT_SIZE \
+ ST_SORT_INVOKE_COMPARE \
+ ST_SORT_INVOKE_ARG)
+
+/*
+ * If we're working with void pointers, we'll use pointer arithmetic based on
+ * uint8, and use the runtime element_size to step through the array and swap
+ * elements. Otherwise we'll work with ST_ELEMENT_TYPE.
+ */
+#ifndef ST_ELEMENT_TYPE_VOID
+#define ST_POINTER_TYPE ST_ELEMENT_TYPE
+#define ST_POINTER_STEP 1
+#define DO_SWAPN(a_, b_, n_) ST_SWAPN((a_), (b_), (n_))
+#define DO_SWAP(a_, b_) ST_SWAP((a_), (b_))
+#else
+#define ST_POINTER_TYPE uint8
+#define ST_POINTER_STEP element_size
+#define DO_SWAPN(a_, b_, n_) ST_SWAPN((a_), (b_), (n_))
+#define DO_SWAP(a_, b_) DO_SWAPN((a_), (b_), element_size)
+#endif
+
+/*
+ * Find the median of three values. Currently, performance seems to be best
+ * if the comparator is inlined here, but the med3 function is not inlined
+ * in the qsort function.
+ */
+static pg_noinline ST_ELEMENT_TYPE *
+ST_MED3(ST_ELEMENT_TYPE * a,
+ ST_ELEMENT_TYPE * b,
+ ST_ELEMENT_TYPE * c
+ ST_SORT_PROTO_COMPARE
+ ST_SORT_PROTO_ARG)
+{
+ return DO_COMPARE(a, b) < 0 ?
+ (DO_COMPARE(b, c) < 0 ? b : (DO_COMPARE(a, c) < 0 ? c : a))
+ : (DO_COMPARE(b, c) > 0 ? b : (DO_COMPARE(a, c) < 0 ? a : c));
+}
+
+static inline void
+ST_SWAP(ST_POINTER_TYPE * a, ST_POINTER_TYPE * b)
+{
+ ST_POINTER_TYPE tmp = *a;
+
+ *a = *b;
+ *b = tmp;
+}
+
+static inline void
+ST_SWAPN(ST_POINTER_TYPE * a, ST_POINTER_TYPE * b, size_t n)
+{
+ for (size_t i = 0; i < n; ++i)
+ ST_SWAP(&a[i], &b[i]);
+}
+
+/*
+ * Sort an array.
+ */
+ST_SCOPE void
+ST_SORT(ST_ELEMENT_TYPE * data, size_t n
+ ST_SORT_PROTO_ELEMENT_SIZE
+ ST_SORT_PROTO_COMPARE
+ ST_SORT_PROTO_ARG)
+{
+ ST_POINTER_TYPE *a = (ST_POINTER_TYPE *) data,
+ *pa,
+ *pb,
+ *pc,
+ *pd,
+ *pl,
+ *pm,
+ *pn;
+ size_t d1,
+ d2;
+ int r,
+ presorted;
+
+loop:
+ DO_CHECK_FOR_INTERRUPTS();
+ if (n < 7)
+ {
+ for (pm = a + ST_POINTER_STEP; pm < a + n * ST_POINTER_STEP;
+ pm += ST_POINTER_STEP)
+ for (pl = pm; pl > a && DO_COMPARE(pl - ST_POINTER_STEP, pl) > 0;
+ pl -= ST_POINTER_STEP)
+ DO_SWAP(pl, pl - ST_POINTER_STEP);
+ return;
+ }
+ presorted = 1;
+ for (pm = a + ST_POINTER_STEP; pm < a + n * ST_POINTER_STEP;
+ pm += ST_POINTER_STEP)
+ {
+ DO_CHECK_FOR_INTERRUPTS();
+ if (DO_COMPARE(pm - ST_POINTER_STEP, pm) > 0)
+ {
+ presorted = 0;
+ break;
+ }
+ }
+ if (presorted)
+ return;
+ pm = a + (n / 2) * ST_POINTER_STEP;
+ if (n > 7)
+ {
+ pl = a;
+ pn = a + (n - 1) * ST_POINTER_STEP;
+ if (n > 40)
+ {
+ size_t d = (n / 8) * ST_POINTER_STEP;
+
+ pl = DO_MED3(pl, pl + d, pl + 2 * d);
+ pm = DO_MED3(pm - d, pm, pm + d);
+ pn = DO_MED3(pn - 2 * d, pn - d, pn);
+ }
+ pm = DO_MED3(pl, pm, pn);
+ }
+ DO_SWAP(a, pm);
+ pa = pb = a + ST_POINTER_STEP;
+ pc = pd = a + (n - 1) * ST_POINTER_STEP;
+ for (;;)
+ {
+ while (pb <= pc && (r = DO_COMPARE(pb, a)) <= 0)
+ {
+ if (r == 0)
+ {
+ DO_SWAP(pa, pb);
+ pa += ST_POINTER_STEP;
+ }
+ pb += ST_POINTER_STEP;
+ DO_CHECK_FOR_INTERRUPTS();
+ }
+ while (pb <= pc && (r = DO_COMPARE(pc, a)) >= 0)
+ {
+ if (r == 0)
+ {
+ DO_SWAP(pc, pd);
+ pd -= ST_POINTER_STEP;
+ }
+ pc -= ST_POINTER_STEP;
+ DO_CHECK_FOR_INTERRUPTS();
+ }
+ if (pb > pc)
+ break;
+ DO_SWAP(pb, pc);
+ pb += ST_POINTER_STEP;
+ pc -= ST_POINTER_STEP;
+ }
+ pn = a + n * ST_POINTER_STEP;
+ d1 = Min(pa - a, pb - pa);
+ DO_SWAPN(a, pb - d1, d1);
+ d1 = Min(pd - pc, pn - pd - ST_POINTER_STEP);
+ DO_SWAPN(pb, pn - d1, d1);
+ d1 = pb - pa;
+ d2 = pd - pc;
+ if (d1 <= d2)
+ {
+ /* Recurse on left partition, then iterate on right partition */
+ if (d1 > ST_POINTER_STEP)
+ DO_SORT(a, d1 / ST_POINTER_STEP);
+ if (d2 > ST_POINTER_STEP)
+ {
+ /* Iterate rather than recurse to save stack space */
+ /* DO_SORT(pn - d2, d2 / ST_POINTER_STEP) */
+ a = pn - d2;
+ n = d2 / ST_POINTER_STEP;
+ goto loop;
+ }
+ }
+ else
+ {
+ /* Recurse on right partition, then iterate on left partition */
+ if (d2 > ST_POINTER_STEP)
+ DO_SORT(pn - d2, d2 / ST_POINTER_STEP);
+ if (d1 > ST_POINTER_STEP)
+ {
+ /* Iterate rather than recurse to save stack space */
+ /* DO_SORT(a, d1 / ST_POINTER_STEP) */
+ n = d1 / ST_POINTER_STEP;
+ goto loop;
+ }
+ }
+}
+#endif
+
+#undef DO_CHECK_FOR_INTERRUPTS
+#undef DO_COMPARE
+#undef DO_MED3
+#undef DO_SORT
+#undef DO_SWAP
+#undef DO_SWAPN
+#undef ST_CHECK_FOR_INTERRUPTS
+#undef ST_COMPARATOR_TYPE_NAME
+#undef ST_COMPARE
+#undef ST_COMPARE_ARG_TYPE
+#undef ST_COMPARE_RUNTIME_POINTER
+#undef ST_ELEMENT_TYPE
+#undef ST_ELEMENT_TYPE_VOID
+#undef ST_MAKE_NAME
+#undef ST_MAKE_NAME_
+#undef ST_MAKE_PREFIX
+#undef ST_MED3
+#undef ST_POINTER_STEP
+#undef ST_POINTER_TYPE
+#undef ST_SCOPE
+#undef ST_SORT
+#undef ST_SORT_INVOKE_ARG
+#undef ST_SORT_INVOKE_COMPARE
+#undef ST_SORT_INVOKE_ELEMENT_SIZE
+#undef ST_SORT_PROTO_ARG
+#undef ST_SORT_PROTO_COMPARE
+#undef ST_SORT_PROTO_ELEMENT_SIZE
+#undef ST_SWAP
+#undef ST_SWAPN
diff --git a/pgsql/include/server/lib/stringinfo.h b/pgsql/include/server/lib/stringinfo.h
new file mode 100644
index 0000000000000000000000000000000000000000..36a416f8e0a0e3f151186b6c2b41ec96a40c3f53
--- /dev/null
+++ b/pgsql/include/server/lib/stringinfo.h
@@ -0,0 +1,161 @@
+/*-------------------------------------------------------------------------
+ *
+ * stringinfo.h
+ * Declarations/definitions for "StringInfo" functions.
+ *
+ * StringInfo provides an extensible string data type (currently limited to a
+ * length of 1GB). It can be used to buffer either ordinary C strings
+ * (null-terminated text) or arbitrary binary data. All storage is allocated
+ * with palloc() (falling back to malloc in frontend code).
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/lib/stringinfo.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef STRINGINFO_H
+#define STRINGINFO_H
+
+/*-------------------------
+ * StringInfoData holds information about an extensible string.
+ * data is the current buffer for the string (allocated with palloc).
+ * len is the current string length. There is guaranteed to be
+ * a terminating '\0' at data[len], although this is not very
+ * useful when the string holds binary data rather than text.
+ * maxlen is the allocated size in bytes of 'data', i.e. the maximum
+ * string size (including the terminating '\0' char) that we can
+ * currently store in 'data' without having to reallocate
+ * more space. We must always have maxlen > len.
+ * cursor is initialized to zero by makeStringInfo or initStringInfo,
+ * but is not otherwise touched by the stringinfo.c routines.
+ * Some routines use it to scan through a StringInfo.
+ *-------------------------
+ */
+typedef struct StringInfoData
+{
+ char *data;
+ int len;
+ int maxlen;
+ int cursor;
+} StringInfoData;
+
+typedef StringInfoData *StringInfo;
+
+
+/*------------------------
+ * There are two ways to create a StringInfo object initially:
+ *
+ * StringInfo stringptr = makeStringInfo();
+ * Both the StringInfoData and the data buffer are palloc'd.
+ *
+ * StringInfoData string;
+ * initStringInfo(&string);
+ * The data buffer is palloc'd but the StringInfoData is just local.
+ * This is the easiest approach for a StringInfo object that will
+ * only live as long as the current routine.
+ *
+ * To destroy a StringInfo, pfree() the data buffer, and then pfree() the
+ * StringInfoData if it was palloc'd. There's no special support for this.
+ *
+ * NOTE: some routines build up a string using StringInfo, and then
+ * release the StringInfoData but return the data string itself to their
+ * caller. At that point the data string looks like a plain palloc'd
+ * string.
+ *-------------------------
+ */
+
+/*------------------------
+ * makeStringInfo
+ * Create an empty 'StringInfoData' & return a pointer to it.
+ */
+extern StringInfo makeStringInfo(void);
+
+/*------------------------
+ * initStringInfo
+ * Initialize a StringInfoData struct (with previously undefined contents)
+ * to describe an empty string.
+ */
+extern void initStringInfo(StringInfo str);
+
+/*------------------------
+ * resetStringInfo
+ * Clears the current content of the StringInfo, if any. The
+ * StringInfo remains valid.
+ */
+extern void resetStringInfo(StringInfo str);
+
+/*------------------------
+ * appendStringInfo
+ * Format text data under the control of fmt (an sprintf-style format string)
+ * and append it to whatever is already in str. More space is allocated
+ * to str if necessary. This is sort of like a combination of sprintf and
+ * strcat.
+ */
+extern void appendStringInfo(StringInfo str, const char *fmt,...) pg_attribute_printf(2, 3);
+
+/*------------------------
+ * appendStringInfoVA
+ * Attempt to format text data under the control of fmt (an sprintf-style
+ * format string) and append it to whatever is already in str. If successful
+ * return zero; if not (because there's not enough space), return an estimate
+ * of the space needed, without modifying str. Typically the caller should
+ * pass the return value to enlargeStringInfo() before trying again; see
+ * appendStringInfo for standard usage pattern.
+ */
+extern int appendStringInfoVA(StringInfo str, const char *fmt, va_list args) pg_attribute_printf(2, 0);
+
+/*------------------------
+ * appendStringInfoString
+ * Append a null-terminated string to str.
+ * Like appendStringInfo(str, "%s", s) but faster.
+ */
+extern void appendStringInfoString(StringInfo str, const char *s);
+
+/*------------------------
+ * appendStringInfoChar
+ * Append a single byte to str.
+ * Like appendStringInfo(str, "%c", ch) but much faster.
+ */
+extern void appendStringInfoChar(StringInfo str, char ch);
+
+/*------------------------
+ * appendStringInfoCharMacro
+ * As above, but a macro for even more speed where it matters.
+ * Caution: str argument will be evaluated multiple times.
+ */
+#define appendStringInfoCharMacro(str,ch) \
+ (((str)->len + 1 >= (str)->maxlen) ? \
+ appendStringInfoChar(str, ch) : \
+ (void)((str)->data[(str)->len] = (ch), (str)->data[++(str)->len] = '\0'))
+
+/*------------------------
+ * appendStringInfoSpaces
+ * Append a given number of spaces to str.
+ */
+extern void appendStringInfoSpaces(StringInfo str, int count);
+
+/*------------------------
+ * appendBinaryStringInfo
+ * Append arbitrary binary data to a StringInfo, allocating more space
+ * if necessary.
+ */
+extern void appendBinaryStringInfo(StringInfo str,
+ const void *data, int datalen);
+
+/*------------------------
+ * appendBinaryStringInfoNT
+ * Append arbitrary binary data to a StringInfo, allocating more space
+ * if necessary. Does not ensure a trailing null-byte exists.
+ */
+extern void appendBinaryStringInfoNT(StringInfo str,
+ const void *data, int datalen);
+
+/*------------------------
+ * enlargeStringInfo
+ * Make sure a StringInfo's buffer can hold at least 'needed' more bytes.
+ */
+extern void enlargeStringInfo(StringInfo str, int needed);
+
+#endif /* STRINGINFO_H */
diff --git a/pgsql/include/server/libpq/auth.h b/pgsql/include/server/libpq/auth.h
new file mode 100644
index 0000000000000000000000000000000000000000..7fac05b813ffc22672ac6bc3e7054c4a88f16366
--- /dev/null
+++ b/pgsql/include/server/libpq/auth.h
@@ -0,0 +1,37 @@
+/*-------------------------------------------------------------------------
+ *
+ * auth.h
+ * Definitions for network authentication routines
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/auth.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef AUTH_H
+#define AUTH_H
+
+#include "libpq/libpq-be.h"
+
+extern PGDLLIMPORT char *pg_krb_server_keyfile;
+extern PGDLLIMPORT bool pg_krb_caseins_users;
+extern PGDLLIMPORT bool pg_gss_accept_delegation;
+
+extern void ClientAuthentication(Port *port);
+extern void sendAuthRequest(Port *port, AuthRequest areq, const char *extradata,
+ int extralen);
+
+/* Hook for plugins to get control in ClientAuthentication() */
+typedef void (*ClientAuthentication_hook_type) (Port *, int);
+extern PGDLLIMPORT ClientAuthentication_hook_type ClientAuthentication_hook;
+
+/* hook type for password manglers */
+typedef char *(*auth_password_hook_typ) (char *input);
+
+/* Default LDAP password mutator hook, can be overridden by a shared library */
+extern PGDLLIMPORT auth_password_hook_typ ldap_password_hook;
+
+#endif /* AUTH_H */
diff --git a/pgsql/include/server/libpq/be-fsstubs.h b/pgsql/include/server/libpq/be-fsstubs.h
new file mode 100644
index 0000000000000000000000000000000000000000..e70a6cb56cc5e9c8b7cb62a76eeaca9825804fd4
--- /dev/null
+++ b/pgsql/include/server/libpq/be-fsstubs.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * be-fsstubs.h
+ *
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/be-fsstubs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BE_FSSTUBS_H
+#define BE_FSSTUBS_H
+
+/*
+ * These are not fmgr-callable, but are available to C code.
+ * Probably these should have had the underscore-free names,
+ * but too late now...
+ */
+extern int lo_read(int fd, char *buf, int len);
+extern int lo_write(int fd, const char *buf, int len);
+
+/*
+ * Cleanup LOs at xact commit/abort
+ */
+extern void AtEOXact_LargeObject(bool isCommit);
+extern void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid,
+ SubTransactionId parentSubid);
+
+#endif /* BE_FSSTUBS_H */
diff --git a/pgsql/include/server/libpq/be-gssapi-common.h b/pgsql/include/server/libpq/be-gssapi-common.h
new file mode 100644
index 0000000000000000000000000000000000000000..0381f0ce771fd373d1be02de6668ae9e472ff307
--- /dev/null
+++ b/pgsql/include/server/libpq/be-gssapi-common.h
@@ -0,0 +1,33 @@
+/*-------------------------------------------------------------------------
+ *
+ * be-gssapi-common.h
+ * Definitions for GSSAPI authentication and encryption handling
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/be-gssapi-common.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef BE_GSSAPI_COMMON_H
+#define BE_GSSAPI_COMMON_H
+
+#ifdef ENABLE_GSS
+
+#if defined(HAVE_GSSAPI_H)
+#include
+#include
+#else
+#include
+#include
+#endif
+
+extern void pg_GSS_error(const char *errmsg,
+ OM_uint32 maj_stat, OM_uint32 min_stat);
+
+extern void pg_store_delegated_credential(gss_cred_id_t cred);
+#endif /* ENABLE_GSS */
+
+#endif /* BE_GSSAPI_COMMON_H */
diff --git a/pgsql/include/server/libpq/crypt.h b/pgsql/include/server/libpq/crypt.h
new file mode 100644
index 0000000000000000000000000000000000000000..ddcd27469ac4ab944f543bcedf2a19c8033ed4bf
--- /dev/null
+++ b/pgsql/include/server/libpq/crypt.h
@@ -0,0 +1,47 @@
+/*-------------------------------------------------------------------------
+ *
+ * crypt.h
+ * Interface to libpq/crypt.c
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/crypt.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_CRYPT_H
+#define PG_CRYPT_H
+
+#include "datatype/timestamp.h"
+
+/*
+ * Types of password hashes or secrets.
+ *
+ * Plaintext passwords can be passed in by the user, in a CREATE/ALTER USER
+ * command. They will be encrypted to MD5 or SCRAM-SHA-256 format, before
+ * storing on-disk, so only MD5 and SCRAM-SHA-256 passwords should appear
+ * in pg_authid.rolpassword. They are also the allowed values for the
+ * password_encryption GUC.
+ */
+typedef enum PasswordType
+{
+ PASSWORD_TYPE_PLAINTEXT = 0,
+ PASSWORD_TYPE_MD5,
+ PASSWORD_TYPE_SCRAM_SHA_256
+} PasswordType;
+
+extern PasswordType get_password_type(const char *shadow_pass);
+extern char *encrypt_password(PasswordType target_type, const char *role,
+ const char *password);
+
+extern char *get_role_password(const char *role, const char **logdetail);
+
+extern int md5_crypt_verify(const char *role, const char *shadow_pass,
+ const char *client_pass, const char *md5_salt,
+ int md5_salt_len, const char **logdetail);
+extern int plain_crypt_verify(const char *role, const char *shadow_pass,
+ const char *client_pass,
+ const char **logdetail);
+
+#endif
diff --git a/pgsql/include/server/libpq/hba.h b/pgsql/include/server/libpq/hba.h
new file mode 100644
index 0000000000000000000000000000000000000000..189f6d0df24815e508e359993b893a68c1dadaa0
--- /dev/null
+++ b/pgsql/include/server/libpq/hba.h
@@ -0,0 +1,186 @@
+/*-------------------------------------------------------------------------
+ *
+ * hba.h
+ * Interface to hba.c
+ *
+ *
+ * src/include/libpq/hba.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef HBA_H
+#define HBA_H
+
+#include "libpq/pqcomm.h" /* pgrminclude ignore */ /* needed for NetBSD */
+#include "nodes/pg_list.h"
+#include "regex/regex.h"
+
+
+/*
+ * The following enum represents the authentication methods that
+ * are supported by PostgreSQL.
+ *
+ * Note: keep this in sync with the UserAuthName array in hba.c.
+ */
+typedef enum UserAuth
+{
+ uaReject,
+ uaImplicitReject, /* Not a user-visible option */
+ uaTrust,
+ uaIdent,
+ uaPassword,
+ uaMD5,
+ uaSCRAM,
+ uaGSS,
+ uaSSPI,
+ uaPAM,
+ uaBSD,
+ uaLDAP,
+ uaCert,
+ uaRADIUS,
+ uaPeer
+#define USER_AUTH_LAST uaPeer /* Must be last value of this enum */
+} UserAuth;
+
+/*
+ * Data structures representing pg_hba.conf entries
+ */
+
+typedef enum IPCompareMethod
+{
+ ipCmpMask,
+ ipCmpSameHost,
+ ipCmpSameNet,
+ ipCmpAll
+} IPCompareMethod;
+
+typedef enum ConnType
+{
+ ctLocal,
+ ctHost,
+ ctHostSSL,
+ ctHostNoSSL,
+ ctHostGSS,
+ ctHostNoGSS,
+} ConnType;
+
+typedef enum ClientCertMode
+{
+ clientCertOff,
+ clientCertCA,
+ clientCertFull
+} ClientCertMode;
+
+typedef enum ClientCertName
+{
+ clientCertCN,
+ clientCertDN
+} ClientCertName;
+
+/*
+ * A single string token lexed from an authentication configuration file
+ * (pg_ident.conf or pg_hba.conf), together with whether the token has
+ * been quoted. If "string" begins with a slash, it may optionally
+ * contain a regular expression (currently used for pg_ident.conf when
+ * building IdentLines and for pg_hba.conf when building HbaLines).
+ */
+typedef struct AuthToken
+{
+ char *string;
+ bool quoted;
+ regex_t *regex;
+} AuthToken;
+
+typedef struct HbaLine
+{
+ char *sourcefile;
+ int linenumber;
+ char *rawline;
+ ConnType conntype;
+ List *databases;
+ List *roles;
+ struct sockaddr_storage addr;
+ int addrlen; /* zero if we don't have a valid addr */
+ struct sockaddr_storage mask;
+ int masklen; /* zero if we don't have a valid mask */
+ IPCompareMethod ip_cmp_method;
+ char *hostname;
+ UserAuth auth_method;
+ char *usermap;
+ char *pamservice;
+ bool pam_use_hostname;
+ bool ldaptls;
+ char *ldapscheme;
+ char *ldapserver;
+ int ldapport;
+ char *ldapbinddn;
+ char *ldapbindpasswd;
+ char *ldapsearchattribute;
+ char *ldapsearchfilter;
+ char *ldapbasedn;
+ int ldapscope;
+ char *ldapprefix;
+ char *ldapsuffix;
+ ClientCertMode clientcert;
+ ClientCertName clientcertname;
+ char *krb_realm;
+ bool include_realm;
+ bool compat_realm;
+ bool upn_username;
+ List *radiusservers;
+ char *radiusservers_s;
+ List *radiussecrets;
+ char *radiussecrets_s;
+ List *radiusidentifiers;
+ char *radiusidentifiers_s;
+ List *radiusports;
+ char *radiusports_s;
+} HbaLine;
+
+typedef struct IdentLine
+{
+ int linenumber;
+
+ char *usermap;
+ AuthToken *system_user;
+ AuthToken *pg_user;
+} IdentLine;
+
+/*
+ * TokenizedAuthLine represents one line lexed from an authentication
+ * configuration file. Each item in the "fields" list is a sub-list of
+ * AuthTokens. We don't emit a TokenizedAuthLine for empty or all-comment
+ * lines, so "fields" is never NIL (nor are any of its sub-lists).
+ *
+ * Exception: if an error occurs during tokenization, we might have
+ * fields == NIL, in which case err_msg != NULL.
+ */
+typedef struct TokenizedAuthLine
+{
+ List *fields; /* List of lists of AuthTokens */
+ char *file_name; /* File name of origin */
+ int line_num; /* Line number */
+ char *raw_line; /* Raw line text */
+ char *err_msg; /* Error message if any */
+} TokenizedAuthLine;
+
+/* kluge to avoid including libpq/libpq-be.h here */
+typedef struct Port hbaPort;
+
+extern bool load_hba(void);
+extern bool load_ident(void);
+extern const char *hba_authname(UserAuth auth_method);
+extern void hba_getauthmethod(hbaPort *port);
+extern int check_usermap(const char *usermap_name,
+ const char *pg_user, const char *system_user,
+ bool case_insensitive);
+extern HbaLine *parse_hba_line(TokenizedAuthLine *tok_line, int elevel);
+extern IdentLine *parse_ident_line(TokenizedAuthLine *tok_line, int elevel);
+extern bool pg_isblank(const char c);
+extern FILE *open_auth_file(const char *filename, int elevel, int depth,
+ char **err_msg);
+extern void free_auth_file(FILE *file, int depth);
+extern void tokenize_auth_file(const char *filename, FILE *file,
+ List **tok_lines, int elevel, int depth);
+
+#endif /* HBA_H */
diff --git a/pgsql/include/server/libpq/ifaddr.h b/pgsql/include/server/libpq/ifaddr.h
new file mode 100644
index 0000000000000000000000000000000000000000..fb50efe6ae708dedb3fcb37ecb89b7b689bc75f1
--- /dev/null
+++ b/pgsql/include/server/libpq/ifaddr.h
@@ -0,0 +1,30 @@
+/*-------------------------------------------------------------------------
+ *
+ * ifaddr.h
+ * IP netmask calculations, and enumerating network interfaces.
+ *
+ * Copyright (c) 2003-2023, PostgreSQL Global Development Group
+ *
+ * src/include/libpq/ifaddr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef IFADDR_H
+#define IFADDR_H
+
+#include "libpq/pqcomm.h" /* pgrminclude ignore */
+
+typedef void (*PgIfAddrCallback) (struct sockaddr *addr,
+ struct sockaddr *netmask,
+ void *cb_data);
+
+extern int pg_range_sockaddr(const struct sockaddr_storage *addr,
+ const struct sockaddr_storage *netaddr,
+ const struct sockaddr_storage *netmask);
+
+extern int pg_sockaddr_cidr_mask(struct sockaddr_storage *mask,
+ char *numbits, int family);
+
+extern int pg_foreach_ifaddr(PgIfAddrCallback callback, void *cb_data);
+
+#endif /* IFADDR_H */
diff --git a/pgsql/include/server/libpq/libpq-be-fe-helpers.h b/pgsql/include/server/libpq/libpq-be-fe-helpers.h
new file mode 100644
index 0000000000000000000000000000000000000000..41e3bb4376ae820a3f3dfb66b9c53e428f08c4e7
--- /dev/null
+++ b/pgsql/include/server/libpq/libpq-be-fe-helpers.h
@@ -0,0 +1,242 @@
+/*-------------------------------------------------------------------------
+ *
+ * libpq-be-fe-helpers.h
+ * Helper functions for using libpq in extensions
+ *
+ * Code built directly into the backend is not allowed to link to libpq
+ * directly. Extension code is allowed to use libpq however. However, libpq
+ * used in extensions has to be careful to block inside libpq, otherwise
+ * interrupts will not be processed, leading to issues like unresolvable
+ * deadlocks. Backend code also needs to take care to acquire/release an
+ * external fd for the connection, otherwise fd.c's accounting of fd's is
+ * broken.
+ *
+ * This file provides helper functions to make it easier to comply with these
+ * rules. It is a header only library as it needs to be linked into each
+ * extension using libpq, and it seems too small to be worth adding a
+ * dedicated static library for.
+ *
+ * TODO: For historical reasons the connections established here are not put
+ * into non-blocking mode. That can lead to blocking even when only the async
+ * libpq functions are used. This should be fixed.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/libpq-be-fe-helpers.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LIBPQ_BE_FE_HELPERS_H
+#define LIBPQ_BE_FE_HELPERS_H
+
+/*
+ * Despite the name, BUILDING_DLL is set only when building code directly part
+ * of the backend. Which also is where libpq isn't allowed to be
+ * used. Obviously this doesn't protect against libpq-fe.h getting included
+ * otherwise, but perhaps still protects against a few mistakes...
+ */
+#ifdef BUILDING_DLL
+#error "libpq may not be used code directly built into the backend"
+#endif
+
+#include "libpq-fe.h"
+#include "miscadmin.h"
+#include "storage/fd.h"
+#include "storage/latch.h"
+#include "utils/wait_event.h"
+
+
+static inline void libpqsrv_connect_prepare(void);
+static inline void libpqsrv_connect_internal(PGconn *conn, uint32 wait_event_info);
+
+
+/*
+ * PQconnectdb() wrapper that reserves a file descriptor and processes
+ * interrupts during connection establishment.
+ *
+ * Throws an error if AcquireExternalFD() fails, but does not throw if
+ * connection establishment itself fails. Callers need to use PQstatus() to
+ * check if connection establishment succeeded.
+ */
+static inline PGconn *
+libpqsrv_connect(const char *conninfo, uint32 wait_event_info)
+{
+ PGconn *conn = NULL;
+
+ libpqsrv_connect_prepare();
+
+ conn = PQconnectStart(conninfo);
+
+ libpqsrv_connect_internal(conn, wait_event_info);
+
+ return conn;
+}
+
+/*
+ * Like libpqsrv_connect(), except that this is a wrapper for
+ * PQconnectdbParams().
+ */
+static inline PGconn *
+libpqsrv_connect_params(const char *const *keywords,
+ const char *const *values,
+ int expand_dbname,
+ uint32 wait_event_info)
+{
+ PGconn *conn = NULL;
+
+ libpqsrv_connect_prepare();
+
+ conn = PQconnectStartParams(keywords, values, expand_dbname);
+
+ libpqsrv_connect_internal(conn, wait_event_info);
+
+ return conn;
+}
+
+/*
+ * PQfinish() wrapper that additionally releases the reserved file descriptor.
+ *
+ * It is allowed to call this with a NULL pgconn iff NULL was returned by
+ * libpqsrv_connect*.
+ */
+static inline void
+libpqsrv_disconnect(PGconn *conn)
+{
+ /*
+ * If no connection was established, we haven't reserved an FD for it (or
+ * already released it). This rule makes it easier to write PG_CATCH()
+ * handlers for this facility's users.
+ *
+ * See also libpqsrv_connect_internal().
+ */
+ if (conn == NULL)
+ return;
+
+ ReleaseExternalFD();
+ PQfinish(conn);
+}
+
+
+/* internal helper functions follow */
+
+
+/*
+ * Helper function for all connection establishment functions.
+ */
+static inline void
+libpqsrv_connect_prepare(void)
+{
+ /*
+ * We must obey fd.c's limit on non-virtual file descriptors. Assume that
+ * a PGconn represents one long-lived FD. (Doing this here also ensures
+ * that VFDs are closed if needed to make room.)
+ */
+ if (!AcquireExternalFD())
+ {
+#ifndef WIN32 /* can't write #if within ereport() macro */
+ ereport(ERROR,
+ (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
+ errmsg("could not establish connection"),
+ errdetail("There are too many open files on the local server."),
+ errhint("Raise the server's max_files_per_process and/or \"ulimit -n\" limits.")));
+#else
+ ereport(ERROR,
+ (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
+ errmsg("could not establish connection"),
+ errdetail("There are too many open files on the local server."),
+ errhint("Raise the server's max_files_per_process setting.")));
+#endif
+ }
+}
+
+/*
+ * Helper function for all connection establishment functions.
+ */
+static inline void
+libpqsrv_connect_internal(PGconn *conn, uint32 wait_event_info)
+{
+ /*
+ * With conn == NULL libpqsrv_disconnect() wouldn't release the FD. So do
+ * that here.
+ */
+ if (conn == NULL)
+ {
+ ReleaseExternalFD();
+ return;
+ }
+
+ /*
+ * Can't wait without a socket. Note that we don't want to close the libpq
+ * connection yet, so callers can emit a useful error.
+ */
+ if (PQstatus(conn) == CONNECTION_BAD)
+ return;
+
+ /*
+ * WaitLatchOrSocket() can conceivably fail, handle that case here instead
+ * of requiring all callers to do so.
+ */
+ PG_TRY();
+ {
+ PostgresPollingStatusType status;
+
+ /*
+ * Poll connection until we have OK or FAILED status.
+ *
+ * Per spec for PQconnectPoll, first wait till socket is write-ready.
+ */
+ status = PGRES_POLLING_WRITING;
+ while (status != PGRES_POLLING_OK && status != PGRES_POLLING_FAILED)
+ {
+ int io_flag;
+ int rc;
+
+ if (status == PGRES_POLLING_READING)
+ io_flag = WL_SOCKET_READABLE;
+#ifdef WIN32
+
+ /*
+ * Windows needs a different test while waiting for
+ * connection-made
+ */
+ else if (PQstatus(conn) == CONNECTION_STARTED)
+ io_flag = WL_SOCKET_CONNECTED;
+#endif
+ else
+ io_flag = WL_SOCKET_WRITEABLE;
+
+ rc = WaitLatchOrSocket(MyLatch,
+ WL_EXIT_ON_PM_DEATH | WL_LATCH_SET | io_flag,
+ PQsocket(conn),
+ 0,
+ wait_event_info);
+
+ /* Interrupted? */
+ if (rc & WL_LATCH_SET)
+ {
+ ResetLatch(MyLatch);
+ CHECK_FOR_INTERRUPTS();
+ }
+
+ /* If socket is ready, advance the libpq state machine */
+ if (rc & io_flag)
+ status = PQconnectPoll(conn);
+ }
+ }
+ PG_CATCH();
+ {
+ /*
+ * If an error is thrown here, the callers won't call
+ * libpqsrv_disconnect() with a conn, so release resources
+ * immediately.
+ */
+ ReleaseExternalFD();
+ PQfinish(conn);
+
+ PG_RE_THROW();
+ }
+ PG_END_TRY();
+}
+
+#endif /* LIBPQ_BE_FE_HELPERS_H */
diff --git a/pgsql/include/server/libpq/libpq-be.h b/pgsql/include/server/libpq/libpq-be.h
new file mode 100644
index 0000000000000000000000000000000000000000..3b2ce9908f81d685af82de64ed554524ac38f5a7
--- /dev/null
+++ b/pgsql/include/server/libpq/libpq-be.h
@@ -0,0 +1,354 @@
+/*-------------------------------------------------------------------------
+ *
+ * libpq-be.h
+ * This file contains definitions for structures and externs used
+ * by the postmaster during client authentication.
+ *
+ * Note that this is backend-internal and is NOT exported to clients.
+ * Structs that need to be client-visible are in pqcomm.h.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/libpq-be.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LIBPQ_BE_H
+#define LIBPQ_BE_H
+
+#include
+#ifdef USE_OPENSSL
+#include
+#include
+#endif
+#include
+
+#ifdef ENABLE_GSS
+#if defined(HAVE_GSSAPI_H)
+#include
+#else
+#include
+#endif /* HAVE_GSSAPI_H */
+#endif /* ENABLE_GSS */
+
+#ifdef ENABLE_SSPI
+#define SECURITY_WIN32
+#if defined(WIN32) && !defined(_MSC_VER)
+#include
+#endif
+#include
+#undef SECURITY_WIN32
+
+#ifndef ENABLE_GSS
+/*
+ * Define a fake structure compatible with GSSAPI on Unix.
+ */
+typedef struct
+{
+ void *value;
+ int length;
+} gss_buffer_desc;
+#endif
+#endif /* ENABLE_SSPI */
+
+#include "datatype/timestamp.h"
+#include "libpq/hba.h"
+#include "libpq/pqcomm.h"
+
+
+typedef enum CAC_state
+{
+ CAC_OK,
+ CAC_STARTUP,
+ CAC_SHUTDOWN,
+ CAC_RECOVERY,
+ CAC_NOTCONSISTENT,
+ CAC_TOOMANY
+} CAC_state;
+
+
+/*
+ * GSSAPI specific state information
+ */
+#if defined(ENABLE_GSS) | defined(ENABLE_SSPI)
+typedef struct
+{
+ gss_buffer_desc outbuf; /* GSSAPI output token buffer */
+#ifdef ENABLE_GSS
+ gss_cred_id_t cred; /* GSSAPI connection cred's */
+ gss_ctx_id_t ctx; /* GSSAPI connection context */
+ gss_name_t name; /* GSSAPI client name */
+ char *princ; /* GSSAPI Principal used for auth, NULL if
+ * GSSAPI auth was not used */
+ bool auth; /* GSSAPI Authentication used */
+ bool enc; /* GSSAPI encryption in use */
+ bool delegated_creds; /* GSSAPI Delegated credentials */
+#endif
+} pg_gssinfo;
+#endif
+
+/*
+ * ClientConnectionInfo includes the fields describing the client connection
+ * that are copied over to parallel workers as nothing from Port does that.
+ * The same rules apply for allocations here as for Port (everything must be
+ * malloc'd or palloc'd in TopMemoryContext).
+ *
+ * If you add a struct member here, remember to also handle serialization in
+ * SerializeClientConnectionInfo() and co.
+ */
+typedef struct ClientConnectionInfo
+{
+ /*
+ * Authenticated identity. The meaning of this identifier is dependent on
+ * auth_method; it is the identity (if any) that the user presented during
+ * the authentication cycle, before they were assigned a database role.
+ * (It is effectively the "SYSTEM-USERNAME" of a pg_ident usermap --
+ * though the exact string in use may be different, depending on pg_hba
+ * options.)
+ *
+ * authn_id is NULL if the user has not actually been authenticated, for
+ * example if the "trust" auth method is in use.
+ */
+ const char *authn_id;
+
+ /*
+ * The HBA method that determined the above authn_id. This only has
+ * meaning if authn_id is not NULL; otherwise it's undefined.
+ */
+ UserAuth auth_method;
+} ClientConnectionInfo;
+
+/*
+ * This is used by the postmaster in its communication with frontends. It
+ * contains all state information needed during this communication before the
+ * backend is run. The Port structure is kept in malloc'd memory and is
+ * still available when a backend is running (see MyProcPort). The data
+ * it points to must also be malloc'd, or else palloc'd in TopMemoryContext,
+ * so that it survives into PostgresMain execution!
+ *
+ * remote_hostname is set if we did a successful reverse lookup of the
+ * client's IP address during connection setup.
+ * remote_hostname_resolv tracks the state of hostname verification:
+ * +1 = remote_hostname is known to resolve to client's IP address
+ * -1 = remote_hostname is known NOT to resolve to client's IP address
+ * 0 = we have not done the forward DNS lookup yet
+ * -2 = there was an error in name resolution
+ * If reverse lookup of the client IP address fails, remote_hostname will be
+ * left NULL while remote_hostname_resolv is set to -2. If reverse lookup
+ * succeeds but forward lookup fails, remote_hostname_resolv is also set to -2
+ * (the case is distinguishable because remote_hostname isn't NULL). In
+ * either of the -2 cases, remote_hostname_errcode saves the lookup return
+ * code for possible later use with gai_strerror.
+ */
+
+typedef struct Port
+{
+ pgsocket sock; /* File descriptor */
+ bool noblock; /* is the socket in non-blocking mode? */
+ ProtocolVersion proto; /* FE/BE protocol version */
+ SockAddr laddr; /* local addr (postmaster) */
+ SockAddr raddr; /* remote addr (client) */
+ char *remote_host; /* name (or ip addr) of remote host */
+ char *remote_hostname; /* name (not ip addr) of remote host, if
+ * available */
+ int remote_hostname_resolv; /* see above */
+ int remote_hostname_errcode; /* see above */
+ char *remote_port; /* text rep of remote port */
+ CAC_state canAcceptConnections; /* postmaster connection status */
+
+ /*
+ * Information that needs to be saved from the startup packet and passed
+ * into backend execution. "char *" fields are NULL if not set.
+ * guc_options points to a List of alternating option names and values.
+ */
+ char *database_name;
+ char *user_name;
+ char *cmdline_options;
+ List *guc_options;
+
+ /*
+ * The startup packet application name, only used here for the "connection
+ * authorized" log message. We shouldn't use this post-startup, instead
+ * the GUC should be used as application can change it afterward.
+ */
+ char *application_name;
+
+ /*
+ * Information that needs to be held during the authentication cycle.
+ */
+ HbaLine *hba;
+
+ /*
+ * TCP keepalive and user timeout settings.
+ *
+ * default values are 0 if AF_UNIX or not yet known; current values are 0
+ * if AF_UNIX or using the default. Also, -1 in a default value means we
+ * were unable to find out the default (getsockopt failed).
+ */
+ int default_keepalives_idle;
+ int default_keepalives_interval;
+ int default_keepalives_count;
+ int default_tcp_user_timeout;
+ int keepalives_idle;
+ int keepalives_interval;
+ int keepalives_count;
+ int tcp_user_timeout;
+
+ /*
+ * GSSAPI structures.
+ */
+#if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
+
+ /*
+ * If GSSAPI is supported and used on this connection, store GSSAPI
+ * information. Even when GSSAPI is not compiled in, store a NULL pointer
+ * to keep struct offsets the same (for extension ABI compatibility).
+ */
+ pg_gssinfo *gss;
+#else
+ void *gss;
+#endif
+
+ /*
+ * SSL structures.
+ */
+ bool ssl_in_use;
+ char *peer_cn;
+ char *peer_dn;
+ bool peer_cert_valid;
+
+ /*
+ * OpenSSL structures. (Keep these last so that the locations of other
+ * fields are the same whether or not you build with SSL enabled.)
+ */
+#ifdef USE_OPENSSL
+ SSL *ssl;
+ X509 *peer;
+#endif
+} Port;
+
+#ifdef USE_SSL
+/*
+ * Hardcoded DH parameters, used in ephemeral DH keying. (See also
+ * README.SSL for more details on EDH.)
+ *
+ * This is the 2048-bit DH parameter from RFC 3526. The generation of the
+ * prime is specified in RFC 2412 Appendix E, which also discusses the
+ * design choice of the generator. Note that when loaded with OpenSSL
+ * this causes DH_check() to fail on DH_NOT_SUITABLE_GENERATOR, where
+ * leaking a bit is preferred.
+ */
+#define FILE_DH2048 \
+"-----BEGIN DH PARAMETERS-----\n\
+MIIBCAKCAQEA///////////JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxOb\n\
+IlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TELppjft\n\
+awv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT\n\
+mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdwlpZtZww1Tkq8mATxdGwIyhgh\n\
+fDKQXkYuNs474553LBgOhgObJ4Oi7Aeij7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq\n\
+5RXSJhiY+gUQFXKOWoqsqmj//////////wIBAg==\n\
+-----END DH PARAMETERS-----\n"
+
+/*
+ * These functions are implemented by the glue code specific to each
+ * SSL implementation (e.g. be-secure-openssl.c)
+ */
+
+/*
+ * Initialize global SSL context.
+ *
+ * If isServerStart is true, report any errors as FATAL (so we don't return).
+ * Otherwise, log errors at LOG level and return -1 to indicate trouble,
+ * preserving the old SSL state if any. Returns 0 if OK.
+ */
+extern int be_tls_init(bool isServerStart);
+
+/*
+ * Destroy global SSL context, if any.
+ */
+extern void be_tls_destroy(void);
+
+/*
+ * Attempt to negotiate SSL connection.
+ */
+extern int be_tls_open_server(Port *port);
+
+/*
+ * Close SSL connection.
+ */
+extern void be_tls_close(Port *port);
+
+/*
+ * Read data from a secure connection.
+ */
+extern ssize_t be_tls_read(Port *port, void *ptr, size_t len, int *waitfor);
+
+/*
+ * Write data to a secure connection.
+ */
+extern ssize_t be_tls_write(Port *port, void *ptr, size_t len, int *waitfor);
+
+/*
+ * Return information about the SSL connection.
+ */
+extern int be_tls_get_cipher_bits(Port *port);
+extern const char *be_tls_get_version(Port *port);
+extern const char *be_tls_get_cipher(Port *port);
+extern void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len);
+extern void be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len);
+extern void be_tls_get_peer_serial(Port *port, char *ptr, size_t len);
+
+/*
+ * Get the server certificate hash for SCRAM channel binding type
+ * tls-server-end-point.
+ *
+ * The result is a palloc'd hash of the server certificate with its
+ * size, and NULL if there is no certificate available.
+ *
+ * This is not supported with old versions of OpenSSL that don't have
+ * the X509_get_signature_nid() function.
+ */
+#if defined(USE_OPENSSL) && (defined(HAVE_X509_GET_SIGNATURE_NID) || defined(HAVE_X509_GET_SIGNATURE_INFO))
+#define HAVE_BE_TLS_GET_CERTIFICATE_HASH
+extern char *be_tls_get_certificate_hash(Port *port, size_t *len);
+#endif
+
+/* init hook for SSL, the default sets the password callback if appropriate */
+#ifdef USE_OPENSSL
+typedef void (*openssl_tls_init_hook_typ) (SSL_CTX *context, bool isServerStart);
+extern PGDLLIMPORT openssl_tls_init_hook_typ openssl_tls_init_hook;
+#endif
+
+#endif /* USE_SSL */
+
+#ifdef ENABLE_GSS
+/*
+ * Return information about the GSSAPI authenticated connection
+ */
+extern bool be_gssapi_get_auth(Port *port);
+extern bool be_gssapi_get_enc(Port *port);
+extern const char *be_gssapi_get_princ(Port *port);
+extern bool be_gssapi_get_delegation(Port *port);
+
+/* Read and write to a GSSAPI-encrypted connection. */
+extern ssize_t be_gssapi_read(Port *port, void *ptr, size_t len);
+extern ssize_t be_gssapi_write(Port *port, void *ptr, size_t len);
+#endif /* ENABLE_GSS */
+
+extern PGDLLIMPORT ProtocolVersion FrontendProtocol;
+extern PGDLLIMPORT ClientConnectionInfo MyClientConnectionInfo;
+
+/* TCP keepalives configuration. These are no-ops on an AF_UNIX socket. */
+
+extern int pq_getkeepalivesidle(Port *port);
+extern int pq_getkeepalivesinterval(Port *port);
+extern int pq_getkeepalivescount(Port *port);
+extern int pq_gettcpusertimeout(Port *port);
+
+extern int pq_setkeepalivesidle(int idle, Port *port);
+extern int pq_setkeepalivesinterval(int interval, Port *port);
+extern int pq_setkeepalivescount(int count, Port *port);
+extern int pq_settcpusertimeout(int timeout, Port *port);
+
+#endif /* LIBPQ_BE_H */
diff --git a/pgsql/include/server/libpq/libpq-fs.h b/pgsql/include/server/libpq/libpq-fs.h
new file mode 100644
index 0000000000000000000000000000000000000000..f89e0f9e3fb06e6e9e894038ca8156560c2ef7e5
--- /dev/null
+++ b/pgsql/include/server/libpq/libpq-fs.h
@@ -0,0 +1,24 @@
+/*-------------------------------------------------------------------------
+ *
+ * libpq-fs.h
+ * definitions for using Inversion file system routines (ie, large objects)
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/libpq-fs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LIBPQ_FS_H
+#define LIBPQ_FS_H
+
+/*
+ * Read/write mode flags for inversion (large object) calls
+ */
+
+#define INV_WRITE 0x00020000
+#define INV_READ 0x00040000
+
+#endif /* LIBPQ_FS_H */
diff --git a/pgsql/include/server/libpq/libpq.h b/pgsql/include/server/libpq/libpq.h
new file mode 100644
index 0000000000000000000000000000000000000000..50fc781f471f3e4d271b186bab82dd81779e6b8a
--- /dev/null
+++ b/pgsql/include/server/libpq/libpq.h
@@ -0,0 +1,144 @@
+/*-------------------------------------------------------------------------
+ *
+ * libpq.h
+ * POSTGRES LIBPQ buffer structure definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/libpq.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LIBPQ_H
+#define LIBPQ_H
+
+#include
+
+#include "lib/stringinfo.h"
+#include "libpq/libpq-be.h"
+#include "storage/latch.h"
+
+
+/*
+ * Callers of pq_getmessage() must supply a maximum expected message size.
+ * By convention, if there's not any specific reason to use another value,
+ * use PQ_SMALL_MESSAGE_LIMIT for messages that shouldn't be too long, and
+ * PQ_LARGE_MESSAGE_LIMIT for messages that can be long.
+ */
+#define PQ_SMALL_MESSAGE_LIMIT 10000
+#define PQ_LARGE_MESSAGE_LIMIT (MaxAllocSize - 1)
+
+typedef struct
+{
+ void (*comm_reset) (void);
+ int (*flush) (void);
+ int (*flush_if_writable) (void);
+ bool (*is_send_pending) (void);
+ int (*putmessage) (char msgtype, const char *s, size_t len);
+ void (*putmessage_noblock) (char msgtype, const char *s, size_t len);
+} PQcommMethods;
+
+extern const PGDLLIMPORT PQcommMethods *PqCommMethods;
+
+#define pq_comm_reset() (PqCommMethods->comm_reset())
+#define pq_flush() (PqCommMethods->flush())
+#define pq_flush_if_writable() (PqCommMethods->flush_if_writable())
+#define pq_is_send_pending() (PqCommMethods->is_send_pending())
+#define pq_putmessage(msgtype, s, len) \
+ (PqCommMethods->putmessage(msgtype, s, len))
+#define pq_putmessage_noblock(msgtype, s, len) \
+ (PqCommMethods->putmessage_noblock(msgtype, s, len))
+
+/*
+ * External functions.
+ */
+
+/*
+ * prototypes for functions in pqcomm.c
+ */
+extern PGDLLIMPORT WaitEventSet *FeBeWaitSet;
+
+#define FeBeWaitSetSocketPos 0
+#define FeBeWaitSetLatchPos 1
+#define FeBeWaitSetNEvents 3
+
+extern int StreamServerPort(int family, const char *hostName,
+ unsigned short portNumber, const char *unixSocketDir,
+ pgsocket ListenSocket[], int MaxListen);
+extern int StreamConnection(pgsocket server_fd, Port *port);
+extern void StreamClose(pgsocket sock);
+extern void TouchSocketFiles(void);
+extern void RemoveSocketFiles(void);
+extern void pq_init(void);
+extern int pq_getbytes(char *s, size_t len);
+extern void pq_startmsgread(void);
+extern void pq_endmsgread(void);
+extern bool pq_is_reading_msg(void);
+extern int pq_getmessage(StringInfo s, int maxlen);
+extern int pq_getbyte(void);
+extern int pq_peekbyte(void);
+extern int pq_getbyte_if_available(unsigned char *c);
+extern bool pq_buffer_has_data(void);
+extern int pq_putmessage_v2(char msgtype, const char *s, size_t len);
+extern bool pq_check_connection(void);
+
+/*
+ * prototypes for functions in be-secure.c
+ */
+extern PGDLLIMPORT char *ssl_library;
+extern PGDLLIMPORT char *ssl_cert_file;
+extern PGDLLIMPORT char *ssl_key_file;
+extern PGDLLIMPORT char *ssl_ca_file;
+extern PGDLLIMPORT char *ssl_crl_file;
+extern PGDLLIMPORT char *ssl_crl_dir;
+extern PGDLLIMPORT char *ssl_dh_params_file;
+extern PGDLLIMPORT char *ssl_passphrase_command;
+extern PGDLLIMPORT bool ssl_passphrase_command_supports_reload;
+#ifdef USE_SSL
+extern PGDLLIMPORT bool ssl_loaded_verify_locations;
+#endif
+
+extern int secure_initialize(bool isServerStart);
+extern bool secure_loaded_verify_locations(void);
+extern void secure_destroy(void);
+extern int secure_open_server(Port *port);
+extern void secure_close(Port *port);
+extern ssize_t secure_read(Port *port, void *ptr, size_t len);
+extern ssize_t secure_write(Port *port, void *ptr, size_t len);
+extern ssize_t secure_raw_read(Port *port, void *ptr, size_t len);
+extern ssize_t secure_raw_write(Port *port, const void *ptr, size_t len);
+
+/*
+ * prototypes for functions in be-secure-gssapi.c
+ */
+#ifdef ENABLE_GSS
+extern ssize_t secure_open_gssapi(Port *port);
+#endif
+
+/* GUCs */
+extern PGDLLIMPORT char *SSLCipherSuites;
+extern PGDLLIMPORT char *SSLECDHCurve;
+extern PGDLLIMPORT bool SSLPreferServerCiphers;
+extern PGDLLIMPORT int ssl_min_protocol_version;
+extern PGDLLIMPORT int ssl_max_protocol_version;
+
+enum ssl_protocol_versions
+{
+ PG_TLS_ANY = 0,
+ PG_TLS1_VERSION,
+ PG_TLS1_1_VERSION,
+ PG_TLS1_2_VERSION,
+ PG_TLS1_3_VERSION,
+};
+
+/*
+ * prototypes for functions in be-secure-common.c
+ */
+extern int run_ssl_passphrase_command(const char *prompt, bool is_server_start,
+ char *buf, int size);
+extern bool check_ssl_key_file_permissions(const char *ssl_key_file,
+ bool isServerStart);
+
+#endif /* LIBPQ_H */
diff --git a/pgsql/include/server/libpq/pqcomm.h b/pgsql/include/server/libpq/pqcomm.h
new file mode 100644
index 0000000000000000000000000000000000000000..c85090259d9d96cbb745cf5f340b7d8f8c26f9db
--- /dev/null
+++ b/pgsql/include/server/libpq/pqcomm.h
@@ -0,0 +1,163 @@
+/*-------------------------------------------------------------------------
+ *
+ * pqcomm.h
+ * Definitions common to frontends and backends.
+ *
+ * NOTE: for historical reasons, this does not correspond to pqcomm.c.
+ * pqcomm.c's routines are declared in libpq.h.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/pqcomm.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PQCOMM_H
+#define PQCOMM_H
+
+#include
+#include
+#include
+#include
+
+typedef struct
+{
+ struct sockaddr_storage addr;
+ socklen_t salen;
+} SockAddr;
+
+typedef struct
+{
+ int family;
+ SockAddr addr;
+} AddrInfo;
+
+/* Configure the UNIX socket location for the well known port. */
+
+#define UNIXSOCK_PATH(path, port, sockdir) \
+ (AssertMacro(sockdir), \
+ AssertMacro(*(sockdir) != '\0'), \
+ snprintf(path, sizeof(path), "%s/.s.PGSQL.%d", \
+ (sockdir), (port)))
+
+/*
+ * The maximum workable length of a socket path is what will fit into
+ * struct sockaddr_un. This is usually only 100 or so bytes :-(.
+ *
+ * For consistency, always pass a MAXPGPATH-sized buffer to UNIXSOCK_PATH(),
+ * then complain if the resulting string is >= UNIXSOCK_PATH_BUFLEN bytes.
+ * (Because the standard API for getaddrinfo doesn't allow it to complain in
+ * a useful way when the socket pathname is too long, we have to test for
+ * this explicitly, instead of just letting the subroutine return an error.)
+ */
+#define UNIXSOCK_PATH_BUFLEN sizeof(((struct sockaddr_un *) NULL)->sun_path)
+
+/*
+ * A host that looks either like an absolute path or starts with @ is
+ * interpreted as a Unix-domain socket address.
+ */
+static inline bool
+is_unixsock_path(const char *path)
+{
+ return is_absolute_path(path) || path[0] == '@';
+}
+
+/*
+ * These manipulate the frontend/backend protocol version number.
+ *
+ * The major number should be incremented for incompatible changes. The minor
+ * number should be incremented for compatible changes (eg. additional
+ * functionality).
+ *
+ * If a backend supports version m.n of the protocol it must actually support
+ * versions m.[0..n]. Backend support for version m-1 can be dropped after a
+ * `reasonable' length of time.
+ *
+ * A frontend isn't required to support anything other than the current
+ * version.
+ */
+
+#define PG_PROTOCOL_MAJOR(v) ((v) >> 16)
+#define PG_PROTOCOL_MINOR(v) ((v) & 0x0000ffff)
+#define PG_PROTOCOL(m,n) (((m) << 16) | (n))
+
+/*
+ * The earliest and latest frontend/backend protocol version supported.
+ * (Only protocol version 3 is currently supported)
+ */
+
+#define PG_PROTOCOL_EARLIEST PG_PROTOCOL(3,0)
+#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,0)
+
+typedef uint32 ProtocolVersion; /* FE/BE protocol version number */
+
+typedef ProtocolVersion MsgType;
+
+
+/*
+ * Packet lengths are 4 bytes in network byte order.
+ *
+ * The initial length is omitted from the packet layouts appearing below.
+ */
+
+typedef uint32 PacketLen;
+
+extern PGDLLIMPORT bool Db_user_namespace;
+
+/*
+ * In protocol 3.0 and later, the startup packet length is not fixed, but
+ * we set an arbitrary limit on it anyway. This is just to prevent simple
+ * denial-of-service attacks via sending enough data to run the server
+ * out of memory.
+ */
+#define MAX_STARTUP_PACKET_LENGTH 10000
+
+
+/* These are the authentication request codes sent by the backend. */
+
+#define AUTH_REQ_OK 0 /* User is authenticated */
+#define AUTH_REQ_KRB4 1 /* Kerberos V4. Not supported any more. */
+#define AUTH_REQ_KRB5 2 /* Kerberos V5. Not supported any more. */
+#define AUTH_REQ_PASSWORD 3 /* Password */
+#define AUTH_REQ_CRYPT 4 /* crypt password. Not supported any more. */
+#define AUTH_REQ_MD5 5 /* md5 password */
+/* 6 is available. It was used for SCM creds, not supported any more. */
+#define AUTH_REQ_GSS 7 /* GSSAPI without wrap() */
+#define AUTH_REQ_GSS_CONT 8 /* Continue GSS exchanges */
+#define AUTH_REQ_SSPI 9 /* SSPI negotiate without wrap() */
+#define AUTH_REQ_SASL 10 /* Begin SASL authentication */
+#define AUTH_REQ_SASL_CONT 11 /* Continue SASL authentication */
+#define AUTH_REQ_SASL_FIN 12 /* Final SASL message */
+#define AUTH_REQ_MAX AUTH_REQ_SASL_FIN /* maximum AUTH_REQ_* value */
+
+typedef uint32 AuthRequest;
+
+
+/*
+ * A client can also send a cancel-current-operation request to the postmaster.
+ * This is uglier than sending it directly to the client's backend, but it
+ * avoids depending on out-of-band communication facilities.
+ *
+ * The cancel request code must not match any protocol version number
+ * we're ever likely to use. This random choice should do.
+ */
+#define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678)
+
+typedef struct CancelRequestPacket
+{
+ /* Note that each field is stored in network byte order! */
+ MsgType cancelRequestCode; /* code to identify a cancel request */
+ uint32 backendPID; /* PID of client's backend */
+ uint32 cancelAuthCode; /* secret key to authorize cancel */
+} CancelRequestPacket;
+
+
+/*
+ * A client can also start by sending a SSL or GSSAPI negotiation request to
+ * get a secure channel.
+ */
+#define NEGOTIATE_SSL_CODE PG_PROTOCOL(1234,5679)
+#define NEGOTIATE_GSS_CODE PG_PROTOCOL(1234,5680)
+
+#endif /* PQCOMM_H */
diff --git a/pgsql/include/server/libpq/pqformat.h b/pgsql/include/server/libpq/pqformat.h
new file mode 100644
index 0000000000000000000000000000000000000000..0d2f958af33dd12b753364b5bbf28e19a8e8c8ca
--- /dev/null
+++ b/pgsql/include/server/libpq/pqformat.h
@@ -0,0 +1,210 @@
+/*-------------------------------------------------------------------------
+ *
+ * pqformat.h
+ * Definitions for formatting and parsing frontend/backend messages
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/pqformat.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PQFORMAT_H
+#define PQFORMAT_H
+
+#include "lib/stringinfo.h"
+#include "mb/pg_wchar.h"
+#include "port/pg_bswap.h"
+
+extern void pq_beginmessage(StringInfo buf, char msgtype);
+extern void pq_beginmessage_reuse(StringInfo buf, char msgtype);
+extern void pq_endmessage(StringInfo buf);
+extern void pq_endmessage_reuse(StringInfo buf);
+
+extern void pq_sendbytes(StringInfo buf, const void *data, int datalen);
+extern void pq_sendcountedtext(StringInfo buf, const char *str, int slen,
+ bool countincludesself);
+extern void pq_sendtext(StringInfo buf, const char *str, int slen);
+extern void pq_sendstring(StringInfo buf, const char *str);
+extern void pq_send_ascii_string(StringInfo buf, const char *str);
+extern void pq_sendfloat4(StringInfo buf, float4 f);
+extern void pq_sendfloat8(StringInfo buf, float8 f);
+
+/*
+ * Append a [u]int8 to a StringInfo buffer, which already has enough space
+ * preallocated.
+ *
+ * The use of pg_restrict allows the compiler to optimize the code based on
+ * the assumption that buf, buf->len, buf->data and *buf->data don't
+ * overlap. Without the annotation buf->len etc cannot be kept in a register
+ * over subsequent pq_writeintN calls.
+ *
+ * The use of StringInfoData * rather than StringInfo is due to MSVC being
+ * overly picky and demanding a * before a restrict.
+ */
+static inline void
+pq_writeint8(StringInfoData *pg_restrict buf, uint8 i)
+{
+ uint8 ni = i;
+
+ Assert(buf->len + (int) sizeof(uint8) <= buf->maxlen);
+ memcpy((char *pg_restrict) (buf->data + buf->len), &ni, sizeof(uint8));
+ buf->len += sizeof(uint8);
+}
+
+/*
+ * Append a [u]int16 to a StringInfo buffer, which already has enough space
+ * preallocated.
+ */
+static inline void
+pq_writeint16(StringInfoData *pg_restrict buf, uint16 i)
+{
+ uint16 ni = pg_hton16(i);
+
+ Assert(buf->len + (int) sizeof(uint16) <= buf->maxlen);
+ memcpy((char *pg_restrict) (buf->data + buf->len), &ni, sizeof(uint16));
+ buf->len += sizeof(uint16);
+}
+
+/*
+ * Append a [u]int32 to a StringInfo buffer, which already has enough space
+ * preallocated.
+ */
+static inline void
+pq_writeint32(StringInfoData *pg_restrict buf, uint32 i)
+{
+ uint32 ni = pg_hton32(i);
+
+ Assert(buf->len + (int) sizeof(uint32) <= buf->maxlen);
+ memcpy((char *pg_restrict) (buf->data + buf->len), &ni, sizeof(uint32));
+ buf->len += sizeof(uint32);
+}
+
+/*
+ * Append a [u]int64 to a StringInfo buffer, which already has enough space
+ * preallocated.
+ */
+static inline void
+pq_writeint64(StringInfoData *pg_restrict buf, uint64 i)
+{
+ uint64 ni = pg_hton64(i);
+
+ Assert(buf->len + (int) sizeof(uint64) <= buf->maxlen);
+ memcpy((char *pg_restrict) (buf->data + buf->len), &ni, sizeof(uint64));
+ buf->len += sizeof(uint64);
+}
+
+/*
+ * Append a null-terminated text string (with conversion) to a buffer with
+ * preallocated space.
+ *
+ * NB: The pre-allocated space needs to be sufficient for the string after
+ * converting to client encoding.
+ *
+ * NB: passed text string must be null-terminated, and so is the data
+ * sent to the frontend.
+ */
+static inline void
+pq_writestring(StringInfoData *pg_restrict buf, const char *pg_restrict str)
+{
+ int slen = strlen(str);
+ char *p;
+
+ p = pg_server_to_client(str, slen);
+ if (p != str) /* actual conversion has been done? */
+ slen = strlen(p);
+
+ Assert(buf->len + slen + 1 <= buf->maxlen);
+
+ memcpy(((char *pg_restrict) buf->data + buf->len), p, slen + 1);
+ buf->len += slen + 1;
+
+ if (p != str)
+ pfree(p);
+}
+
+/* append a binary [u]int8 to a StringInfo buffer */
+static inline void
+pq_sendint8(StringInfo buf, uint8 i)
+{
+ enlargeStringInfo(buf, sizeof(uint8));
+ pq_writeint8(buf, i);
+}
+
+/* append a binary [u]int16 to a StringInfo buffer */
+static inline void
+pq_sendint16(StringInfo buf, uint16 i)
+{
+ enlargeStringInfo(buf, sizeof(uint16));
+ pq_writeint16(buf, i);
+}
+
+/* append a binary [u]int32 to a StringInfo buffer */
+static inline void
+pq_sendint32(StringInfo buf, uint32 i)
+{
+ enlargeStringInfo(buf, sizeof(uint32));
+ pq_writeint32(buf, i);
+}
+
+/* append a binary [u]int64 to a StringInfo buffer */
+static inline void
+pq_sendint64(StringInfo buf, uint64 i)
+{
+ enlargeStringInfo(buf, sizeof(uint64));
+ pq_writeint64(buf, i);
+}
+
+/* append a binary byte to a StringInfo buffer */
+static inline void
+pq_sendbyte(StringInfo buf, uint8 byt)
+{
+ pq_sendint8(buf, byt);
+}
+
+/*
+ * Append a binary integer to a StringInfo buffer
+ *
+ * This function is deprecated; prefer use of the functions above.
+ */
+static inline void
+pq_sendint(StringInfo buf, uint32 i, int b)
+{
+ switch (b)
+ {
+ case 1:
+ pq_sendint8(buf, (uint8) i);
+ break;
+ case 2:
+ pq_sendint16(buf, (uint16) i);
+ break;
+ case 4:
+ pq_sendint32(buf, (uint32) i);
+ break;
+ default:
+ elog(ERROR, "unsupported integer size %d", b);
+ break;
+ }
+}
+
+
+extern void pq_begintypsend(StringInfo buf);
+extern bytea *pq_endtypsend(StringInfo buf);
+
+extern void pq_puttextmessage(char msgtype, const char *str);
+extern void pq_putemptymessage(char msgtype);
+
+extern int pq_getmsgbyte(StringInfo msg);
+extern unsigned int pq_getmsgint(StringInfo msg, int b);
+extern int64 pq_getmsgint64(StringInfo msg);
+extern float4 pq_getmsgfloat4(StringInfo msg);
+extern float8 pq_getmsgfloat8(StringInfo msg);
+extern const char *pq_getmsgbytes(StringInfo msg, int datalen);
+extern void pq_copymsgbytes(StringInfo msg, char *buf, int datalen);
+extern char *pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes);
+extern const char *pq_getmsgstring(StringInfo msg);
+extern const char *pq_getmsgrawstring(StringInfo msg);
+extern void pq_getmsgend(StringInfo msg);
+
+#endif /* PQFORMAT_H */
diff --git a/pgsql/include/server/libpq/pqmq.h b/pgsql/include/server/libpq/pqmq.h
new file mode 100644
index 0000000000000000000000000000000000000000..af607edf4cbc03c356ccdae12b4ac09ec4d39517
--- /dev/null
+++ b/pgsql/include/server/libpq/pqmq.h
@@ -0,0 +1,24 @@
+/*-------------------------------------------------------------------------
+ *
+ * pqmq.h
+ * Use the frontend/backend protocol for communication over a shm_mq
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/pqmq.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PQMQ_H
+#define PQMQ_H
+
+#include "lib/stringinfo.h"
+#include "storage/shm_mq.h"
+
+extern void pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh);
+extern void pq_set_parallel_leader(pid_t pid, BackendId backend_id);
+
+extern void pq_parse_errornotice(StringInfo msg, ErrorData *edata);
+
+#endif /* PQMQ_H */
diff --git a/pgsql/include/server/libpq/pqsignal.h b/pgsql/include/server/libpq/pqsignal.h
new file mode 100644
index 0000000000000000000000000000000000000000..023bcd13bd47c94a9703f4c2b8b2d24d13c8328a
--- /dev/null
+++ b/pgsql/include/server/libpq/pqsignal.h
@@ -0,0 +1,54 @@
+/*-------------------------------------------------------------------------
+ *
+ * pqsignal.h
+ * Backend signal(2) support (see also src/port/pqsignal.c)
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/pqsignal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PQSIGNAL_H
+#define PQSIGNAL_H
+
+#include
+
+#ifdef WIN32
+/* Emulate POSIX sigset_t APIs on Windows */
+typedef int sigset_t;
+
+#define SA_RESTART 1
+#define SA_NODEFER 2
+
+struct sigaction
+{
+ void (*sa_handler) (int);
+ /* sa_sigaction not yet implemented */
+ sigset_t sa_mask;
+ int sa_flags;
+};
+
+extern int pqsigprocmask(int how, const sigset_t *set, sigset_t *oset);
+extern int pqsigaction(int signum, const struct sigaction *act,
+ struct sigaction *oldact);
+
+#define SIG_BLOCK 1
+#define SIG_UNBLOCK 2
+#define SIG_SETMASK 3
+#define sigprocmask(how, set, oset) pqsigprocmask((how), (set), (oset))
+#define sigaction(signum, act, oldact) pqsigaction((signum), (act), (oldact))
+#define sigemptyset(set) (*(set) = 0)
+#define sigfillset(set) (*(set) = ~0)
+#define sigaddset(set, signum) (*(set) |= (sigmask(signum)))
+#define sigdelset(set, signum) (*(set) &= ~(sigmask(signum)))
+#endif /* WIN32 */
+
+extern PGDLLIMPORT sigset_t UnBlockSig;
+extern PGDLLIMPORT sigset_t BlockSig;
+extern PGDLLIMPORT sigset_t StartupBlockSig;
+
+extern void pqinitmask(void);
+
+#endif /* PQSIGNAL_H */
diff --git a/pgsql/include/server/libpq/sasl.h b/pgsql/include/server/libpq/sasl.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a1b1ed0a00c0c74f93a9695eaf48de4e7eef362
--- /dev/null
+++ b/pgsql/include/server/libpq/sasl.h
@@ -0,0 +1,136 @@
+/*-------------------------------------------------------------------------
+ *
+ * sasl.h
+ * Defines the SASL mechanism interface for the backend.
+ *
+ * Each SASL mechanism defines a frontend and a backend callback structure.
+ *
+ * See src/interfaces/libpq/fe-auth-sasl.h for the frontend counterpart.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/sasl.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef PG_SASL_H
+#define PG_SASL_H
+
+#include "lib/stringinfo.h"
+#include "libpq/libpq-be.h"
+
+/* Status codes for message exchange */
+#define PG_SASL_EXCHANGE_CONTINUE 0
+#define PG_SASL_EXCHANGE_SUCCESS 1
+#define PG_SASL_EXCHANGE_FAILURE 2
+
+/*
+ * Backend SASL mechanism callbacks.
+ *
+ * To implement a backend mechanism, declare a pg_be_sasl_mech struct with
+ * appropriate callback implementations. Then pass the mechanism to
+ * CheckSASLAuth() during ClientAuthentication(), once the server has decided
+ * which authentication method to use.
+ */
+typedef struct pg_be_sasl_mech
+{
+ /*---------
+ * get_mechanisms()
+ *
+ * Retrieves the list of SASL mechanism names supported by this
+ * implementation.
+ *
+ * Input parameters:
+ *
+ * port: The client Port
+ *
+ * Output parameters:
+ *
+ * buf: A StringInfo buffer that the callback should populate with
+ * supported mechanism names. The names are appended into this
+ * StringInfo, each one ending with '\0' bytes.
+ *---------
+ */
+ void (*get_mechanisms) (Port *port, StringInfo buf);
+
+ /*---------
+ * init()
+ *
+ * Initializes mechanism-specific state for a connection. This callback
+ * must return a pointer to its allocated state, which will be passed
+ * as-is as the first argument to the other callbacks.
+ *
+ * Input parameters:
+ *
+ * port: The client Port.
+ *
+ * mech: The actual mechanism name in use by the client.
+ *
+ * shadow_pass: The stored secret for the role being authenticated, or
+ * NULL if one does not exist. Mechanisms that do not use
+ * shadow entries may ignore this parameter. If a
+ * mechanism uses shadow entries but shadow_pass is NULL,
+ * the implementation must continue the exchange as if the
+ * user existed and the password did not match, to avoid
+ * disclosing valid user names.
+ *---------
+ */
+ void *(*init) (Port *port, const char *mech, const char *shadow_pass);
+
+ /*---------
+ * exchange()
+ *
+ * Produces a server challenge to be sent to the client. The callback
+ * must return one of the PG_SASL_EXCHANGE_* values, depending on
+ * whether the exchange continues, has finished successfully, or has
+ * failed.
+ *
+ * Input parameters:
+ *
+ * state: The opaque mechanism state returned by init()
+ *
+ * input: The response data sent by the client, or NULL if the
+ * mechanism is client-first but the client did not send an
+ * initial response. (This can only happen during the first
+ * message from the client.) This is guaranteed to be
+ * null-terminated for safety, but SASL allows embedded
+ * nulls in responses, so mechanisms must be careful to
+ * check inputlen.
+ *
+ * inputlen: The length of the challenge data sent by the server, or
+ * -1 if the client did not send an initial response
+ *
+ * Output parameters, to be set by the callback function:
+ *
+ * output: A palloc'd buffer containing either the server's next
+ * challenge (if PG_SASL_EXCHANGE_CONTINUE is returned) or
+ * the server's outcome data (if PG_SASL_EXCHANGE_SUCCESS is
+ * returned and the mechanism requires data to be sent during
+ * a successful outcome). The callback should set this to
+ * NULL if the exchange is over and no output should be sent,
+ * which should correspond to either PG_SASL_EXCHANGE_FAILURE
+ * or a PG_SASL_EXCHANGE_SUCCESS with no outcome data.
+ *
+ * outputlen: The length of the challenge data. Ignored if *output is
+ * NULL.
+ *
+ * logdetail: Set to an optional DETAIL message to be printed to the
+ * server log, to disambiguate failure modes. (The client
+ * will only ever see the same generic authentication
+ * failure message.) Ignored if the exchange is completed
+ * with PG_SASL_EXCHANGE_SUCCESS.
+ *---------
+ */
+ int (*exchange) (void *state,
+ const char *input, int inputlen,
+ char **output, int *outputlen,
+ const char **logdetail);
+} pg_be_sasl_mech;
+
+/* Common implementation for auth.c */
+extern int CheckSASLAuth(const pg_be_sasl_mech *mech, Port *port,
+ char *shadow_pass, const char **logdetail);
+
+#endif /* PG_SASL_H */
diff --git a/pgsql/include/server/libpq/scram.h b/pgsql/include/server/libpq/scram.h
new file mode 100644
index 0000000000000000000000000000000000000000..310bc36517707c5b4abb28dbc346c2ea06ae3192
--- /dev/null
+++ b/pgsql/include/server/libpq/scram.h
@@ -0,0 +1,37 @@
+/*-------------------------------------------------------------------------
+ *
+ * scram.h
+ * Interface to libpq/scram.c
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/libpq/scram.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_SCRAM_H
+#define PG_SCRAM_H
+
+#include "common/cryptohash.h"
+#include "lib/stringinfo.h"
+#include "libpq/libpq-be.h"
+#include "libpq/sasl.h"
+
+/* Number of iterations when generating new secrets */
+extern PGDLLIMPORT int scram_sha_256_iterations;
+
+/* SASL implementation callbacks */
+extern PGDLLIMPORT const pg_be_sasl_mech pg_be_scram_mech;
+
+/* Routines to handle and check SCRAM-SHA-256 secret */
+extern char *pg_be_scram_build_secret(const char *password);
+extern bool parse_scram_secret(const char *secret,
+ int *iterations,
+ pg_cryptohash_type *hash_type,
+ int *key_length, char **salt,
+ uint8 *stored_key, uint8 *server_key);
+extern bool scram_verify_plain_password(const char *username,
+ const char *password, const char *secret);
+
+#endif /* PG_SCRAM_H */
diff --git a/pgsql/include/server/mb/pg_wchar.h b/pgsql/include/server/mb/pg_wchar.h
new file mode 100644
index 0000000000000000000000000000000000000000..06a56a41bb821260923a4fb16e2528c87dd4a56b
--- /dev/null
+++ b/pgsql/include/server/mb/pg_wchar.h
@@ -0,0 +1,703 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_wchar.h
+ * multibyte-character support
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/mb/pg_wchar.h
+ *
+ * NOTES
+ * This is used both by the backend and by frontends, but should not be
+ * included by libpq client programs. In particular, a libpq client
+ * should not assume that the encoding IDs used by the version of libpq
+ * it's linked to match up with the IDs declared here.
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_WCHAR_H
+#define PG_WCHAR_H
+
+/*
+ * The pg_wchar type
+ */
+typedef unsigned int pg_wchar;
+
+/*
+ * Maximum byte length of multibyte characters in any backend encoding
+ */
+#define MAX_MULTIBYTE_CHAR_LEN 4
+
+/*
+ * various definitions for EUC
+ */
+#define SS2 0x8e /* single shift 2 (JIS0201) */
+#define SS3 0x8f /* single shift 3 (JIS0212) */
+
+/*
+ * SJIS validation macros
+ */
+#define ISSJISHEAD(c) (((c) >= 0x81 && (c) <= 0x9f) || ((c) >= 0xe0 && (c) <= 0xfc))
+#define ISSJISTAIL(c) (((c) >= 0x40 && (c) <= 0x7e) || ((c) >= 0x80 && (c) <= 0xfc))
+
+/*----------------------------------------------------
+ * MULE Internal Encoding (MIC)
+ *
+ * This encoding follows the design used within XEmacs; it is meant to
+ * subsume many externally-defined character sets. Each character includes
+ * identification of the character set it belongs to, so the encoding is
+ * general but somewhat bulky.
+ *
+ * Currently PostgreSQL supports 5 types of MULE character sets:
+ *
+ * 1) 1-byte ASCII characters. Each byte is below 0x80.
+ *
+ * 2) "Official" single byte charsets such as ISO-8859-1 (Latin1).
+ * Each MULE character consists of 2 bytes: LC1 + C1, where LC1 is
+ * an identifier for the charset (in the range 0x81 to 0x8d) and C1
+ * is the character code (in the range 0xa0 to 0xff).
+ *
+ * 3) "Private" single byte charsets such as SISHENG. Each MULE
+ * character consists of 3 bytes: LCPRV1 + LC12 + C1, where LCPRV1
+ * is a private-charset flag, LC12 is an identifier for the charset,
+ * and C1 is the character code (in the range 0xa0 to 0xff).
+ * LCPRV1 is either 0x9a (if LC12 is in the range 0xa0 to 0xdf)
+ * or 0x9b (if LC12 is in the range 0xe0 to 0xef).
+ *
+ * 4) "Official" multibyte charsets such as JIS X0208. Each MULE
+ * character consists of 3 bytes: LC2 + C1 + C2, where LC2 is
+ * an identifier for the charset (in the range 0x90 to 0x99) and C1
+ * and C2 form the character code (each in the range 0xa0 to 0xff).
+ *
+ * 5) "Private" multibyte charsets such as CNS 11643-1992 Plane 3.
+ * Each MULE character consists of 4 bytes: LCPRV2 + LC22 + C1 + C2,
+ * where LCPRV2 is a private-charset flag, LC22 is an identifier for
+ * the charset, and C1 and C2 form the character code (each in the range
+ * 0xa0 to 0xff). LCPRV2 is either 0x9c (if LC22 is in the range 0xf0
+ * to 0xf4) or 0x9d (if LC22 is in the range 0xf5 to 0xfe).
+ *
+ * "Official" encodings are those that have been assigned code numbers by
+ * the XEmacs project; "private" encodings have Postgres-specific charset
+ * identifiers.
+ *
+ * See the "XEmacs Internals Manual", available at http://www.xemacs.org,
+ * for more details. Note that for historical reasons, Postgres'
+ * private-charset flag values do not match what XEmacs says they should be,
+ * so this isn't really exactly MULE (not that private charsets would be
+ * interoperable anyway).
+ *
+ * Note that XEmacs's implementation is different from what emacs does.
+ * We follow emacs's implementation, rather than XEmacs's.
+ *----------------------------------------------------
+ */
+
+/*
+ * Charset identifiers (also called "leading bytes" in the MULE documentation)
+ */
+
+/*
+ * Charset IDs for official single byte encodings (0x81-0x8e)
+ */
+#define LC_ISO8859_1 0x81 /* ISO8859 Latin 1 */
+#define LC_ISO8859_2 0x82 /* ISO8859 Latin 2 */
+#define LC_ISO8859_3 0x83 /* ISO8859 Latin 3 */
+#define LC_ISO8859_4 0x84 /* ISO8859 Latin 4 */
+#define LC_TIS620 0x85 /* Thai (not supported yet) */
+#define LC_ISO8859_7 0x86 /* Greek (not supported yet) */
+#define LC_ISO8859_6 0x87 /* Arabic (not supported yet) */
+#define LC_ISO8859_8 0x88 /* Hebrew (not supported yet) */
+#define LC_JISX0201K 0x89 /* Japanese 1 byte kana */
+#define LC_JISX0201R 0x8a /* Japanese 1 byte Roman */
+/* Note that 0x8b seems to be unused as of Emacs 20.7.
+ * However, there might be a chance that 0x8b could be used
+ * in later versions of Emacs.
+ */
+#define LC_KOI8_R 0x8b /* Cyrillic KOI8-R */
+#define LC_ISO8859_5 0x8c /* ISO8859 Cyrillic */
+#define LC_ISO8859_9 0x8d /* ISO8859 Latin 5 (not supported yet) */
+#define LC_ISO8859_15 0x8e /* ISO8859 Latin 15 (not supported yet) */
+/* #define CONTROL_1 0x8f control characters (unused) */
+
+/* Is a leading byte for "official" single byte encodings? */
+#define IS_LC1(c) ((unsigned char)(c) >= 0x81 && (unsigned char)(c) <= 0x8d)
+
+/*
+ * Charset IDs for official multibyte encodings (0x90-0x99)
+ * 0x9a-0x9d are free. 0x9e and 0x9f are reserved.
+ */
+#define LC_JISX0208_1978 0x90 /* Japanese Kanji, old JIS (not supported) */
+#define LC_GB2312_80 0x91 /* Chinese */
+#define LC_JISX0208 0x92 /* Japanese Kanji (JIS X 0208) */
+#define LC_KS5601 0x93 /* Korean */
+#define LC_JISX0212 0x94 /* Japanese Kanji (JIS X 0212) */
+#define LC_CNS11643_1 0x95 /* CNS 11643-1992 Plane 1 */
+#define LC_CNS11643_2 0x96 /* CNS 11643-1992 Plane 2 */
+#define LC_JISX0213_1 0x97 /* Japanese Kanji (JIS X 0213 Plane 1)
+ * (not supported) */
+#define LC_BIG5_1 0x98 /* Plane 1 Chinese traditional (not
+ * supported) */
+#define LC_BIG5_2 0x99 /* Plane 1 Chinese traditional (not
+ * supported) */
+
+/* Is a leading byte for "official" multibyte encodings? */
+#define IS_LC2(c) ((unsigned char)(c) >= 0x90 && (unsigned char)(c) <= 0x99)
+
+/*
+ * Postgres-specific prefix bytes for "private" single byte encodings
+ * (According to the MULE docs, we should be using 0x9e for this)
+ */
+#define LCPRV1_A 0x9a
+#define LCPRV1_B 0x9b
+#define IS_LCPRV1(c) ((unsigned char)(c) == LCPRV1_A || (unsigned char)(c) == LCPRV1_B)
+#define IS_LCPRV1_A_RANGE(c) \
+ ((unsigned char)(c) >= 0xa0 && (unsigned char)(c) <= 0xdf)
+#define IS_LCPRV1_B_RANGE(c) \
+ ((unsigned char)(c) >= 0xe0 && (unsigned char)(c) <= 0xef)
+
+/*
+ * Postgres-specific prefix bytes for "private" multibyte encodings
+ * (According to the MULE docs, we should be using 0x9f for this)
+ */
+#define LCPRV2_A 0x9c
+#define LCPRV2_B 0x9d
+#define IS_LCPRV2(c) ((unsigned char)(c) == LCPRV2_A || (unsigned char)(c) == LCPRV2_B)
+#define IS_LCPRV2_A_RANGE(c) \
+ ((unsigned char)(c) >= 0xf0 && (unsigned char)(c) <= 0xf4)
+#define IS_LCPRV2_B_RANGE(c) \
+ ((unsigned char)(c) >= 0xf5 && (unsigned char)(c) <= 0xfe)
+
+/*
+ * Charset IDs for private single byte encodings (0xa0-0xef)
+ */
+#define LC_SISHENG 0xa0 /* Chinese SiSheng characters for
+ * PinYin/ZhuYin (not supported) */
+#define LC_IPA 0xa1 /* IPA (International Phonetic
+ * Association) (not supported) */
+#define LC_VISCII_LOWER 0xa2 /* Vietnamese VISCII1.1 lower-case (not
+ * supported) */
+#define LC_VISCII_UPPER 0xa3 /* Vietnamese VISCII1.1 upper-case (not
+ * supported) */
+#define LC_ARABIC_DIGIT 0xa4 /* Arabic digit (not supported) */
+#define LC_ARABIC_1_COLUMN 0xa5 /* Arabic 1-column (not supported) */
+#define LC_ASCII_RIGHT_TO_LEFT 0xa6 /* ASCII (left half of ISO8859-1) with
+ * right-to-left direction (not
+ * supported) */
+#define LC_LAO 0xa7 /* Lao characters (ISO10646 0E80..0EDF)
+ * (not supported) */
+#define LC_ARABIC_2_COLUMN 0xa8 /* Arabic 1-column (not supported) */
+
+/*
+ * Charset IDs for private multibyte encodings (0xf0-0xff)
+ */
+#define LC_INDIAN_1_COLUMN 0xf0 /* Indian charset for 1-column width
+ * glyphs (not supported) */
+#define LC_TIBETAN_1_COLUMN 0xf1 /* Tibetan 1-column width glyphs (not
+ * supported) */
+#define LC_UNICODE_SUBSET_2 0xf2 /* Unicode characters of the range
+ * U+2500..U+33FF. (not supported) */
+#define LC_UNICODE_SUBSET_3 0xf3 /* Unicode characters of the range
+ * U+E000..U+FFFF. (not supported) */
+#define LC_UNICODE_SUBSET 0xf4 /* Unicode characters of the range
+ * U+0100..U+24FF. (not supported) */
+#define LC_ETHIOPIC 0xf5 /* Ethiopic characters (not supported) */
+#define LC_CNS11643_3 0xf6 /* CNS 11643-1992 Plane 3 */
+#define LC_CNS11643_4 0xf7 /* CNS 11643-1992 Plane 4 */
+#define LC_CNS11643_5 0xf8 /* CNS 11643-1992 Plane 5 */
+#define LC_CNS11643_6 0xf9 /* CNS 11643-1992 Plane 6 */
+#define LC_CNS11643_7 0xfa /* CNS 11643-1992 Plane 7 */
+#define LC_INDIAN_2_COLUMN 0xfb /* Indian charset for 2-column width
+ * glyphs (not supported) */
+#define LC_TIBETAN 0xfc /* Tibetan (not supported) */
+/* #define FREE 0xfd free (unused) */
+/* #define FREE 0xfe free (unused) */
+/* #define FREE 0xff free (unused) */
+
+/*----------------------------------------------------
+ * end of MULE stuff
+ *----------------------------------------------------
+ */
+
+/*
+ * PostgreSQL encoding identifiers
+ *
+ * WARNING: the order of this enum must be same as order of entries
+ * in the pg_enc2name_tbl[] array (in src/common/encnames.c), and
+ * in the pg_wchar_table[] array (in src/common/wchar.c)!
+ *
+ * If you add some encoding don't forget to check
+ * PG_ENCODING_BE_LAST macro.
+ *
+ * PG_SQL_ASCII is default encoding and must be = 0.
+ *
+ * XXX We must avoid renumbering any backend encoding until libpq's major
+ * version number is increased beyond 5; it turns out that the backend
+ * encoding IDs are effectively part of libpq's ABI as far as 8.2 initdb and
+ * psql are concerned.
+ */
+typedef enum pg_enc
+{
+ PG_SQL_ASCII = 0, /* SQL/ASCII */
+ PG_EUC_JP, /* EUC for Japanese */
+ PG_EUC_CN, /* EUC for Chinese */
+ PG_EUC_KR, /* EUC for Korean */
+ PG_EUC_TW, /* EUC for Taiwan */
+ PG_EUC_JIS_2004, /* EUC-JIS-2004 */
+ PG_UTF8, /* Unicode UTF8 */
+ PG_MULE_INTERNAL, /* Mule internal code */
+ PG_LATIN1, /* ISO-8859-1 Latin 1 */
+ PG_LATIN2, /* ISO-8859-2 Latin 2 */
+ PG_LATIN3, /* ISO-8859-3 Latin 3 */
+ PG_LATIN4, /* ISO-8859-4 Latin 4 */
+ PG_LATIN5, /* ISO-8859-9 Latin 5 */
+ PG_LATIN6, /* ISO-8859-10 Latin6 */
+ PG_LATIN7, /* ISO-8859-13 Latin7 */
+ PG_LATIN8, /* ISO-8859-14 Latin8 */
+ PG_LATIN9, /* ISO-8859-15 Latin9 */
+ PG_LATIN10, /* ISO-8859-16 Latin10 */
+ PG_WIN1256, /* windows-1256 */
+ PG_WIN1258, /* Windows-1258 */
+ PG_WIN866, /* (MS-DOS CP866) */
+ PG_WIN874, /* windows-874 */
+ PG_KOI8R, /* KOI8-R */
+ PG_WIN1251, /* windows-1251 */
+ PG_WIN1252, /* windows-1252 */
+ PG_ISO_8859_5, /* ISO-8859-5 */
+ PG_ISO_8859_6, /* ISO-8859-6 */
+ PG_ISO_8859_7, /* ISO-8859-7 */
+ PG_ISO_8859_8, /* ISO-8859-8 */
+ PG_WIN1250, /* windows-1250 */
+ PG_WIN1253, /* windows-1253 */
+ PG_WIN1254, /* windows-1254 */
+ PG_WIN1255, /* windows-1255 */
+ PG_WIN1257, /* windows-1257 */
+ PG_KOI8U, /* KOI8-U */
+ /* PG_ENCODING_BE_LAST points to the above entry */
+
+ /* followings are for client encoding only */
+ PG_SJIS, /* Shift JIS (Windows-932) */
+ PG_BIG5, /* Big5 (Windows-950) */
+ PG_GBK, /* GBK (Windows-936) */
+ PG_UHC, /* UHC (Windows-949) */
+ PG_GB18030, /* GB18030 */
+ PG_JOHAB, /* EUC for Korean JOHAB */
+ PG_SHIFT_JIS_2004, /* Shift-JIS-2004 */
+ _PG_LAST_ENCODING_ /* mark only */
+
+} pg_enc;
+
+#define PG_ENCODING_BE_LAST PG_KOI8U
+
+/*
+ * Please use these tests before access to pg_enc2name_tbl[]
+ * or to other places...
+ */
+#define PG_VALID_BE_ENCODING(_enc) \
+ ((_enc) >= 0 && (_enc) <= PG_ENCODING_BE_LAST)
+
+#define PG_ENCODING_IS_CLIENT_ONLY(_enc) \
+ ((_enc) > PG_ENCODING_BE_LAST && (_enc) < _PG_LAST_ENCODING_)
+
+#define PG_VALID_ENCODING(_enc) \
+ ((_enc) >= 0 && (_enc) < _PG_LAST_ENCODING_)
+
+/* On FE are possible all encodings */
+#define PG_VALID_FE_ENCODING(_enc) PG_VALID_ENCODING(_enc)
+
+/*
+ * When converting strings between different encodings, we assume that space
+ * for converted result is 4-to-1 growth in the worst case. The rate for
+ * currently supported encoding pairs are within 3 (SJIS JIS X0201 half width
+ * kana -> UTF8 is the worst case). So "4" should be enough for the moment.
+ *
+ * Note that this is not the same as the maximum character width in any
+ * particular encoding.
+ */
+#define MAX_CONVERSION_GROWTH 4
+
+/*
+ * Maximum byte length of a string that's required in any encoding to convert
+ * at least one character to any other encoding. In other words, if you feed
+ * MAX_CONVERSION_INPUT_LENGTH bytes to any encoding conversion function, it
+ * is guaranteed to be able to convert something without needing more input
+ * (assuming the input is valid).
+ *
+ * Currently, the maximum case is the conversion UTF8 -> SJIS JIS X0201 half
+ * width kana, where a pair of UTF-8 characters is converted into a single
+ * SHIFT_JIS_2004 character (the reverse of the worst case for
+ * MAX_CONVERSION_GROWTH). It needs 6 bytes of input. In theory, a
+ * user-defined conversion function might have more complicated cases, although
+ * for the reverse mapping you would probably also need to bump up
+ * MAX_CONVERSION_GROWTH. But there is no need to be stingy here, so make it
+ * generous.
+ */
+#define MAX_CONVERSION_INPUT_LENGTH 16
+
+/*
+ * Maximum byte length of the string equivalent to any one Unicode code point,
+ * in any backend encoding. The current value assumes that a 4-byte UTF-8
+ * character might expand by MAX_CONVERSION_GROWTH, which is a huge
+ * overestimate. But in current usage we don't allocate large multiples of
+ * this, so there's little point in being stingy.
+ */
+#define MAX_UNICODE_EQUIVALENT_STRING 16
+
+/*
+ * Table for mapping an encoding number to official encoding name and
+ * possibly other subsidiary data. Be careful to check encoding number
+ * before accessing a table entry!
+ *
+ * if (PG_VALID_ENCODING(encoding))
+ * pg_enc2name_tbl[ encoding ];
+ */
+typedef struct pg_enc2name
+{
+ const char *name;
+ pg_enc encoding;
+#ifdef WIN32
+ unsigned codepage; /* codepage for WIN32 */
+#endif
+} pg_enc2name;
+
+extern PGDLLIMPORT const pg_enc2name pg_enc2name_tbl[];
+
+/*
+ * Encoding names for gettext
+ */
+typedef struct pg_enc2gettext
+{
+ pg_enc encoding;
+ const char *name;
+} pg_enc2gettext;
+
+extern PGDLLIMPORT const pg_enc2gettext pg_enc2gettext_tbl[];
+
+/*
+ * pg_wchar stuff
+ */
+typedef int (*mb2wchar_with_len_converter) (const unsigned char *from,
+ pg_wchar *to,
+ int len);
+
+typedef int (*wchar2mb_with_len_converter) (const pg_wchar *from,
+ unsigned char *to,
+ int len);
+
+typedef int (*mblen_converter) (const unsigned char *mbstr);
+
+typedef int (*mbdisplaylen_converter) (const unsigned char *mbstr);
+
+typedef bool (*mbcharacter_incrementer) (unsigned char *mbstr, int len);
+
+typedef int (*mbchar_verifier) (const unsigned char *mbstr, int len);
+
+typedef int (*mbstr_verifier) (const unsigned char *mbstr, int len);
+
+typedef struct
+{
+ mb2wchar_with_len_converter mb2wchar_with_len; /* convert a multibyte
+ * string to a wchar */
+ wchar2mb_with_len_converter wchar2mb_with_len; /* convert a wchar string
+ * to a multibyte */
+ mblen_converter mblen; /* get byte length of a char */
+ mbdisplaylen_converter dsplen; /* get display width of a char */
+ mbchar_verifier mbverifychar; /* verify multibyte character */
+ mbstr_verifier mbverifystr; /* verify multibyte string */
+ int maxmblen; /* max bytes for a char in this encoding */
+} pg_wchar_tbl;
+
+extern PGDLLIMPORT const pg_wchar_tbl pg_wchar_table[];
+
+/*
+ * Data structures for conversions between UTF-8 and other encodings
+ * (UtfToLocal() and LocalToUtf()). In these data structures, characters of
+ * either encoding are represented by uint32 words; hence we can only support
+ * characters up to 4 bytes long. For example, the byte sequence 0xC2 0x89
+ * would be represented by 0x0000C289, and 0xE8 0xA2 0xB4 by 0x00E8A2B4.
+ *
+ * There are three possible ways a character can be mapped:
+ *
+ * 1. Using a radix tree, from source to destination code.
+ * 2. Using a sorted array of source -> destination code pairs. This
+ * method is used for "combining" characters. There are so few of
+ * them that building a radix tree would be wasteful.
+ * 3. Using a conversion function.
+ */
+
+/*
+ * Radix tree for character conversion.
+ *
+ * Logically, this is actually four different radix trees, for 1-byte,
+ * 2-byte, 3-byte and 4-byte inputs. The 1-byte tree is a simple lookup
+ * table from source to target code. The 2-byte tree consists of two levels:
+ * one lookup table for the first byte, where the value in the lookup table
+ * points to a lookup table for the second byte. And so on.
+ *
+ * Physically, all the trees are stored in one big array, in 'chars16' or
+ * 'chars32', depending on the maximum value that needs to be represented. For
+ * each level in each tree, we also store lower and upper bound of allowed
+ * values - values outside those bounds are considered invalid, and are left
+ * out of the tables.
+ *
+ * In the intermediate levels of the trees, the values stored are offsets
+ * into the chars[16|32] array.
+ *
+ * In the beginning of the chars[16|32] array, there is always a number of
+ * zeros, so that you safely follow an index from an intermediate table
+ * without explicitly checking for a zero. Following a zero any number of
+ * times will always bring you to the dummy, all-zeros table in the
+ * beginning. This helps to shave some cycles when looking up values.
+ */
+typedef struct
+{
+ /*
+ * Array containing all the values. Only one of chars16 or chars32 is
+ * used, depending on how wide the values we need to represent are.
+ */
+ const uint16 *chars16;
+ const uint32 *chars32;
+
+ /* Radix tree for 1-byte inputs */
+ uint32 b1root; /* offset of table in the chars[16|32] array */
+ uint8 b1_lower; /* min allowed value for a single byte input */
+ uint8 b1_upper; /* max allowed value for a single byte input */
+
+ /* Radix tree for 2-byte inputs */
+ uint32 b2root; /* offset of 1st byte's table */
+ uint8 b2_1_lower; /* min/max allowed value for 1st input byte */
+ uint8 b2_1_upper;
+ uint8 b2_2_lower; /* min/max allowed value for 2nd input byte */
+ uint8 b2_2_upper;
+
+ /* Radix tree for 3-byte inputs */
+ uint32 b3root; /* offset of 1st byte's table */
+ uint8 b3_1_lower; /* min/max allowed value for 1st input byte */
+ uint8 b3_1_upper;
+ uint8 b3_2_lower; /* min/max allowed value for 2nd input byte */
+ uint8 b3_2_upper;
+ uint8 b3_3_lower; /* min/max allowed value for 3rd input byte */
+ uint8 b3_3_upper;
+
+ /* Radix tree for 4-byte inputs */
+ uint32 b4root; /* offset of 1st byte's table */
+ uint8 b4_1_lower; /* min/max allowed value for 1st input byte */
+ uint8 b4_1_upper;
+ uint8 b4_2_lower; /* min/max allowed value for 2nd input byte */
+ uint8 b4_2_upper;
+ uint8 b4_3_lower; /* min/max allowed value for 3rd input byte */
+ uint8 b4_3_upper;
+ uint8 b4_4_lower; /* min/max allowed value for 4th input byte */
+ uint8 b4_4_upper;
+
+} pg_mb_radix_tree;
+
+/*
+ * UTF-8 to local code conversion map (for combined characters)
+ */
+typedef struct
+{
+ uint32 utf1; /* UTF-8 code 1 */
+ uint32 utf2; /* UTF-8 code 2 */
+ uint32 code; /* local code */
+} pg_utf_to_local_combined;
+
+/*
+ * local code to UTF-8 conversion map (for combined characters)
+ */
+typedef struct
+{
+ uint32 code; /* local code */
+ uint32 utf1; /* UTF-8 code 1 */
+ uint32 utf2; /* UTF-8 code 2 */
+} pg_local_to_utf_combined;
+
+/*
+ * callback function for algorithmic encoding conversions (in either direction)
+ *
+ * if function returns zero, it does not know how to convert the code
+ */
+typedef uint32 (*utf_local_conversion_func) (uint32 code);
+
+/*
+ * Support macro for encoding conversion functions to validate their
+ * arguments. (This could be made more compact if we included fmgr.h
+ * here, but we don't want to do that because this header file is also
+ * used by frontends.)
+ */
+#define CHECK_ENCODING_CONVERSION_ARGS(srcencoding,destencoding) \
+ check_encoding_conversion_args(PG_GETARG_INT32(0), \
+ PG_GETARG_INT32(1), \
+ PG_GETARG_INT32(4), \
+ (srcencoding), \
+ (destencoding))
+
+
+/*
+ * Some handy functions for Unicode-specific tests.
+ */
+static inline bool
+is_valid_unicode_codepoint(pg_wchar c)
+{
+ return (c > 0 && c <= 0x10FFFF);
+}
+
+static inline bool
+is_utf16_surrogate_first(pg_wchar c)
+{
+ return (c >= 0xD800 && c <= 0xDBFF);
+}
+
+static inline bool
+is_utf16_surrogate_second(pg_wchar c)
+{
+ return (c >= 0xDC00 && c <= 0xDFFF);
+}
+
+static inline pg_wchar
+surrogate_pair_to_codepoint(pg_wchar first, pg_wchar second)
+{
+ return ((first & 0x3FF) << 10) + 0x10000 + (second & 0x3FF);
+}
+
+
+/*
+ * These functions are considered part of libpq's exported API and
+ * are also declared in libpq-fe.h.
+ */
+extern int pg_char_to_encoding(const char *name);
+extern const char *pg_encoding_to_char(int encoding);
+extern int pg_valid_server_encoding_id(int encoding);
+
+/*
+ * These functions are available to frontend code that links with libpgcommon
+ * (in addition to the ones just above). The constant tables declared
+ * earlier in this file are also available from libpgcommon.
+ */
+extern int pg_encoding_mblen(int encoding, const char *mbstr);
+extern int pg_encoding_mblen_bounded(int encoding, const char *mbstr);
+extern int pg_encoding_dsplen(int encoding, const char *mbstr);
+extern int pg_encoding_verifymbchar(int encoding, const char *mbstr, int len);
+extern int pg_encoding_verifymbstr(int encoding, const char *mbstr, int len);
+extern int pg_encoding_max_length(int encoding);
+extern int pg_valid_client_encoding(const char *name);
+extern int pg_valid_server_encoding(const char *name);
+extern bool is_encoding_supported_by_icu(int encoding);
+extern const char *get_encoding_name_for_icu(int encoding);
+
+extern unsigned char *unicode_to_utf8(pg_wchar c, unsigned char *utf8string);
+extern pg_wchar utf8_to_unicode(const unsigned char *c);
+extern bool pg_utf8_islegal(const unsigned char *source, int length);
+extern int pg_utf_mblen(const unsigned char *s);
+extern int pg_mule_mblen(const unsigned char *s);
+
+/*
+ * The remaining functions are backend-only.
+ */
+extern int pg_mb2wchar(const char *from, pg_wchar *to);
+extern int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len);
+extern int pg_encoding_mb2wchar_with_len(int encoding,
+ const char *from, pg_wchar *to, int len);
+extern int pg_wchar2mb(const pg_wchar *from, char *to);
+extern int pg_wchar2mb_with_len(const pg_wchar *from, char *to, int len);
+extern int pg_encoding_wchar2mb_with_len(int encoding,
+ const pg_wchar *from, char *to, int len);
+extern int pg_char_and_wchar_strcmp(const char *s1, const pg_wchar *s2);
+extern int pg_wchar_strncmp(const pg_wchar *s1, const pg_wchar *s2, size_t n);
+extern int pg_char_and_wchar_strncmp(const char *s1, const pg_wchar *s2, size_t n);
+extern size_t pg_wchar_strlen(const pg_wchar *str);
+extern int pg_mblen(const char *mbstr);
+extern int pg_dsplen(const char *mbstr);
+extern int pg_mbstrlen(const char *mbstr);
+extern int pg_mbstrlen_with_len(const char *mbstr, int limit);
+extern int pg_mbcliplen(const char *mbstr, int len, int limit);
+extern int pg_encoding_mbcliplen(int encoding, const char *mbstr,
+ int len, int limit);
+extern int pg_mbcharcliplen(const char *mbstr, int len, int limit);
+extern int pg_database_encoding_max_length(void);
+extern mbcharacter_incrementer pg_database_encoding_character_incrementer(void);
+
+extern int PrepareClientEncoding(int encoding);
+extern int SetClientEncoding(int encoding);
+extern void InitializeClientEncoding(void);
+extern int pg_get_client_encoding(void);
+extern const char *pg_get_client_encoding_name(void);
+
+extern void SetDatabaseEncoding(int encoding);
+extern int GetDatabaseEncoding(void);
+extern const char *GetDatabaseEncodingName(void);
+extern void SetMessageEncoding(int encoding);
+extern int GetMessageEncoding(void);
+
+#ifdef ENABLE_NLS
+extern int pg_bind_textdomain_codeset(const char *domainname);
+#endif
+
+extern unsigned char *pg_do_encoding_conversion(unsigned char *src, int len,
+ int src_encoding,
+ int dest_encoding);
+extern int pg_do_encoding_conversion_buf(Oid proc,
+ int src_encoding,
+ int dest_encoding,
+ unsigned char *src, int srclen,
+ unsigned char *dest, int destlen,
+ bool noError);
+
+extern char *pg_client_to_server(const char *s, int len);
+extern char *pg_server_to_client(const char *s, int len);
+extern char *pg_any_to_server(const char *s, int len, int encoding);
+extern char *pg_server_to_any(const char *s, int len, int encoding);
+
+extern void pg_unicode_to_server(pg_wchar c, unsigned char *s);
+extern bool pg_unicode_to_server_noerror(pg_wchar c, unsigned char *s);
+
+extern unsigned short BIG5toCNS(unsigned short big5, unsigned char *lc);
+extern unsigned short CNStoBIG5(unsigned short cns, unsigned char lc);
+
+extern int UtfToLocal(const unsigned char *utf, int len,
+ unsigned char *iso,
+ const pg_mb_radix_tree *map,
+ const pg_utf_to_local_combined *cmap, int cmapsize,
+ utf_local_conversion_func conv_func,
+ int encoding, bool noError);
+extern int LocalToUtf(const unsigned char *iso, int len,
+ unsigned char *utf,
+ const pg_mb_radix_tree *map,
+ const pg_local_to_utf_combined *cmap, int cmapsize,
+ utf_local_conversion_func conv_func,
+ int encoding, bool noError);
+
+extern bool pg_verifymbstr(const char *mbstr, int len, bool noError);
+extern bool pg_verify_mbstr(int encoding, const char *mbstr, int len,
+ bool noError);
+extern int pg_verify_mbstr_len(int encoding, const char *mbstr, int len,
+ bool noError);
+
+extern void check_encoding_conversion_args(int src_encoding,
+ int dest_encoding,
+ int len,
+ int expected_src_encoding,
+ int expected_dest_encoding);
+
+extern void report_invalid_encoding(int encoding, const char *mbstr, int len) pg_attribute_noreturn();
+extern void report_untranslatable_char(int src_encoding, int dest_encoding,
+ const char *mbstr, int len) pg_attribute_noreturn();
+
+extern int local2local(const unsigned char *l, unsigned char *p, int len,
+ int src_encoding, int dest_encoding,
+ const unsigned char *tab, bool noError);
+extern int latin2mic(const unsigned char *l, unsigned char *p, int len,
+ int lc, int encoding, bool noError);
+extern int mic2latin(const unsigned char *mic, unsigned char *p, int len,
+ int lc, int encoding, bool noError);
+extern int latin2mic_with_table(const unsigned char *l, unsigned char *p,
+ int len, int lc, int encoding,
+ const unsigned char *tab, bool noError);
+extern int mic2latin_with_table(const unsigned char *mic, unsigned char *p,
+ int len, int lc, int encoding,
+ const unsigned char *tab, bool noError);
+
+#ifdef WIN32
+extern WCHAR *pgwin32_message_to_UTF16(const char *str, int len, int *utf16len);
+#endif
+
+#endif /* PG_WCHAR_H */
diff --git a/pgsql/include/server/mb/stringinfo_mb.h b/pgsql/include/server/mb/stringinfo_mb.h
new file mode 100644
index 0000000000000000000000000000000000000000..9c533f3e76e0402e19e3319c8b5b704a6c7a956f
--- /dev/null
+++ b/pgsql/include/server/mb/stringinfo_mb.h
@@ -0,0 +1,24 @@
+/*-------------------------------------------------------------------------
+ *
+ * stringinfo_mb.h
+ * multibyte support for StringInfo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/mb/stringinfo_mb.h
+ *-------------------------------------------------------------------------
+ */
+#ifndef STRINGINFO_MB_H
+#define STRINGINFO_MB_H
+
+
+#include "lib/stringinfo.h"
+
+/*
+ * Multibyte-aware StringInfo support function.
+ */
+extern void appendStringInfoStringQuoted(StringInfo str,
+ const char *s, int maxlen);
+
+#endif /* STRINGINFO_MB_H */
diff --git a/pgsql/include/server/nodes/bitmapset.h b/pgsql/include/server/nodes/bitmapset.h
new file mode 100644
index 0000000000000000000000000000000000000000..14de6a9ff1e26386e2830c71ac3e1b22eeead695
--- /dev/null
+++ b/pgsql/include/server/nodes/bitmapset.h
@@ -0,0 +1,126 @@
+/*-------------------------------------------------------------------------
+ *
+ * bitmapset.h
+ * PostgreSQL generic bitmap set package
+ *
+ * A bitmap set can represent any set of nonnegative integers, although
+ * it is mainly intended for sets where the maximum value is not large,
+ * say at most a few hundred. By convention, we always represent the
+ * empty set by a NULL pointer.
+ *
+ *
+ * Copyright (c) 2003-2023, PostgreSQL Global Development Group
+ *
+ * src/include/nodes/bitmapset.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BITMAPSET_H
+#define BITMAPSET_H
+
+#include "nodes/nodes.h"
+
+/*
+ * Forward decl to save including pg_list.h
+ */
+struct List;
+
+/*
+ * Data representation
+ *
+ * Larger bitmap word sizes generally give better performance, so long as
+ * they're not wider than the processor can handle efficiently. We use
+ * 64-bit words if pointers are that large, else 32-bit words.
+ */
+#if SIZEOF_VOID_P >= 8
+
+#define BITS_PER_BITMAPWORD 64
+typedef uint64 bitmapword; /* must be an unsigned type */
+typedef int64 signedbitmapword; /* must be the matching signed type */
+
+#else
+
+#define BITS_PER_BITMAPWORD 32
+typedef uint32 bitmapword; /* must be an unsigned type */
+typedef int32 signedbitmapword; /* must be the matching signed type */
+
+#endif
+
+typedef struct Bitmapset
+{
+ pg_node_attr(custom_copy_equal, special_read_write, no_query_jumble)
+
+ NodeTag type;
+ int nwords; /* number of words in array */
+ bitmapword words[FLEXIBLE_ARRAY_MEMBER]; /* really [nwords] */
+} Bitmapset;
+
+
+/* result of bms_subset_compare */
+typedef enum
+{
+ BMS_EQUAL, /* sets are equal */
+ BMS_SUBSET1, /* first set is a subset of the second */
+ BMS_SUBSET2, /* second set is a subset of the first */
+ BMS_DIFFERENT /* neither set is a subset of the other */
+} BMS_Comparison;
+
+/* result of bms_membership */
+typedef enum
+{
+ BMS_EMPTY_SET, /* 0 members */
+ BMS_SINGLETON, /* 1 member */
+ BMS_MULTIPLE /* >1 member */
+} BMS_Membership;
+
+
+/*
+ * function prototypes in nodes/bitmapset.c
+ */
+
+extern Bitmapset *bms_copy(const Bitmapset *a);
+extern bool bms_equal(const Bitmapset *a, const Bitmapset *b);
+extern int bms_compare(const Bitmapset *a, const Bitmapset *b);
+extern Bitmapset *bms_make_singleton(int x);
+extern void bms_free(Bitmapset *a);
+
+extern Bitmapset *bms_union(const Bitmapset *a, const Bitmapset *b);
+extern Bitmapset *bms_intersect(const Bitmapset *a, const Bitmapset *b);
+extern Bitmapset *bms_difference(const Bitmapset *a, const Bitmapset *b);
+extern bool bms_is_subset(const Bitmapset *a, const Bitmapset *b);
+extern BMS_Comparison bms_subset_compare(const Bitmapset *a, const Bitmapset *b);
+extern bool bms_is_member(int x, const Bitmapset *a);
+extern int bms_member_index(Bitmapset *a, int x);
+extern bool bms_overlap(const Bitmapset *a, const Bitmapset *b);
+extern bool bms_overlap_list(const Bitmapset *a, const struct List *b);
+extern bool bms_nonempty_difference(const Bitmapset *a, const Bitmapset *b);
+extern int bms_singleton_member(const Bitmapset *a);
+extern bool bms_get_singleton_member(const Bitmapset *a, int *member);
+extern int bms_num_members(const Bitmapset *a);
+
+/* optimized tests when we don't need to know exact membership count: */
+extern BMS_Membership bms_membership(const Bitmapset *a);
+
+/* NULL is now the only allowed representation of an empty bitmapset */
+#define bms_is_empty(a) ((a) == NULL)
+
+/* these routines recycle (modify or free) their non-const inputs: */
+
+extern Bitmapset *bms_add_member(Bitmapset *a, int x);
+extern Bitmapset *bms_del_member(Bitmapset *a, int x);
+extern Bitmapset *bms_add_members(Bitmapset *a, const Bitmapset *b);
+extern Bitmapset *bms_add_range(Bitmapset *a, int lower, int upper);
+extern Bitmapset *bms_int_members(Bitmapset *a, const Bitmapset *b);
+extern Bitmapset *bms_del_members(Bitmapset *a, const Bitmapset *b);
+extern Bitmapset *bms_join(Bitmapset *a, Bitmapset *b);
+
+/* support for iterating through the integer elements of a set: */
+extern int bms_next_member(const Bitmapset *a, int prevbit);
+extern int bms_prev_member(const Bitmapset *a, int prevbit);
+
+/* support for hashtables using Bitmapsets as keys: */
+extern uint32 bms_hash_value(const Bitmapset *a);
+extern uint32 bitmap_hash(const void *key, Size keysize);
+extern int bitmap_match(const void *key1, const void *key2, Size keysize);
+
+#endif /* BITMAPSET_H */
diff --git a/pgsql/include/server/nodes/execnodes.h b/pgsql/include/server/nodes/execnodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..49419f14f0d5b6d714ae06a073debb731f41b512
--- /dev/null
+++ b/pgsql/include/server/nodes/execnodes.h
@@ -0,0 +1,2772 @@
+/*-------------------------------------------------------------------------
+ *
+ * execnodes.h
+ * definitions for executor state nodes
+ *
+ * Most plan node types declared in plannodes.h have a corresponding
+ * execution-state node type declared here. An exception is that
+ * expression nodes (subtypes of Expr) are usually represented by steps
+ * of an ExprState, and fully handled within execExpr* - but sometimes
+ * their state needs to be shared with other parts of the executor, as
+ * for example with SubPlanState, which nodeSubplan.c has to modify.
+ *
+ * Node types declared in this file do not have any copy/equal/out/read
+ * support. (That is currently hard-wired in gen_node_support.pl, rather
+ * than being explicitly represented by pg_node_attr decorations here.)
+ * There is no need for copy, equal, or read support for executor trees.
+ * Output support could be useful for debugging; but there are a lot of
+ * specialized fields that would require custom code, so for now it's
+ * not provided.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/execnodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef EXECNODES_H
+#define EXECNODES_H
+
+#include "access/tupconvert.h"
+#include "executor/instrument.h"
+#include "fmgr.h"
+#include "lib/ilist.h"
+#include "lib/pairingheap.h"
+#include "nodes/params.h"
+#include "nodes/plannodes.h"
+#include "nodes/tidbitmap.h"
+#include "partitioning/partdefs.h"
+#include "storage/condition_variable.h"
+#include "utils/hsearch.h"
+#include "utils/queryenvironment.h"
+#include "utils/reltrigger.h"
+#include "utils/sharedtuplestore.h"
+#include "utils/snapshot.h"
+#include "utils/sortsupport.h"
+#include "utils/tuplesort.h"
+#include "utils/tuplestore.h"
+
+struct PlanState; /* forward references in this file */
+struct ParallelHashJoinState;
+struct ExecRowMark;
+struct ExprState;
+struct ExprContext;
+struct RangeTblEntry; /* avoid including parsenodes.h here */
+struct ExprEvalStep; /* avoid including execExpr.h everywhere */
+struct CopyMultiInsertBuffer;
+struct LogicalTapeSet;
+
+
+/* ----------------
+ * ExprState node
+ *
+ * ExprState represents the evaluation state for a whole expression tree.
+ * It contains instructions (in ->steps) to evaluate the expression.
+ * ----------------
+ */
+typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression,
+ struct ExprContext *econtext,
+ bool *isNull);
+
+/* Bits in ExprState->flags (see also execExpr.h for private flag bits): */
+/* expression is for use with ExecQual() */
+#define EEO_FLAG_IS_QUAL (1 << 0)
+
+typedef struct ExprState
+{
+ NodeTag type;
+
+ uint8 flags; /* bitmask of EEO_FLAG_* bits, see above */
+
+ /*
+ * Storage for result value of a scalar expression, or for individual
+ * column results within expressions built by ExecBuildProjectionInfo().
+ */
+#define FIELDNO_EXPRSTATE_RESNULL 2
+ bool resnull;
+#define FIELDNO_EXPRSTATE_RESVALUE 3
+ Datum resvalue;
+
+ /*
+ * If projecting a tuple result, this slot holds the result; else NULL.
+ */
+#define FIELDNO_EXPRSTATE_RESULTSLOT 4
+ TupleTableSlot *resultslot;
+
+ /*
+ * Instructions to compute expression's return value.
+ */
+ struct ExprEvalStep *steps;
+
+ /*
+ * Function that actually evaluates the expression. This can be set to
+ * different values depending on the complexity of the expression.
+ */
+ ExprStateEvalFunc evalfunc;
+
+ /* original expression tree, for debugging only */
+ Expr *expr;
+
+ /* private state for an evalfunc */
+ void *evalfunc_private;
+
+ /*
+ * XXX: following fields only needed during "compilation" (ExecInitExpr);
+ * could be thrown away afterwards.
+ */
+
+ int steps_len; /* number of steps currently */
+ int steps_alloc; /* allocated length of steps array */
+
+#define FIELDNO_EXPRSTATE_PARENT 11
+ struct PlanState *parent; /* parent PlanState node, if any */
+ ParamListInfo ext_params; /* for compiling PARAM_EXTERN nodes */
+
+ Datum *innermost_caseval;
+ bool *innermost_casenull;
+
+ Datum *innermost_domainval;
+ bool *innermost_domainnull;
+} ExprState;
+
+
+/* ----------------
+ * IndexInfo information
+ *
+ * this struct holds the information needed to construct new index
+ * entries for a particular index. Used for both index_build and
+ * retail creation of index entries.
+ *
+ * NumIndexAttrs total number of columns in this index
+ * NumIndexKeyAttrs number of key columns in index
+ * IndexAttrNumbers underlying-rel attribute numbers used as keys
+ * (zeroes indicate expressions). It also contains
+ * info about included columns.
+ * Expressions expr trees for expression entries, or NIL if none
+ * ExpressionsState exec state for expressions, or NIL if none
+ * Predicate partial-index predicate, or NIL if none
+ * PredicateState exec state for predicate, or NIL if none
+ * ExclusionOps Per-column exclusion operators, or NULL if none
+ * ExclusionProcs Underlying function OIDs for ExclusionOps
+ * ExclusionStrats Opclass strategy numbers for ExclusionOps
+ * UniqueOps These are like Exclusion*, but for unique indexes
+ * UniqueProcs
+ * UniqueStrats
+ * Unique is it a unique index?
+ * OpclassOptions opclass-specific options, or NULL if none
+ * ReadyForInserts is it valid for inserts?
+ * CheckedUnchanged IndexUnchanged status determined yet?
+ * IndexUnchanged aminsert hint, cached for retail inserts
+ * Concurrent are we doing a concurrent index build?
+ * BrokenHotChain did we detect any broken HOT chains?
+ * Summarizing is it a summarizing index?
+ * ParallelWorkers # of workers requested (excludes leader)
+ * Am Oid of index AM
+ * AmCache private cache area for index AM
+ * Context memory context holding this IndexInfo
+ *
+ * ii_Concurrent, ii_BrokenHotChain, and ii_ParallelWorkers are used only
+ * during index build; they're conventionally zeroed otherwise.
+ * ----------------
+ */
+typedef struct IndexInfo
+{
+ NodeTag type;
+ int ii_NumIndexAttrs; /* total number of columns in index */
+ int ii_NumIndexKeyAttrs; /* number of key columns in index */
+ AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS];
+ List *ii_Expressions; /* list of Expr */
+ List *ii_ExpressionsState; /* list of ExprState */
+ List *ii_Predicate; /* list of Expr */
+ ExprState *ii_PredicateState;
+ Oid *ii_ExclusionOps; /* array with one entry per column */
+ Oid *ii_ExclusionProcs; /* array with one entry per column */
+ uint16 *ii_ExclusionStrats; /* array with one entry per column */
+ Oid *ii_UniqueOps; /* array with one entry per column */
+ Oid *ii_UniqueProcs; /* array with one entry per column */
+ uint16 *ii_UniqueStrats; /* array with one entry per column */
+ Datum *ii_OpclassOptions; /* array with one entry per column */
+ bool ii_Unique;
+ bool ii_NullsNotDistinct;
+ bool ii_ReadyForInserts;
+ bool ii_CheckedUnchanged;
+ bool ii_IndexUnchanged;
+ bool ii_Concurrent;
+ bool ii_BrokenHotChain;
+ bool ii_Summarizing;
+ int ii_ParallelWorkers;
+ Oid ii_Am;
+ void *ii_AmCache;
+ MemoryContext ii_Context;
+} IndexInfo;
+
+/* ----------------
+ * ExprContext_CB
+ *
+ * List of callbacks to be called at ExprContext shutdown.
+ * ----------------
+ */
+typedef void (*ExprContextCallbackFunction) (Datum arg);
+
+typedef struct ExprContext_CB
+{
+ struct ExprContext_CB *next;
+ ExprContextCallbackFunction function;
+ Datum arg;
+} ExprContext_CB;
+
+/* ----------------
+ * ExprContext
+ *
+ * This class holds the "current context" information
+ * needed to evaluate expressions for doing tuple qualifications
+ * and tuple projections. For example, if an expression refers
+ * to an attribute in the current inner tuple then we need to know
+ * what the current inner tuple is and so we look at the expression
+ * context.
+ *
+ * There are two memory contexts associated with an ExprContext:
+ * * ecxt_per_query_memory is a query-lifespan context, typically the same
+ * context the ExprContext node itself is allocated in. This context
+ * can be used for purposes such as storing function call cache info.
+ * * ecxt_per_tuple_memory is a short-term context for expression results.
+ * As the name suggests, it will typically be reset once per tuple,
+ * before we begin to evaluate expressions for that tuple. Each
+ * ExprContext normally has its very own per-tuple memory context.
+ *
+ * CurrentMemoryContext should be set to ecxt_per_tuple_memory before
+ * calling ExecEvalExpr() --- see ExecEvalExprSwitchContext().
+ * ----------------
+ */
+typedef struct ExprContext
+{
+ NodeTag type;
+
+ /* Tuples that Var nodes in expression may refer to */
+#define FIELDNO_EXPRCONTEXT_SCANTUPLE 1
+ TupleTableSlot *ecxt_scantuple;
+#define FIELDNO_EXPRCONTEXT_INNERTUPLE 2
+ TupleTableSlot *ecxt_innertuple;
+#define FIELDNO_EXPRCONTEXT_OUTERTUPLE 3
+ TupleTableSlot *ecxt_outertuple;
+
+ /* Memory contexts for expression evaluation --- see notes above */
+ MemoryContext ecxt_per_query_memory;
+ MemoryContext ecxt_per_tuple_memory;
+
+ /* Values to substitute for Param nodes in expression */
+ ParamExecData *ecxt_param_exec_vals; /* for PARAM_EXEC params */
+ ParamListInfo ecxt_param_list_info; /* for other param types */
+
+ /*
+ * Values to substitute for Aggref nodes in the expressions of an Agg
+ * node, or for WindowFunc nodes within a WindowAgg node.
+ */
+#define FIELDNO_EXPRCONTEXT_AGGVALUES 8
+ Datum *ecxt_aggvalues; /* precomputed values for aggs/windowfuncs */
+#define FIELDNO_EXPRCONTEXT_AGGNULLS 9
+ bool *ecxt_aggnulls; /* null flags for aggs/windowfuncs */
+
+ /* Value to substitute for CaseTestExpr nodes in expression */
+#define FIELDNO_EXPRCONTEXT_CASEDATUM 10
+ Datum caseValue_datum;
+#define FIELDNO_EXPRCONTEXT_CASENULL 11
+ bool caseValue_isNull;
+
+ /* Value to substitute for CoerceToDomainValue nodes in expression */
+#define FIELDNO_EXPRCONTEXT_DOMAINDATUM 12
+ Datum domainValue_datum;
+#define FIELDNO_EXPRCONTEXT_DOMAINNULL 13
+ bool domainValue_isNull;
+
+ /* Link to containing EState (NULL if a standalone ExprContext) */
+ struct EState *ecxt_estate;
+
+ /* Functions to call back when ExprContext is shut down or rescanned */
+ ExprContext_CB *ecxt_callbacks;
+} ExprContext;
+
+/*
+ * Set-result status used when evaluating functions potentially returning a
+ * set.
+ */
+typedef enum
+{
+ ExprSingleResult, /* expression does not return a set */
+ ExprMultipleResult, /* this result is an element of a set */
+ ExprEndResult /* there are no more elements in the set */
+} ExprDoneCond;
+
+/*
+ * Return modes for functions returning sets. Note values must be chosen
+ * as separate bits so that a bitmask can be formed to indicate supported
+ * modes. SFRM_Materialize_Random and SFRM_Materialize_Preferred are
+ * auxiliary flags about SFRM_Materialize mode, rather than separate modes.
+ */
+typedef enum
+{
+ SFRM_ValuePerCall = 0x01, /* one value returned per call */
+ SFRM_Materialize = 0x02, /* result set instantiated in Tuplestore */
+ SFRM_Materialize_Random = 0x04, /* Tuplestore needs randomAccess */
+ SFRM_Materialize_Preferred = 0x08 /* caller prefers Tuplestore */
+} SetFunctionReturnMode;
+
+/*
+ * When calling a function that might return a set (multiple rows),
+ * a node of this type is passed as fcinfo->resultinfo to allow
+ * return status to be passed back. A function returning set should
+ * raise an error if no such resultinfo is provided.
+ */
+typedef struct ReturnSetInfo
+{
+ NodeTag type;
+ /* values set by caller: */
+ ExprContext *econtext; /* context function is being called in */
+ TupleDesc expectedDesc; /* tuple descriptor expected by caller */
+ int allowedModes; /* bitmask: return modes caller can handle */
+ /* result status from function (but pre-initialized by caller): */
+ SetFunctionReturnMode returnMode; /* actual return mode */
+ ExprDoneCond isDone; /* status for ValuePerCall mode */
+ /* fields filled by function in Materialize return mode: */
+ Tuplestorestate *setResult; /* holds the complete returned tuple set */
+ TupleDesc setDesc; /* actual descriptor for returned tuples */
+} ReturnSetInfo;
+
+/* ----------------
+ * ProjectionInfo node information
+ *
+ * This is all the information needed to perform projections ---
+ * that is, form new tuples by evaluation of targetlist expressions.
+ * Nodes which need to do projections create one of these.
+ *
+ * The target tuple slot is kept in ProjectionInfo->pi_state.resultslot.
+ * ExecProject() evaluates the tlist, forms a tuple, and stores it
+ * in the given slot. Note that the result will be a "virtual" tuple
+ * unless ExecMaterializeSlot() is then called to force it to be
+ * converted to a physical tuple. The slot must have a tupledesc
+ * that matches the output of the tlist!
+ * ----------------
+ */
+typedef struct ProjectionInfo
+{
+ NodeTag type;
+ /* instructions to evaluate projection */
+ ExprState pi_state;
+ /* expression context in which to evaluate expression */
+ ExprContext *pi_exprContext;
+} ProjectionInfo;
+
+/* ----------------
+ * JunkFilter
+ *
+ * This class is used to store information regarding junk attributes.
+ * A junk attribute is an attribute in a tuple that is needed only for
+ * storing intermediate information in the executor, and does not belong
+ * in emitted tuples. For example, when we do an UPDATE query,
+ * the planner adds a "junk" entry to the targetlist so that the tuples
+ * returned to ExecutePlan() contain an extra attribute: the ctid of
+ * the tuple to be updated. This is needed to do the update, but we
+ * don't want the ctid to be part of the stored new tuple! So, we
+ * apply a "junk filter" to remove the junk attributes and form the
+ * real output tuple. The junkfilter code also provides routines to
+ * extract the values of the junk attribute(s) from the input tuple.
+ *
+ * targetList: the original target list (including junk attributes).
+ * cleanTupType: the tuple descriptor for the "clean" tuple (with
+ * junk attributes removed).
+ * cleanMap: A map with the correspondence between the non-junk
+ * attribute numbers of the "original" tuple and the
+ * attribute numbers of the "clean" tuple.
+ * resultSlot: tuple slot used to hold cleaned tuple.
+ * ----------------
+ */
+typedef struct JunkFilter
+{
+ NodeTag type;
+ List *jf_targetList;
+ TupleDesc jf_cleanTupType;
+ AttrNumber *jf_cleanMap;
+ TupleTableSlot *jf_resultSlot;
+} JunkFilter;
+
+/*
+ * OnConflictSetState
+ *
+ * Executor state of an ON CONFLICT DO UPDATE operation.
+ */
+typedef struct OnConflictSetState
+{
+ NodeTag type;
+
+ TupleTableSlot *oc_Existing; /* slot to store existing target tuple in */
+ TupleTableSlot *oc_ProjSlot; /* CONFLICT ... SET ... projection target */
+ ProjectionInfo *oc_ProjInfo; /* for ON CONFLICT DO UPDATE SET */
+ ExprState *oc_WhereClause; /* state for the WHERE clause */
+} OnConflictSetState;
+
+/* ----------------
+ * MergeActionState information
+ *
+ * Executor state for a MERGE action.
+ * ----------------
+ */
+typedef struct MergeActionState
+{
+ NodeTag type;
+
+ MergeAction *mas_action; /* associated MergeAction node */
+ ProjectionInfo *mas_proj; /* projection of the action's targetlist for
+ * this rel */
+ ExprState *mas_whenqual; /* WHEN [NOT] MATCHED AND conditions */
+} MergeActionState;
+
+/*
+ * ResultRelInfo
+ *
+ * Whenever we update an existing relation, we have to update indexes on the
+ * relation, and perhaps also fire triggers. ResultRelInfo holds all the
+ * information needed about a result relation, including indexes.
+ *
+ * Normally, a ResultRelInfo refers to a table that is in the query's range
+ * table; then ri_RangeTableIndex is the RT index and ri_RelationDesc is
+ * just a copy of the relevant es_relations[] entry. However, in some
+ * situations we create ResultRelInfos for relations that are not in the
+ * range table, namely for targets of tuple routing in a partitioned table,
+ * and when firing triggers in tables other than the target tables (See
+ * ExecGetTriggerResultRel). In these situations, ri_RangeTableIndex is 0
+ * and ri_RelationDesc is a separately-opened relcache pointer that needs to
+ * be separately closed.
+ */
+typedef struct ResultRelInfo
+{
+ NodeTag type;
+
+ /* result relation's range table index, or 0 if not in range table */
+ Index ri_RangeTableIndex;
+
+ /* relation descriptor for result relation */
+ Relation ri_RelationDesc;
+
+ /* # of indices existing on result relation */
+ int ri_NumIndices;
+
+ /* array of relation descriptors for indices */
+ RelationPtr ri_IndexRelationDescs;
+
+ /* array of key/attr info for indices */
+ IndexInfo **ri_IndexRelationInfo;
+
+ /*
+ * For UPDATE/DELETE result relations, the attribute number of the row
+ * identity junk attribute in the source plan's output tuples
+ */
+ AttrNumber ri_RowIdAttNo;
+
+ /* For UPDATE, attnums of generated columns to be computed */
+ Bitmapset *ri_extraUpdatedCols;
+
+ /* Projection to generate new tuple in an INSERT/UPDATE */
+ ProjectionInfo *ri_projectNew;
+ /* Slot to hold that tuple */
+ TupleTableSlot *ri_newTupleSlot;
+ /* Slot to hold the old tuple being updated */
+ TupleTableSlot *ri_oldTupleSlot;
+ /* Have the projection and the slots above been initialized? */
+ bool ri_projectNewInfoValid;
+
+ /* triggers to be fired, if any */
+ TriggerDesc *ri_TrigDesc;
+
+ /* cached lookup info for trigger functions */
+ FmgrInfo *ri_TrigFunctions;
+
+ /* array of trigger WHEN expr states */
+ ExprState **ri_TrigWhenExprs;
+
+ /* optional runtime measurements for triggers */
+ Instrumentation *ri_TrigInstrument;
+
+ /* On-demand created slots for triggers / returning processing */
+ TupleTableSlot *ri_ReturningSlot; /* for trigger output tuples */
+ TupleTableSlot *ri_TrigOldSlot; /* for a trigger's old tuple */
+ TupleTableSlot *ri_TrigNewSlot; /* for a trigger's new tuple */
+
+ /* FDW callback functions, if foreign table */
+ struct FdwRoutine *ri_FdwRoutine;
+
+ /* available to save private state of FDW */
+ void *ri_FdwState;
+
+ /* true when modifying foreign table directly */
+ bool ri_usesFdwDirectModify;
+
+ /* batch insert stuff */
+ int ri_NumSlots; /* number of slots in the array */
+ int ri_NumSlotsInitialized; /* number of initialized slots */
+ int ri_BatchSize; /* max slots inserted in a single batch */
+ TupleTableSlot **ri_Slots; /* input tuples for batch insert */
+ TupleTableSlot **ri_PlanSlots;
+
+ /* list of WithCheckOption's to be checked */
+ List *ri_WithCheckOptions;
+
+ /* list of WithCheckOption expr states */
+ List *ri_WithCheckOptionExprs;
+
+ /* array of constraint-checking expr states */
+ ExprState **ri_ConstraintExprs;
+
+ /* arrays of stored generated columns expr states, for INSERT and UPDATE */
+ ExprState **ri_GeneratedExprsI;
+ ExprState **ri_GeneratedExprsU;
+
+ /* number of stored generated columns we need to compute */
+ int ri_NumGeneratedNeededI;
+ int ri_NumGeneratedNeededU;
+
+ /* list of RETURNING expressions */
+ List *ri_returningList;
+
+ /* for computing a RETURNING list */
+ ProjectionInfo *ri_projectReturning;
+
+ /* list of arbiter indexes to use to check conflicts */
+ List *ri_onConflictArbiterIndexes;
+
+ /* ON CONFLICT evaluation state */
+ OnConflictSetState *ri_onConflict;
+
+ /* for MERGE, lists of MergeActionState */
+ List *ri_matchedMergeAction;
+ List *ri_notMatchedMergeAction;
+
+ /* partition check expression state (NULL if not set up yet) */
+ ExprState *ri_PartitionCheckExpr;
+
+ /*
+ * Map to convert child result relation tuples to the format of the table
+ * actually mentioned in the query (called "root"). Computed only if
+ * needed. A NULL map value indicates that no conversion is needed, so we
+ * must have a separate flag to show if the map has been computed.
+ */
+ TupleConversionMap *ri_ChildToRootMap;
+ bool ri_ChildToRootMapValid;
+
+ /*
+ * As above, but in the other direction.
+ */
+ TupleConversionMap *ri_RootToChildMap;
+ bool ri_RootToChildMapValid;
+
+ /*
+ * Information needed by tuple routing target relations
+ *
+ * RootResultRelInfo gives the target relation mentioned in the query, if
+ * it's a partitioned table. It is not set if the target relation
+ * mentioned in the query is an inherited table, nor when tuple routing is
+ * not needed.
+ *
+ * PartitionTupleSlot is non-NULL if RootToChild conversion is needed and
+ * the relation is a partition.
+ */
+ struct ResultRelInfo *ri_RootResultRelInfo;
+ TupleTableSlot *ri_PartitionTupleSlot;
+
+ /* for use by copyfrom.c when performing multi-inserts */
+ struct CopyMultiInsertBuffer *ri_CopyMultiInsertBuffer;
+
+ /*
+ * Used when a leaf partition is involved in a cross-partition update of
+ * one of its ancestors; see ExecCrossPartitionUpdateForeignKey().
+ */
+ List *ri_ancestorResultRels;
+} ResultRelInfo;
+
+/* ----------------
+ * AsyncRequest
+ *
+ * State for an asynchronous tuple request.
+ * ----------------
+ */
+typedef struct AsyncRequest
+{
+ struct PlanState *requestor; /* Node that wants a tuple */
+ struct PlanState *requestee; /* Node from which a tuple is wanted */
+ int request_index; /* Scratch space for requestor */
+ bool callback_pending; /* Callback is needed */
+ bool request_complete; /* Request complete, result valid */
+ TupleTableSlot *result; /* Result (NULL or an empty slot if no more
+ * tuples) */
+} AsyncRequest;
+
+/* ----------------
+ * EState information
+ *
+ * Working state for an Executor invocation
+ * ----------------
+ */
+typedef struct EState
+{
+ NodeTag type;
+
+ /* Basic state for all query types: */
+ ScanDirection es_direction; /* current scan direction */
+ Snapshot es_snapshot; /* time qual to use */
+ Snapshot es_crosscheck_snapshot; /* crosscheck time qual for RI */
+ List *es_range_table; /* List of RangeTblEntry */
+ Index es_range_table_size; /* size of the range table arrays */
+ Relation *es_relations; /* Array of per-range-table-entry Relation
+ * pointers, or NULL if not yet opened */
+ struct ExecRowMark **es_rowmarks; /* Array of per-range-table-entry
+ * ExecRowMarks, or NULL if none */
+ List *es_rteperminfos; /* List of RTEPermissionInfo */
+ PlannedStmt *es_plannedstmt; /* link to top of plan tree */
+ const char *es_sourceText; /* Source text from QueryDesc */
+
+ JunkFilter *es_junkFilter; /* top-level junk filter, if any */
+
+ /* If query can insert/delete tuples, the command ID to mark them with */
+ CommandId es_output_cid;
+
+ /* Info about target table(s) for insert/update/delete queries: */
+ ResultRelInfo **es_result_relations; /* Array of per-range-table-entry
+ * ResultRelInfo pointers, or NULL
+ * if not a target table */
+ List *es_opened_result_relations; /* List of non-NULL entries in
+ * es_result_relations in no
+ * specific order */
+
+ PartitionDirectory es_partition_directory; /* for PartitionDesc lookup */
+
+ /*
+ * The following list contains ResultRelInfos created by the tuple routing
+ * code for partitions that aren't found in the es_result_relations array.
+ */
+ List *es_tuple_routing_result_relations;
+
+ /* Stuff used for firing triggers: */
+ List *es_trig_target_relations; /* trigger-only ResultRelInfos */
+
+ /* Parameter info: */
+ ParamListInfo es_param_list_info; /* values of external params */
+ ParamExecData *es_param_exec_vals; /* values of internal params */
+
+ QueryEnvironment *es_queryEnv; /* query environment */
+
+ /* Other working state: */
+ MemoryContext es_query_cxt; /* per-query context in which EState lives */
+
+ List *es_tupleTable; /* List of TupleTableSlots */
+
+ uint64 es_processed; /* # of tuples processed during one
+ * ExecutorRun() call. */
+ uint64 es_total_processed; /* total # of tuples aggregated across all
+ * ExecutorRun() calls. */
+
+ int es_top_eflags; /* eflags passed to ExecutorStart */
+ int es_instrument; /* OR of InstrumentOption flags */
+ bool es_finished; /* true when ExecutorFinish is done */
+
+ List *es_exprcontexts; /* List of ExprContexts within EState */
+
+ List *es_subplanstates; /* List of PlanState for SubPlans */
+
+ List *es_auxmodifytables; /* List of secondary ModifyTableStates */
+
+ /*
+ * this ExprContext is for per-output-tuple operations, such as constraint
+ * checks and index-value computations. It will be reset for each output
+ * tuple. Note that it will be created only if needed.
+ */
+ ExprContext *es_per_tuple_exprcontext;
+
+ /*
+ * If not NULL, this is an EPQState's EState. This is a field in EState
+ * both to allow EvalPlanQual aware executor nodes to detect that they
+ * need to perform EPQ related work, and to provide necessary information
+ * to do so.
+ */
+ struct EPQState *es_epq_active;
+
+ bool es_use_parallel_mode; /* can we use parallel workers? */
+
+ /* The per-query shared memory area to use for parallel execution. */
+ struct dsa_area *es_query_dsa;
+
+ /*
+ * JIT information. es_jit_flags indicates whether JIT should be performed
+ * and with which options. es_jit is created on-demand when JITing is
+ * performed.
+ *
+ * es_jit_worker_instr is the combined, on demand allocated,
+ * instrumentation from all workers. The leader's instrumentation is kept
+ * separate, and is combined on demand by ExplainPrintJITSummary().
+ */
+ int es_jit_flags;
+ struct JitContext *es_jit;
+ struct JitInstrumentation *es_jit_worker_instr;
+
+ /*
+ * Lists of ResultRelInfos for foreign tables on which batch-inserts are
+ * to be executed and owning ModifyTableStates, stored in the same order.
+ */
+ List *es_insert_pending_result_relations;
+ List *es_insert_pending_modifytables;
+} EState;
+
+
+/*
+ * ExecRowMark -
+ * runtime representation of FOR [KEY] UPDATE/SHARE clauses
+ *
+ * When doing UPDATE/DELETE/MERGE/SELECT FOR [KEY] UPDATE/SHARE, we will have
+ * an ExecRowMark for each non-target relation in the query (except inheritance
+ * parent RTEs, which can be ignored at runtime). Virtual relations such as
+ * subqueries-in-FROM will have an ExecRowMark with relation == NULL. See
+ * PlanRowMark for details about most of the fields. In addition to fields
+ * directly derived from PlanRowMark, we store an activity flag (to denote
+ * inactive children of inheritance trees), curCtid, which is used by the
+ * WHERE CURRENT OF code, and ermExtra, which is available for use by the plan
+ * node that sources the relation (e.g., for a foreign table the FDW can use
+ * ermExtra to hold information).
+ *
+ * EState->es_rowmarks is an array of these structs, indexed by RT index,
+ * with NULLs for irrelevant RT indexes. es_rowmarks itself is NULL if
+ * there are no rowmarks.
+ */
+typedef struct ExecRowMark
+{
+ Relation relation; /* opened and suitably locked relation */
+ Oid relid; /* its OID (or InvalidOid, if subquery) */
+ Index rti; /* its range table index */
+ Index prti; /* parent range table index, if child */
+ Index rowmarkId; /* unique identifier for resjunk columns */
+ RowMarkType markType; /* see enum in nodes/plannodes.h */
+ LockClauseStrength strength; /* LockingClause's strength, or LCS_NONE */
+ LockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
+ bool ermActive; /* is this mark relevant for current tuple? */
+ ItemPointerData curCtid; /* ctid of currently locked tuple, if any */
+ void *ermExtra; /* available for use by relation source node */
+} ExecRowMark;
+
+/*
+ * ExecAuxRowMark -
+ * additional runtime representation of FOR [KEY] UPDATE/SHARE clauses
+ *
+ * Each LockRows and ModifyTable node keeps a list of the rowmarks it needs to
+ * deal with. In addition to a pointer to the related entry in es_rowmarks,
+ * this struct carries the column number(s) of the resjunk columns associated
+ * with the rowmark (see comments for PlanRowMark for more detail).
+ */
+typedef struct ExecAuxRowMark
+{
+ ExecRowMark *rowmark; /* related entry in es_rowmarks */
+ AttrNumber ctidAttNo; /* resno of ctid junk attribute, if any */
+ AttrNumber toidAttNo; /* resno of tableoid junk attribute, if any */
+ AttrNumber wholeAttNo; /* resno of whole-row junk attribute, if any */
+} ExecAuxRowMark;
+
+
+/* ----------------------------------------------------------------
+ * Tuple Hash Tables
+ *
+ * All-in-memory tuple hash tables are used for a number of purposes.
+ *
+ * Note: tab_hash_funcs are for the key datatype(s) stored in the table,
+ * and tab_eq_funcs are non-cross-type equality operators for those types.
+ * Normally these are the only functions used, but FindTupleHashEntry()
+ * supports searching a hashtable using cross-data-type hashing. For that,
+ * the caller must supply hash functions for the LHS datatype as well as
+ * the cross-type equality operators to use. in_hash_funcs and cur_eq_func
+ * are set to point to the caller's function arrays while doing such a search.
+ * During LookupTupleHashEntry(), they point to tab_hash_funcs and
+ * tab_eq_func respectively.
+ * ----------------------------------------------------------------
+ */
+typedef struct TupleHashEntryData *TupleHashEntry;
+typedef struct TupleHashTableData *TupleHashTable;
+
+typedef struct TupleHashEntryData
+{
+ MinimalTuple firstTuple; /* copy of first tuple in this group */
+ void *additional; /* user data */
+ uint32 status; /* hash status */
+ uint32 hash; /* hash value (cached) */
+} TupleHashEntryData;
+
+/* define parameters necessary to generate the tuple hash table interface */
+#define SH_PREFIX tuplehash
+#define SH_ELEMENT_TYPE TupleHashEntryData
+#define SH_KEY_TYPE MinimalTuple
+#define SH_SCOPE extern
+#define SH_DECLARE
+#include "lib/simplehash.h"
+
+typedef struct TupleHashTableData
+{
+ tuplehash_hash *hashtab; /* underlying hash table */
+ int numCols; /* number of columns in lookup key */
+ AttrNumber *keyColIdx; /* attr numbers of key columns */
+ FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
+ ExprState *tab_eq_func; /* comparator for table datatype(s) */
+ Oid *tab_collations; /* collations for hash and comparison */
+ MemoryContext tablecxt; /* memory context containing table */
+ MemoryContext tempcxt; /* context for function evaluations */
+ Size entrysize; /* actual size to make each hash entry */
+ TupleTableSlot *tableslot; /* slot for referencing table entries */
+ /* The following fields are set transiently for each table search: */
+ TupleTableSlot *inputslot; /* current input tuple's slot */
+ FmgrInfo *in_hash_funcs; /* hash functions for input datatype(s) */
+ ExprState *cur_eq_func; /* comparator for input vs. table */
+ uint32 hash_iv; /* hash-function IV */
+ ExprContext *exprcontext; /* expression context */
+} TupleHashTableData;
+
+typedef tuplehash_iterator TupleHashIterator;
+
+/*
+ * Use InitTupleHashIterator/TermTupleHashIterator for a read/write scan.
+ * Use ResetTupleHashIterator if the table can be frozen (in this case no
+ * explicit scan termination is needed).
+ */
+#define InitTupleHashIterator(htable, iter) \
+ tuplehash_start_iterate(htable->hashtab, iter)
+#define TermTupleHashIterator(iter) \
+ ((void) 0)
+#define ResetTupleHashIterator(htable, iter) \
+ InitTupleHashIterator(htable, iter)
+#define ScanTupleHashTable(htable, iter) \
+ tuplehash_iterate(htable->hashtab, iter)
+
+
+/* ----------------------------------------------------------------
+ * Expression State Nodes
+ *
+ * Formerly, there was a separate executor expression state node corresponding
+ * to each node in a planned expression tree. That's no longer the case; for
+ * common expression node types, all the execution info is embedded into
+ * step(s) in a single ExprState node. But we still have a few executor state
+ * node types for selected expression node types, mostly those in which info
+ * has to be shared with other parts of the execution state tree.
+ * ----------------------------------------------------------------
+ */
+
+/* ----------------
+ * WindowFuncExprState node
+ * ----------------
+ */
+typedef struct WindowFuncExprState
+{
+ NodeTag type;
+ WindowFunc *wfunc; /* expression plan node */
+ List *args; /* ExprStates for argument expressions */
+ ExprState *aggfilter; /* FILTER expression */
+ int wfuncno; /* ID number for wfunc within its plan node */
+} WindowFuncExprState;
+
+
+/* ----------------
+ * SetExprState node
+ *
+ * State for evaluating a potentially set-returning expression (like FuncExpr
+ * or OpExpr). In some cases, like some of the expressions in ROWS FROM(...)
+ * the expression might not be a SRF, but nonetheless it uses the same
+ * machinery as SRFs; it will be treated as a SRF returning a single row.
+ * ----------------
+ */
+typedef struct SetExprState
+{
+ NodeTag type;
+ Expr *expr; /* expression plan node */
+ List *args; /* ExprStates for argument expressions */
+
+ /*
+ * In ROWS FROM, functions can be inlined, removing the FuncExpr normally
+ * inside. In such a case this is the compiled expression (which cannot
+ * return a set), which'll be evaluated using regular ExecEvalExpr().
+ */
+ ExprState *elidedFuncState;
+
+ /*
+ * Function manager's lookup info for the target function. If func.fn_oid
+ * is InvalidOid, we haven't initialized it yet (nor any of the following
+ * fields, except funcReturnsSet).
+ */
+ FmgrInfo func;
+
+ /*
+ * For a set-returning function (SRF) that returns a tuplestore, we keep
+ * the tuplestore here and dole out the result rows one at a time. The
+ * slot holds the row currently being returned.
+ */
+ Tuplestorestate *funcResultStore;
+ TupleTableSlot *funcResultSlot;
+
+ /*
+ * In some cases we need to compute a tuple descriptor for the function's
+ * output. If so, it's stored here.
+ */
+ TupleDesc funcResultDesc;
+ bool funcReturnsTuple; /* valid when funcResultDesc isn't NULL */
+
+ /*
+ * Remember whether the function is declared to return a set. This is set
+ * by ExecInitExpr, and is valid even before the FmgrInfo is set up.
+ */
+ bool funcReturnsSet;
+
+ /*
+ * setArgsValid is true when we are evaluating a set-returning function
+ * that uses value-per-call mode and we are in the middle of a call
+ * series; we want to pass the same argument values to the function again
+ * (and again, until it returns ExprEndResult). This indicates that
+ * fcinfo_data already contains valid argument data.
+ */
+ bool setArgsValid;
+
+ /*
+ * Flag to remember whether we have registered a shutdown callback for
+ * this SetExprState. We do so only if funcResultStore or setArgsValid
+ * has been set at least once (since all the callback is for is to release
+ * the tuplestore or clear setArgsValid).
+ */
+ bool shutdown_reg; /* a shutdown callback is registered */
+
+ /*
+ * Call parameter structure for the function. This has been initialized
+ * (by InitFunctionCallInfoData) if func.fn_oid is valid. It also saves
+ * argument values between calls, when setArgsValid is true.
+ */
+ FunctionCallInfo fcinfo;
+} SetExprState;
+
+/* ----------------
+ * SubPlanState node
+ * ----------------
+ */
+typedef struct SubPlanState
+{
+ NodeTag type;
+ SubPlan *subplan; /* expression plan node */
+ struct PlanState *planstate; /* subselect plan's state tree */
+ struct PlanState *parent; /* parent plan node's state tree */
+ ExprState *testexpr; /* state of combining expression */
+ List *args; /* states of argument expression(s) */
+ HeapTuple curTuple; /* copy of most recent tuple from subplan */
+ Datum curArray; /* most recent array from ARRAY() subplan */
+ /* these are used when hashing the subselect's output: */
+ TupleDesc descRight; /* subselect desc after projection */
+ ProjectionInfo *projLeft; /* for projecting lefthand exprs */
+ ProjectionInfo *projRight; /* for projecting subselect output */
+ TupleHashTable hashtable; /* hash table for no-nulls subselect rows */
+ TupleHashTable hashnulls; /* hash table for rows with null(s) */
+ bool havehashrows; /* true if hashtable is not empty */
+ bool havenullrows; /* true if hashnulls is not empty */
+ MemoryContext hashtablecxt; /* memory context containing hash tables */
+ MemoryContext hashtempcxt; /* temp memory context for hash tables */
+ ExprContext *innerecontext; /* econtext for computing inner tuples */
+ int numCols; /* number of columns being hashed */
+ /* each of the remaining fields is an array of length numCols: */
+ AttrNumber *keyColIdx; /* control data for hash tables */
+ Oid *tab_eq_funcoids; /* equality func oids for table
+ * datatype(s) */
+ Oid *tab_collations; /* collations for hash and comparison */
+ FmgrInfo *tab_hash_funcs; /* hash functions for table datatype(s) */
+ FmgrInfo *tab_eq_funcs; /* equality functions for table datatype(s) */
+ FmgrInfo *lhs_hash_funcs; /* hash functions for lefthand datatype(s) */
+ FmgrInfo *cur_eq_funcs; /* equality functions for LHS vs. table */
+ ExprState *cur_eq_comp; /* equality comparator for LHS vs. table */
+} SubPlanState;
+
+/*
+ * DomainConstraintState - one item to check during CoerceToDomain
+ *
+ * Note: we consider this to be part of an ExprState tree, so we give it
+ * a name following the xxxState convention. But there's no directly
+ * associated plan-tree node.
+ */
+typedef enum DomainConstraintType
+{
+ DOM_CONSTRAINT_NOTNULL,
+ DOM_CONSTRAINT_CHECK
+} DomainConstraintType;
+
+typedef struct DomainConstraintState
+{
+ NodeTag type;
+ DomainConstraintType constrainttype; /* constraint type */
+ char *name; /* name of constraint (for error msgs) */
+ Expr *check_expr; /* for CHECK, a boolean expression */
+ ExprState *check_exprstate; /* check_expr's eval state, or NULL */
+} DomainConstraintState;
+
+
+/* ----------------------------------------------------------------
+ * Executor State Trees
+ *
+ * An executing query has a PlanState tree paralleling the Plan tree
+ * that describes the plan.
+ * ----------------------------------------------------------------
+ */
+
+/* ----------------
+ * ExecProcNodeMtd
+ *
+ * This is the method called by ExecProcNode to return the next tuple
+ * from an executor node. It returns NULL, or an empty TupleTableSlot,
+ * if no more tuples are available.
+ * ----------------
+ */
+typedef TupleTableSlot *(*ExecProcNodeMtd) (struct PlanState *pstate);
+
+/* ----------------
+ * PlanState node
+ *
+ * We never actually instantiate any PlanState nodes; this is just the common
+ * abstract superclass for all PlanState-type nodes.
+ * ----------------
+ */
+typedef struct PlanState
+{
+ pg_node_attr(abstract)
+
+ NodeTag type;
+
+ Plan *plan; /* associated Plan node */
+
+ EState *state; /* at execution time, states of individual
+ * nodes point to one EState for the whole
+ * top-level plan */
+
+ ExecProcNodeMtd ExecProcNode; /* function to return next tuple */
+ ExecProcNodeMtd ExecProcNodeReal; /* actual function, if above is a
+ * wrapper */
+
+ Instrumentation *instrument; /* Optional runtime stats for this node */
+ WorkerInstrumentation *worker_instrument; /* per-worker instrumentation */
+
+ /* Per-worker JIT instrumentation */
+ struct SharedJitInstrumentation *worker_jit_instrument;
+
+ /*
+ * Common structural data for all Plan types. These links to subsidiary
+ * state trees parallel links in the associated plan tree (except for the
+ * subPlan list, which does not exist in the plan tree).
+ */
+ ExprState *qual; /* boolean qual condition */
+ struct PlanState *lefttree; /* input plan tree(s) */
+ struct PlanState *righttree;
+
+ List *initPlan; /* Init SubPlanState nodes (un-correlated expr
+ * subselects) */
+ List *subPlan; /* SubPlanState nodes in my expressions */
+
+ /*
+ * State for management of parameter-change-driven rescanning
+ */
+ Bitmapset *chgParam; /* set of IDs of changed Params */
+
+ /*
+ * Other run-time state needed by most if not all node types.
+ */
+ TupleDesc ps_ResultTupleDesc; /* node's return type */
+ TupleTableSlot *ps_ResultTupleSlot; /* slot for my result tuples */
+ ExprContext *ps_ExprContext; /* node's expression-evaluation context */
+ ProjectionInfo *ps_ProjInfo; /* info for doing tuple projection */
+
+ bool async_capable; /* true if node is async-capable */
+
+ /*
+ * Scanslot's descriptor if known. This is a bit of a hack, but otherwise
+ * it's hard for expression compilation to optimize based on the
+ * descriptor, without encoding knowledge about all executor nodes.
+ */
+ TupleDesc scandesc;
+
+ /*
+ * Define the slot types for inner, outer and scanslots for expression
+ * contexts with this state as a parent. If *opsset is set, then
+ * *opsfixed indicates whether *ops is guaranteed to be the type of slot
+ * used. That means that every slot in the corresponding
+ * ExprContext.ecxt_*tuple will point to a slot of that type, while
+ * evaluating the expression. If *opsfixed is false, but *ops is set,
+ * that indicates the most likely type of slot.
+ *
+ * The scan* fields are set by ExecInitScanTupleSlot(). If that's not
+ * called, nodes can initialize the fields themselves.
+ *
+ * If outer/inneropsset is false, the information is inferred on-demand
+ * using ExecGetResultSlotOps() on ->righttree/lefttree, using the
+ * corresponding node's resultops* fields.
+ *
+ * The result* fields are automatically set when ExecInitResultSlot is
+ * used (be it directly or when the slot is created by
+ * ExecAssignScanProjectionInfo() /
+ * ExecConditionalAssignProjectionInfo()). If no projection is necessary
+ * ExecConditionalAssignProjectionInfo() defaults those fields to the scan
+ * operations.
+ */
+ const TupleTableSlotOps *scanops;
+ const TupleTableSlotOps *outerops;
+ const TupleTableSlotOps *innerops;
+ const TupleTableSlotOps *resultops;
+ bool scanopsfixed;
+ bool outeropsfixed;
+ bool inneropsfixed;
+ bool resultopsfixed;
+ bool scanopsset;
+ bool outeropsset;
+ bool inneropsset;
+ bool resultopsset;
+} PlanState;
+
+/* ----------------
+ * these are defined to avoid confusion problems with "left"
+ * and "right" and "inner" and "outer". The convention is that
+ * the "left" plan is the "outer" plan and the "right" plan is
+ * the inner plan, but these make the code more readable.
+ * ----------------
+ */
+#define innerPlanState(node) (((PlanState *)(node))->righttree)
+#define outerPlanState(node) (((PlanState *)(node))->lefttree)
+
+/* Macros for inline access to certain instrumentation counters */
+#define InstrCountTuples2(node, delta) \
+ do { \
+ if (((PlanState *)(node))->instrument) \
+ ((PlanState *)(node))->instrument->ntuples2 += (delta); \
+ } while (0)
+#define InstrCountFiltered1(node, delta) \
+ do { \
+ if (((PlanState *)(node))->instrument) \
+ ((PlanState *)(node))->instrument->nfiltered1 += (delta); \
+ } while(0)
+#define InstrCountFiltered2(node, delta) \
+ do { \
+ if (((PlanState *)(node))->instrument) \
+ ((PlanState *)(node))->instrument->nfiltered2 += (delta); \
+ } while(0)
+
+/*
+ * EPQState is state for executing an EvalPlanQual recheck on a candidate
+ * tuples e.g. in ModifyTable or LockRows.
+ *
+ * To execute EPQ a separate EState is created (stored in ->recheckestate),
+ * which shares some resources, like the rangetable, with the main query's
+ * EState (stored in ->parentestate). The (sub-)tree of the plan that needs to
+ * be rechecked (in ->plan), is separately initialized (into
+ * ->recheckplanstate), but shares plan nodes with the corresponding nodes in
+ * the main query. The scan nodes in that separate executor tree are changed
+ * to return only the current tuple of interest for the respective
+ * table. Those tuples are either provided by the caller (using
+ * EvalPlanQualSlot), and/or found using the rowmark mechanism (non-locking
+ * rowmarks by the EPQ machinery itself, locking ones by the caller).
+ *
+ * While the plan to be checked may be changed using EvalPlanQualSetPlan(),
+ * all such plans need to share the same EState.
+ */
+typedef struct EPQState
+{
+ /* These are initialized by EvalPlanQualInit() and do not change later: */
+ EState *parentestate; /* main query's EState */
+ int epqParam; /* ID of Param to force scan node re-eval */
+ List *resultRelations; /* integer list of RT indexes, or NIL */
+
+ /*
+ * relsubs_slot[scanrelid - 1] holds the EPQ test tuple to be returned by
+ * the scan node for the scanrelid'th RT index, in place of performing an
+ * actual table scan. Callers should use EvalPlanQualSlot() to fetch
+ * these slots.
+ */
+ List *tuple_table; /* tuple table for relsubs_slot */
+ TupleTableSlot **relsubs_slot;
+
+ /*
+ * Initialized by EvalPlanQualInit(), may be changed later with
+ * EvalPlanQualSetPlan():
+ */
+
+ Plan *plan; /* plan tree to be executed */
+ List *arowMarks; /* ExecAuxRowMarks (non-locking only) */
+
+
+ /*
+ * The original output tuple to be rechecked. Set by
+ * EvalPlanQualSetSlot(), before EvalPlanQualNext() or EvalPlanQual() may
+ * be called.
+ */
+ TupleTableSlot *origslot;
+
+
+ /* Initialized or reset by EvalPlanQualBegin(): */
+
+ EState *recheckestate; /* EState for EPQ execution, see above */
+
+ /*
+ * Rowmarks that can be fetched on-demand using
+ * EvalPlanQualFetchRowMark(), indexed by scanrelid - 1. Only non-locking
+ * rowmarks.
+ */
+ ExecAuxRowMark **relsubs_rowmark;
+
+ /*
+ * relsubs_done[scanrelid - 1] is true if there is no EPQ tuple for this
+ * target relation or it has already been fetched in the current scan of
+ * this target relation within the current EvalPlanQual test.
+ */
+ bool *relsubs_done;
+
+ /*
+ * relsubs_blocked[scanrelid - 1] is true if there is no EPQ tuple for
+ * this target relation during the current EvalPlanQual test. We keep
+ * these flags set for all relids listed in resultRelations, but
+ * transiently clear the one for the relation whose tuple is actually
+ * passed to EvalPlanQual().
+ */
+ bool *relsubs_blocked;
+
+ PlanState *recheckplanstate; /* EPQ specific exec nodes, for ->plan */
+} EPQState;
+
+
+/* ----------------
+ * ResultState information
+ * ----------------
+ */
+typedef struct ResultState
+{
+ PlanState ps; /* its first field is NodeTag */
+ ExprState *resconstantqual;
+ bool rs_done; /* are we done? */
+ bool rs_checkqual; /* do we need to check the qual? */
+} ResultState;
+
+/* ----------------
+ * ProjectSetState information
+ *
+ * Note: at least one of the "elems" will be a SetExprState; the rest are
+ * regular ExprStates.
+ * ----------------
+ */
+typedef struct ProjectSetState
+{
+ PlanState ps; /* its first field is NodeTag */
+ Node **elems; /* array of expression states */
+ ExprDoneCond *elemdone; /* array of per-SRF is-done states */
+ int nelems; /* length of elemdone[] array */
+ bool pending_srf_tuples; /* still evaluating srfs in tlist? */
+ MemoryContext argcontext; /* context for SRF arguments */
+} ProjectSetState;
+
+
+/* flags for mt_merge_subcommands */
+#define MERGE_INSERT 0x01
+#define MERGE_UPDATE 0x02
+#define MERGE_DELETE 0x04
+
+/* ----------------
+ * ModifyTableState information
+ * ----------------
+ */
+typedef struct ModifyTableState
+{
+ PlanState ps; /* its first field is NodeTag */
+ CmdType operation; /* INSERT, UPDATE, DELETE, or MERGE */
+ bool canSetTag; /* do we set the command tag/es_processed? */
+ bool mt_done; /* are we done? */
+ int mt_nrels; /* number of entries in resultRelInfo[] */
+ ResultRelInfo *resultRelInfo; /* info about target relation(s) */
+
+ /*
+ * Target relation mentioned in the original statement, used to fire
+ * statement-level triggers and as the root for tuple routing. (This
+ * might point to one of the resultRelInfo[] entries, but it can also be a
+ * distinct struct.)
+ */
+ ResultRelInfo *rootResultRelInfo;
+
+ EPQState mt_epqstate; /* for evaluating EvalPlanQual rechecks */
+ bool fireBSTriggers; /* do we need to fire stmt triggers? */
+
+ /*
+ * These fields are used for inherited UPDATE and DELETE, to track which
+ * target relation a given tuple is from. If there are a lot of target
+ * relations, we use a hash table to translate table OIDs to
+ * resultRelInfo[] indexes; otherwise mt_resultOidHash is NULL.
+ */
+ int mt_resultOidAttno; /* resno of "tableoid" junk attr */
+ Oid mt_lastResultOid; /* last-seen value of tableoid */
+ int mt_lastResultIndex; /* corresponding index in resultRelInfo[] */
+ HTAB *mt_resultOidHash; /* optional hash table to speed lookups */
+
+ /*
+ * Slot for storing tuples in the root partitioned table's rowtype during
+ * an UPDATE of a partitioned table.
+ */
+ TupleTableSlot *mt_root_tuple_slot;
+
+ /* Tuple-routing support info */
+ struct PartitionTupleRouting *mt_partition_tuple_routing;
+
+ /* controls transition table population for specified operation */
+ struct TransitionCaptureState *mt_transition_capture;
+
+ /* controls transition table population for INSERT...ON CONFLICT UPDATE */
+ struct TransitionCaptureState *mt_oc_transition_capture;
+
+ /* Flags showing which subcommands are present INS/UPD/DEL/DO NOTHING */
+ int mt_merge_subcommands;
+
+ /* tuple counters for MERGE */
+ double mt_merge_inserted;
+ double mt_merge_updated;
+ double mt_merge_deleted;
+} ModifyTableState;
+
+/* ----------------
+ * AppendState information
+ *
+ * nplans how many plans are in the array
+ * whichplan which synchronous plan is being executed (0 .. n-1)
+ * or a special negative value. See nodeAppend.c.
+ * prune_state details required to allow partitions to be
+ * eliminated from the scan, or NULL if not possible.
+ * valid_subplans for runtime pruning, valid synchronous appendplans
+ * indexes to scan.
+ * ----------------
+ */
+
+struct AppendState;
+typedef struct AppendState AppendState;
+struct ParallelAppendState;
+typedef struct ParallelAppendState ParallelAppendState;
+struct PartitionPruneState;
+
+struct AppendState
+{
+ PlanState ps; /* its first field is NodeTag */
+ PlanState **appendplans; /* array of PlanStates for my inputs */
+ int as_nplans;
+ int as_whichplan;
+ bool as_begun; /* false means need to initialize */
+ Bitmapset *as_asyncplans; /* asynchronous plans indexes */
+ int as_nasyncplans; /* # of asynchronous plans */
+ AsyncRequest **as_asyncrequests; /* array of AsyncRequests */
+ TupleTableSlot **as_asyncresults; /* unreturned results of async plans */
+ int as_nasyncresults; /* # of valid entries in as_asyncresults */
+ bool as_syncdone; /* true if all synchronous plans done in
+ * asynchronous mode, else false */
+ int as_nasyncremain; /* # of remaining asynchronous plans */
+ Bitmapset *as_needrequest; /* asynchronous plans needing a new request */
+ struct WaitEventSet *as_eventset; /* WaitEventSet used to configure file
+ * descriptor wait events */
+ int as_first_partial_plan; /* Index of 'appendplans' containing
+ * the first partial plan */
+ ParallelAppendState *as_pstate; /* parallel coordination info */
+ Size pstate_len; /* size of parallel coordination info */
+ struct PartitionPruneState *as_prune_state;
+ bool as_valid_subplans_identified; /* is as_valid_subplans valid? */
+ Bitmapset *as_valid_subplans;
+ Bitmapset *as_valid_asyncplans; /* valid asynchronous plans indexes */
+ bool (*choose_next_subplan) (AppendState *);
+};
+
+/* ----------------
+ * MergeAppendState information
+ *
+ * nplans how many plans are in the array
+ * nkeys number of sort key columns
+ * sortkeys sort keys in SortSupport representation
+ * slots current output tuple of each subplan
+ * heap heap of active tuples
+ * initialized true if we have fetched first tuple from each subplan
+ * prune_state details required to allow partitions to be
+ * eliminated from the scan, or NULL if not possible.
+ * valid_subplans for runtime pruning, valid mergeplans indexes to
+ * scan.
+ * ----------------
+ */
+typedef struct MergeAppendState
+{
+ PlanState ps; /* its first field is NodeTag */
+ PlanState **mergeplans; /* array of PlanStates for my inputs */
+ int ms_nplans;
+ int ms_nkeys;
+ SortSupport ms_sortkeys; /* array of length ms_nkeys */
+ TupleTableSlot **ms_slots; /* array of length ms_nplans */
+ struct binaryheap *ms_heap; /* binary heap of slot indices */
+ bool ms_initialized; /* are subplans started? */
+ struct PartitionPruneState *ms_prune_state;
+ Bitmapset *ms_valid_subplans;
+} MergeAppendState;
+
+/* ----------------
+ * RecursiveUnionState information
+ *
+ * RecursiveUnionState is used for performing a recursive union.
+ *
+ * recursing T when we're done scanning the non-recursive term
+ * intermediate_empty T if intermediate_table is currently empty
+ * working_table working table (to be scanned by recursive term)
+ * intermediate_table current recursive output (next generation of WT)
+ * ----------------
+ */
+typedef struct RecursiveUnionState
+{
+ PlanState ps; /* its first field is NodeTag */
+ bool recursing;
+ bool intermediate_empty;
+ Tuplestorestate *working_table;
+ Tuplestorestate *intermediate_table;
+ /* Remaining fields are unused in UNION ALL case */
+ Oid *eqfuncoids; /* per-grouping-field equality fns */
+ FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
+ MemoryContext tempContext; /* short-term context for comparisons */
+ TupleHashTable hashtable; /* hash table for tuples already seen */
+ MemoryContext tableContext; /* memory context containing hash table */
+} RecursiveUnionState;
+
+/* ----------------
+ * BitmapAndState information
+ * ----------------
+ */
+typedef struct BitmapAndState
+{
+ PlanState ps; /* its first field is NodeTag */
+ PlanState **bitmapplans; /* array of PlanStates for my inputs */
+ int nplans; /* number of input plans */
+} BitmapAndState;
+
+/* ----------------
+ * BitmapOrState information
+ * ----------------
+ */
+typedef struct BitmapOrState
+{
+ PlanState ps; /* its first field is NodeTag */
+ PlanState **bitmapplans; /* array of PlanStates for my inputs */
+ int nplans; /* number of input plans */
+} BitmapOrState;
+
+/* ----------------------------------------------------------------
+ * Scan State Information
+ * ----------------------------------------------------------------
+ */
+
+/* ----------------
+ * ScanState information
+ *
+ * ScanState extends PlanState for node types that represent
+ * scans of an underlying relation. It can also be used for nodes
+ * that scan the output of an underlying plan node --- in that case,
+ * only ScanTupleSlot is actually useful, and it refers to the tuple
+ * retrieved from the subplan.
+ *
+ * currentRelation relation being scanned (NULL if none)
+ * currentScanDesc current scan descriptor for scan (NULL if none)
+ * ScanTupleSlot pointer to slot in tuple table holding scan tuple
+ * ----------------
+ */
+typedef struct ScanState
+{
+ PlanState ps; /* its first field is NodeTag */
+ Relation ss_currentRelation;
+ struct TableScanDescData *ss_currentScanDesc;
+ TupleTableSlot *ss_ScanTupleSlot;
+} ScanState;
+
+/* ----------------
+ * SeqScanState information
+ * ----------------
+ */
+typedef struct SeqScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ Size pscan_len; /* size of parallel heap scan descriptor */
+} SeqScanState;
+
+/* ----------------
+ * SampleScanState information
+ * ----------------
+ */
+typedef struct SampleScanState
+{
+ ScanState ss;
+ List *args; /* expr states for TABLESAMPLE params */
+ ExprState *repeatable; /* expr state for REPEATABLE expr */
+ /* use struct pointer to avoid including tsmapi.h here */
+ struct TsmRoutine *tsmroutine; /* descriptor for tablesample method */
+ void *tsm_state; /* tablesample method can keep state here */
+ bool use_bulkread; /* use bulkread buffer access strategy? */
+ bool use_pagemode; /* use page-at-a-time visibility checking? */
+ bool begun; /* false means need to call BeginSampleScan */
+ uint32 seed; /* random seed */
+ int64 donetuples; /* number of tuples already returned */
+ bool haveblock; /* has a block for sampling been determined */
+ bool done; /* exhausted all tuples? */
+} SampleScanState;
+
+/*
+ * These structs store information about index quals that don't have simple
+ * constant right-hand sides. See comments for ExecIndexBuildScanKeys()
+ * for discussion.
+ */
+typedef struct
+{
+ struct ScanKeyData *scan_key; /* scankey to put value into */
+ ExprState *key_expr; /* expr to evaluate to get value */
+ bool key_toastable; /* is expr's result a toastable datatype? */
+} IndexRuntimeKeyInfo;
+
+typedef struct
+{
+ struct ScanKeyData *scan_key; /* scankey to put value into */
+ ExprState *array_expr; /* expr to evaluate to get array value */
+ int next_elem; /* next array element to use */
+ int num_elems; /* number of elems in current array value */
+ Datum *elem_values; /* array of num_elems Datums */
+ bool *elem_nulls; /* array of num_elems is-null flags */
+} IndexArrayKeyInfo;
+
+/* ----------------
+ * IndexScanState information
+ *
+ * indexqualorig execution state for indexqualorig expressions
+ * indexorderbyorig execution state for indexorderbyorig expressions
+ * ScanKeys Skey structures for index quals
+ * NumScanKeys number of ScanKeys
+ * OrderByKeys Skey structures for index ordering operators
+ * NumOrderByKeys number of OrderByKeys
+ * RuntimeKeys info about Skeys that must be evaluated at runtime
+ * NumRuntimeKeys number of RuntimeKeys
+ * RuntimeKeysReady true if runtime Skeys have been computed
+ * RuntimeContext expr context for evaling runtime Skeys
+ * RelationDesc index relation descriptor
+ * ScanDesc index scan descriptor
+ *
+ * ReorderQueue tuples that need reordering due to re-check
+ * ReachedEnd have we fetched all tuples from index already?
+ * OrderByValues values of ORDER BY exprs of last fetched tuple
+ * OrderByNulls null flags for OrderByValues
+ * SortSupport for reordering ORDER BY exprs
+ * OrderByTypByVals is the datatype of order by expression pass-by-value?
+ * OrderByTypLens typlens of the datatypes of order by expressions
+ * PscanLen size of parallel index scan descriptor
+ * ----------------
+ */
+typedef struct IndexScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprState *indexqualorig;
+ List *indexorderbyorig;
+ struct ScanKeyData *iss_ScanKeys;
+ int iss_NumScanKeys;
+ struct ScanKeyData *iss_OrderByKeys;
+ int iss_NumOrderByKeys;
+ IndexRuntimeKeyInfo *iss_RuntimeKeys;
+ int iss_NumRuntimeKeys;
+ bool iss_RuntimeKeysReady;
+ ExprContext *iss_RuntimeContext;
+ Relation iss_RelationDesc;
+ struct IndexScanDescData *iss_ScanDesc;
+
+ /* These are needed for re-checking ORDER BY expr ordering */
+ pairingheap *iss_ReorderQueue;
+ bool iss_ReachedEnd;
+ Datum *iss_OrderByValues;
+ bool *iss_OrderByNulls;
+ SortSupport iss_SortSupport;
+ bool *iss_OrderByTypByVals;
+ int16 *iss_OrderByTypLens;
+ Size iss_PscanLen;
+} IndexScanState;
+
+/* ----------------
+ * IndexOnlyScanState information
+ *
+ * recheckqual execution state for recheckqual expressions
+ * ScanKeys Skey structures for index quals
+ * NumScanKeys number of ScanKeys
+ * OrderByKeys Skey structures for index ordering operators
+ * NumOrderByKeys number of OrderByKeys
+ * RuntimeKeys info about Skeys that must be evaluated at runtime
+ * NumRuntimeKeys number of RuntimeKeys
+ * RuntimeKeysReady true if runtime Skeys have been computed
+ * RuntimeContext expr context for evaling runtime Skeys
+ * RelationDesc index relation descriptor
+ * ScanDesc index scan descriptor
+ * TableSlot slot for holding tuples fetched from the table
+ * VMBuffer buffer in use for visibility map testing, if any
+ * PscanLen size of parallel index-only scan descriptor
+ * NameCStringAttNums attnums of name typed columns to pad to NAMEDATALEN
+ * NameCStringCount number of elements in the NameCStringAttNums array
+ * ----------------
+ */
+typedef struct IndexOnlyScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprState *recheckqual;
+ struct ScanKeyData *ioss_ScanKeys;
+ int ioss_NumScanKeys;
+ struct ScanKeyData *ioss_OrderByKeys;
+ int ioss_NumOrderByKeys;
+ IndexRuntimeKeyInfo *ioss_RuntimeKeys;
+ int ioss_NumRuntimeKeys;
+ bool ioss_RuntimeKeysReady;
+ ExprContext *ioss_RuntimeContext;
+ Relation ioss_RelationDesc;
+ struct IndexScanDescData *ioss_ScanDesc;
+ TupleTableSlot *ioss_TableSlot;
+ Buffer ioss_VMBuffer;
+ Size ioss_PscanLen;
+ AttrNumber *ioss_NameCStringAttNums;
+ int ioss_NameCStringCount;
+} IndexOnlyScanState;
+
+/* ----------------
+ * BitmapIndexScanState information
+ *
+ * result bitmap to return output into, or NULL
+ * ScanKeys Skey structures for index quals
+ * NumScanKeys number of ScanKeys
+ * RuntimeKeys info about Skeys that must be evaluated at runtime
+ * NumRuntimeKeys number of RuntimeKeys
+ * ArrayKeys info about Skeys that come from ScalarArrayOpExprs
+ * NumArrayKeys number of ArrayKeys
+ * RuntimeKeysReady true if runtime Skeys have been computed
+ * RuntimeContext expr context for evaling runtime Skeys
+ * RelationDesc index relation descriptor
+ * ScanDesc index scan descriptor
+ * ----------------
+ */
+typedef struct BitmapIndexScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ TIDBitmap *biss_result;
+ struct ScanKeyData *biss_ScanKeys;
+ int biss_NumScanKeys;
+ IndexRuntimeKeyInfo *biss_RuntimeKeys;
+ int biss_NumRuntimeKeys;
+ IndexArrayKeyInfo *biss_ArrayKeys;
+ int biss_NumArrayKeys;
+ bool biss_RuntimeKeysReady;
+ ExprContext *biss_RuntimeContext;
+ Relation biss_RelationDesc;
+ struct IndexScanDescData *biss_ScanDesc;
+} BitmapIndexScanState;
+
+/* ----------------
+ * SharedBitmapState information
+ *
+ * BM_INITIAL TIDBitmap creation is not yet started, so first worker
+ * to see this state will set the state to BM_INPROGRESS
+ * and that process will be responsible for creating
+ * TIDBitmap.
+ * BM_INPROGRESS TIDBitmap creation is in progress; workers need to
+ * sleep until it's finished.
+ * BM_FINISHED TIDBitmap creation is done, so now all workers can
+ * proceed to iterate over TIDBitmap.
+ * ----------------
+ */
+typedef enum
+{
+ BM_INITIAL,
+ BM_INPROGRESS,
+ BM_FINISHED
+} SharedBitmapState;
+
+/* ----------------
+ * ParallelBitmapHeapState information
+ * tbmiterator iterator for scanning current pages
+ * prefetch_iterator iterator for prefetching ahead of current page
+ * mutex mutual exclusion for the prefetching variable
+ * and state
+ * prefetch_pages # pages prefetch iterator is ahead of current
+ * prefetch_target current target prefetch distance
+ * state current state of the TIDBitmap
+ * cv conditional wait variable
+ * phs_snapshot_data snapshot data shared to workers
+ * ----------------
+ */
+typedef struct ParallelBitmapHeapState
+{
+ dsa_pointer tbmiterator;
+ dsa_pointer prefetch_iterator;
+ slock_t mutex;
+ int prefetch_pages;
+ int prefetch_target;
+ SharedBitmapState state;
+ ConditionVariable cv;
+ char phs_snapshot_data[FLEXIBLE_ARRAY_MEMBER];
+} ParallelBitmapHeapState;
+
+/* ----------------
+ * BitmapHeapScanState information
+ *
+ * bitmapqualorig execution state for bitmapqualorig expressions
+ * tbm bitmap obtained from child index scan(s)
+ * tbmiterator iterator for scanning current pages
+ * tbmres current-page data
+ * can_skip_fetch can we potentially skip tuple fetches in this scan?
+ * return_empty_tuples number of empty tuples to return
+ * vmbuffer buffer for visibility-map lookups
+ * pvmbuffer ditto, for prefetched pages
+ * exact_pages total number of exact pages retrieved
+ * lossy_pages total number of lossy pages retrieved
+ * prefetch_iterator iterator for prefetching ahead of current page
+ * prefetch_pages # pages prefetch iterator is ahead of current
+ * prefetch_target current target prefetch distance
+ * prefetch_maximum maximum value for prefetch_target
+ * pscan_len size of the shared memory for parallel bitmap
+ * initialized is node is ready to iterate
+ * shared_tbmiterator shared iterator
+ * shared_prefetch_iterator shared iterator for prefetching
+ * pstate shared state for parallel bitmap scan
+ * ----------------
+ */
+typedef struct BitmapHeapScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprState *bitmapqualorig;
+ TIDBitmap *tbm;
+ TBMIterator *tbmiterator;
+ TBMIterateResult *tbmres;
+ bool can_skip_fetch;
+ int return_empty_tuples;
+ Buffer vmbuffer;
+ Buffer pvmbuffer;
+ long exact_pages;
+ long lossy_pages;
+ TBMIterator *prefetch_iterator;
+ int prefetch_pages;
+ int prefetch_target;
+ int prefetch_maximum;
+ Size pscan_len;
+ bool initialized;
+ TBMSharedIterator *shared_tbmiterator;
+ TBMSharedIterator *shared_prefetch_iterator;
+ ParallelBitmapHeapState *pstate;
+} BitmapHeapScanState;
+
+/* ----------------
+ * TidScanState information
+ *
+ * tidexprs list of TidExpr structs (see nodeTidscan.c)
+ * isCurrentOf scan has a CurrentOfExpr qual
+ * NumTids number of tids in this scan
+ * TidPtr index of currently fetched tid
+ * TidList evaluated item pointers (array of size NumTids)
+ * htup currently-fetched tuple, if any
+ * ----------------
+ */
+typedef struct TidScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ List *tss_tidexprs;
+ bool tss_isCurrentOf;
+ int tss_NumTids;
+ int tss_TidPtr;
+ ItemPointerData *tss_TidList;
+ HeapTupleData tss_htup;
+} TidScanState;
+
+/* ----------------
+ * TidRangeScanState information
+ *
+ * trss_tidexprs list of TidOpExpr structs (see nodeTidrangescan.c)
+ * trss_mintid the lowest TID in the scan range
+ * trss_maxtid the highest TID in the scan range
+ * trss_inScan is a scan currently in progress?
+ * ----------------
+ */
+typedef struct TidRangeScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ List *trss_tidexprs;
+ ItemPointerData trss_mintid;
+ ItemPointerData trss_maxtid;
+ bool trss_inScan;
+} TidRangeScanState;
+
+/* ----------------
+ * SubqueryScanState information
+ *
+ * SubqueryScanState is used for scanning a sub-query in the range table.
+ * ScanTupleSlot references the current output tuple of the sub-query.
+ * ----------------
+ */
+typedef struct SubqueryScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ PlanState *subplan;
+} SubqueryScanState;
+
+/* ----------------
+ * FunctionScanState information
+ *
+ * Function nodes are used to scan the results of a
+ * function appearing in FROM (typically a function returning set).
+ *
+ * eflags node's capability flags
+ * ordinality is this scan WITH ORDINALITY?
+ * simple true if we have 1 function and no ordinality
+ * ordinal current ordinal column value
+ * nfuncs number of functions being executed
+ * funcstates per-function execution states (private in
+ * nodeFunctionscan.c)
+ * argcontext memory context to evaluate function arguments in
+ * ----------------
+ */
+struct FunctionScanPerFuncState;
+
+typedef struct FunctionScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ int eflags;
+ bool ordinality;
+ bool simple;
+ int64 ordinal;
+ int nfuncs;
+ struct FunctionScanPerFuncState *funcstates; /* array of length nfuncs */
+ MemoryContext argcontext;
+} FunctionScanState;
+
+/* ----------------
+ * ValuesScanState information
+ *
+ * ValuesScan nodes are used to scan the results of a VALUES list
+ *
+ * rowcontext per-expression-list context
+ * exprlists array of expression lists being evaluated
+ * exprstatelists array of expression state lists, for SubPlans only
+ * array_len size of above arrays
+ * curr_idx current array index (0-based)
+ *
+ * Note: ss.ps.ps_ExprContext is used to evaluate any qual or projection
+ * expressions attached to the node. We create a second ExprContext,
+ * rowcontext, in which to build the executor expression state for each
+ * Values sublist. Resetting this context lets us get rid of expression
+ * state for each row, avoiding major memory leakage over a long values list.
+ * However, that doesn't work for sublists containing SubPlans, because a
+ * SubPlan has to be connected up to the outer plan tree to work properly.
+ * Therefore, for only those sublists containing SubPlans, we do expression
+ * state construction at executor start, and store those pointers in
+ * exprstatelists[]. NULL entries in that array correspond to simple
+ * subexpressions that are handled as described above.
+ * ----------------
+ */
+typedef struct ValuesScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprContext *rowcontext;
+ List **exprlists;
+ List **exprstatelists;
+ int array_len;
+ int curr_idx;
+} ValuesScanState;
+
+/* ----------------
+ * TableFuncScanState node
+ *
+ * Used in table-expression functions like XMLTABLE.
+ * ----------------
+ */
+typedef struct TableFuncScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprState *docexpr; /* state for document expression */
+ ExprState *rowexpr; /* state for row-generating expression */
+ List *colexprs; /* state for column-generating expression */
+ List *coldefexprs; /* state for column default expressions */
+ List *ns_names; /* same as TableFunc.ns_names */
+ List *ns_uris; /* list of states of namespace URI exprs */
+ Bitmapset *notnulls; /* nullability flag for each output column */
+ void *opaque; /* table builder private space */
+ const struct TableFuncRoutine *routine; /* table builder methods */
+ FmgrInfo *in_functions; /* input function for each column */
+ Oid *typioparams; /* typioparam for each column */
+ int64 ordinal; /* row number to be output next */
+ MemoryContext perTableCxt; /* per-table context */
+ Tuplestorestate *tupstore; /* output tuple store */
+} TableFuncScanState;
+
+/* ----------------
+ * CteScanState information
+ *
+ * CteScan nodes are used to scan a CommonTableExpr query.
+ *
+ * Multiple CteScan nodes can read out from the same CTE query. We use
+ * a tuplestore to hold rows that have been read from the CTE query but
+ * not yet consumed by all readers.
+ * ----------------
+ */
+typedef struct CteScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ int eflags; /* capability flags to pass to tuplestore */
+ int readptr; /* index of my tuplestore read pointer */
+ PlanState *cteplanstate; /* PlanState for the CTE query itself */
+ /* Link to the "leader" CteScanState (possibly this same node) */
+ struct CteScanState *leader;
+ /* The remaining fields are only valid in the "leader" CteScanState */
+ Tuplestorestate *cte_table; /* rows already read from the CTE query */
+ bool eof_cte; /* reached end of CTE query? */
+} CteScanState;
+
+/* ----------------
+ * NamedTuplestoreScanState information
+ *
+ * NamedTuplestoreScan nodes are used to scan a Tuplestore created and
+ * named prior to execution of the query. An example is a transition
+ * table for an AFTER trigger.
+ *
+ * Multiple NamedTuplestoreScan nodes can read out from the same Tuplestore.
+ * ----------------
+ */
+typedef struct NamedTuplestoreScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ int readptr; /* index of my tuplestore read pointer */
+ TupleDesc tupdesc; /* format of the tuples in the tuplestore */
+ Tuplestorestate *relation; /* the rows */
+} NamedTuplestoreScanState;
+
+/* ----------------
+ * WorkTableScanState information
+ *
+ * WorkTableScan nodes are used to scan the work table created by
+ * a RecursiveUnion node. We locate the RecursiveUnion node
+ * during executor startup.
+ * ----------------
+ */
+typedef struct WorkTableScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ RecursiveUnionState *rustate;
+} WorkTableScanState;
+
+/* ----------------
+ * ForeignScanState information
+ *
+ * ForeignScan nodes are used to scan foreign-data tables.
+ * ----------------
+ */
+typedef struct ForeignScanState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprState *fdw_recheck_quals; /* original quals not in ss.ps.qual */
+ Size pscan_len; /* size of parallel coordination information */
+ ResultRelInfo *resultRelInfo; /* result rel info, if UPDATE or DELETE */
+ /* use struct pointer to avoid including fdwapi.h here */
+ struct FdwRoutine *fdwroutine;
+ void *fdw_state; /* foreign-data wrapper can keep state here */
+} ForeignScanState;
+
+/* ----------------
+ * CustomScanState information
+ *
+ * CustomScan nodes are used to execute custom code within executor.
+ *
+ * Core code must avoid assuming that the CustomScanState is only as large as
+ * the structure declared here; providers are allowed to make it the first
+ * element in a larger structure, and typically would need to do so. The
+ * struct is actually allocated by the CreateCustomScanState method associated
+ * with the plan node. Any additional fields can be initialized there, or in
+ * the BeginCustomScan method.
+ * ----------------
+ */
+struct CustomExecMethods;
+
+typedef struct CustomScanState
+{
+ ScanState ss;
+ uint32 flags; /* mask of CUSTOMPATH_* flags, see
+ * nodes/extensible.h */
+ List *custom_ps; /* list of child PlanState nodes, if any */
+ Size pscan_len; /* size of parallel coordination information */
+ const struct CustomExecMethods *methods;
+ const struct TupleTableSlotOps *slotOps;
+} CustomScanState;
+
+/* ----------------------------------------------------------------
+ * Join State Information
+ * ----------------------------------------------------------------
+ */
+
+/* ----------------
+ * JoinState information
+ *
+ * Superclass for state nodes of join plans.
+ * ----------------
+ */
+typedef struct JoinState
+{
+ PlanState ps;
+ JoinType jointype;
+ bool single_match; /* True if we should skip to next outer tuple
+ * after finding one inner match */
+ ExprState *joinqual; /* JOIN quals (in addition to ps.qual) */
+} JoinState;
+
+/* ----------------
+ * NestLoopState information
+ *
+ * NeedNewOuter true if need new outer tuple on next call
+ * MatchedOuter true if found a join match for current outer tuple
+ * NullInnerTupleSlot prepared null tuple for left outer joins
+ * ----------------
+ */
+typedef struct NestLoopState
+{
+ JoinState js; /* its first field is NodeTag */
+ bool nl_NeedNewOuter;
+ bool nl_MatchedOuter;
+ TupleTableSlot *nl_NullInnerTupleSlot;
+} NestLoopState;
+
+/* ----------------
+ * MergeJoinState information
+ *
+ * NumClauses number of mergejoinable join clauses
+ * Clauses info for each mergejoinable clause
+ * JoinState current state of ExecMergeJoin state machine
+ * SkipMarkRestore true if we may skip Mark and Restore operations
+ * ExtraMarks true to issue extra Mark operations on inner scan
+ * ConstFalseJoin true if we have a constant-false joinqual
+ * FillOuter true if should emit unjoined outer tuples anyway
+ * FillInner true if should emit unjoined inner tuples anyway
+ * MatchedOuter true if found a join match for current outer tuple
+ * MatchedInner true if found a join match for current inner tuple
+ * OuterTupleSlot slot in tuple table for cur outer tuple
+ * InnerTupleSlot slot in tuple table for cur inner tuple
+ * MarkedTupleSlot slot in tuple table for marked tuple
+ * NullOuterTupleSlot prepared null tuple for right outer joins
+ * NullInnerTupleSlot prepared null tuple for left outer joins
+ * OuterEContext workspace for computing outer tuple's join values
+ * InnerEContext workspace for computing inner tuple's join values
+ * ----------------
+ */
+/* private in nodeMergejoin.c: */
+typedef struct MergeJoinClauseData *MergeJoinClause;
+
+typedef struct MergeJoinState
+{
+ JoinState js; /* its first field is NodeTag */
+ int mj_NumClauses;
+ MergeJoinClause mj_Clauses; /* array of length mj_NumClauses */
+ int mj_JoinState;
+ bool mj_SkipMarkRestore;
+ bool mj_ExtraMarks;
+ bool mj_ConstFalseJoin;
+ bool mj_FillOuter;
+ bool mj_FillInner;
+ bool mj_MatchedOuter;
+ bool mj_MatchedInner;
+ TupleTableSlot *mj_OuterTupleSlot;
+ TupleTableSlot *mj_InnerTupleSlot;
+ TupleTableSlot *mj_MarkedTupleSlot;
+ TupleTableSlot *mj_NullOuterTupleSlot;
+ TupleTableSlot *mj_NullInnerTupleSlot;
+ ExprContext *mj_OuterEContext;
+ ExprContext *mj_InnerEContext;
+} MergeJoinState;
+
+/* ----------------
+ * HashJoinState information
+ *
+ * hashclauses original form of the hashjoin condition
+ * hj_OuterHashKeys the outer hash keys in the hashjoin condition
+ * hj_HashOperators the join operators in the hashjoin condition
+ * hj_HashTable hash table for the hashjoin
+ * (NULL if table not built yet)
+ * hj_CurHashValue hash value for current outer tuple
+ * hj_CurBucketNo regular bucket# for current outer tuple
+ * hj_CurSkewBucketNo skew bucket# for current outer tuple
+ * hj_CurTuple last inner tuple matched to current outer
+ * tuple, or NULL if starting search
+ * (hj_CurXXX variables are undefined if
+ * OuterTupleSlot is empty!)
+ * hj_OuterTupleSlot tuple slot for outer tuples
+ * hj_HashTupleSlot tuple slot for inner (hashed) tuples
+ * hj_NullOuterTupleSlot prepared null tuple for right/right-anti/full
+ * outer joins
+ * hj_NullInnerTupleSlot prepared null tuple for left/full outer joins
+ * hj_FirstOuterTupleSlot first tuple retrieved from outer plan
+ * hj_JoinState current state of ExecHashJoin state machine
+ * hj_MatchedOuter true if found a join match for current outer
+ * hj_OuterNotEmpty true if outer relation known not empty
+ * ----------------
+ */
+
+/* these structs are defined in executor/hashjoin.h: */
+typedef struct HashJoinTupleData *HashJoinTuple;
+typedef struct HashJoinTableData *HashJoinTable;
+
+typedef struct HashJoinState
+{
+ JoinState js; /* its first field is NodeTag */
+ ExprState *hashclauses;
+ List *hj_OuterHashKeys; /* list of ExprState nodes */
+ List *hj_HashOperators; /* list of operator OIDs */
+ List *hj_Collations;
+ HashJoinTable hj_HashTable;
+ uint32 hj_CurHashValue;
+ int hj_CurBucketNo;
+ int hj_CurSkewBucketNo;
+ HashJoinTuple hj_CurTuple;
+ TupleTableSlot *hj_OuterTupleSlot;
+ TupleTableSlot *hj_HashTupleSlot;
+ TupleTableSlot *hj_NullOuterTupleSlot;
+ TupleTableSlot *hj_NullInnerTupleSlot;
+ TupleTableSlot *hj_FirstOuterTupleSlot;
+ int hj_JoinState;
+ bool hj_MatchedOuter;
+ bool hj_OuterNotEmpty;
+} HashJoinState;
+
+
+/* ----------------------------------------------------------------
+ * Materialization State Information
+ * ----------------------------------------------------------------
+ */
+
+/* ----------------
+ * MaterialState information
+ *
+ * materialize nodes are used to materialize the results
+ * of a subplan into a temporary file.
+ *
+ * ss.ss_ScanTupleSlot refers to output of underlying plan.
+ * ----------------
+ */
+typedef struct MaterialState
+{
+ ScanState ss; /* its first field is NodeTag */
+ int eflags; /* capability flags to pass to tuplestore */
+ bool eof_underlying; /* reached end of underlying plan? */
+ Tuplestorestate *tuplestorestate;
+} MaterialState;
+
+struct MemoizeEntry;
+struct MemoizeTuple;
+struct MemoizeKey;
+
+typedef struct MemoizeInstrumentation
+{
+ uint64 cache_hits; /* number of rescans where we've found the
+ * scan parameter values to be cached */
+ uint64 cache_misses; /* number of rescans where we've not found the
+ * scan parameter values to be cached. */
+ uint64 cache_evictions; /* number of cache entries removed due to
+ * the need to free memory */
+ uint64 cache_overflows; /* number of times we've had to bypass the
+ * cache when filling it due to not being
+ * able to free enough space to store the
+ * current scan's tuples. */
+ uint64 mem_peak; /* peak memory usage in bytes */
+} MemoizeInstrumentation;
+
+/* ----------------
+ * Shared memory container for per-worker memoize information
+ * ----------------
+ */
+typedef struct SharedMemoizeInfo
+{
+ int num_workers;
+ MemoizeInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER];
+} SharedMemoizeInfo;
+
+/* ----------------
+ * MemoizeState information
+ *
+ * memoize nodes are used to cache recent and commonly seen results from
+ * a parameterized scan.
+ * ----------------
+ */
+typedef struct MemoizeState
+{
+ ScanState ss; /* its first field is NodeTag */
+ int mstatus; /* value of ExecMemoize state machine */
+ int nkeys; /* number of cache keys */
+ struct memoize_hash *hashtable; /* hash table for cache entries */
+ TupleDesc hashkeydesc; /* tuple descriptor for cache keys */
+ TupleTableSlot *tableslot; /* min tuple slot for existing cache entries */
+ TupleTableSlot *probeslot; /* virtual slot used for hash lookups */
+ ExprState *cache_eq_expr; /* Compare exec params to hash key */
+ ExprState **param_exprs; /* exprs containing the parameters to this
+ * node */
+ FmgrInfo *hashfunctions; /* lookup data for hash funcs nkeys in size */
+ Oid *collations; /* collation for comparisons nkeys in size */
+ uint64 mem_used; /* bytes of memory used by cache */
+ uint64 mem_limit; /* memory limit in bytes for the cache */
+ MemoryContext tableContext; /* memory context to store cache data */
+ dlist_head lru_list; /* least recently used entry list */
+ struct MemoizeTuple *last_tuple; /* Used to point to the last tuple
+ * returned during a cache hit and the
+ * tuple we last stored when
+ * populating the cache. */
+ struct MemoizeEntry *entry; /* the entry that 'last_tuple' belongs to or
+ * NULL if 'last_tuple' is NULL. */
+ bool singlerow; /* true if the cache entry is to be marked as
+ * complete after caching the first tuple. */
+ bool binary_mode; /* true when cache key should be compared bit
+ * by bit, false when using hash equality ops */
+ MemoizeInstrumentation stats; /* execution statistics */
+ SharedMemoizeInfo *shared_info; /* statistics for parallel workers */
+ Bitmapset *keyparamids; /* Param->paramids of expressions belonging to
+ * param_exprs */
+} MemoizeState;
+
+/* ----------------
+ * When performing sorting by multiple keys, it's possible that the input
+ * dataset is already sorted on a prefix of those keys. We call these
+ * "presorted keys".
+ * PresortedKeyData represents information about one such key.
+ * ----------------
+ */
+typedef struct PresortedKeyData
+{
+ FmgrInfo flinfo; /* comparison function info */
+ FunctionCallInfo fcinfo; /* comparison function call info */
+ OffsetNumber attno; /* attribute number in tuple */
+} PresortedKeyData;
+
+/* ----------------
+ * Shared memory container for per-worker sort information
+ * ----------------
+ */
+typedef struct SharedSortInfo
+{
+ int num_workers;
+ TuplesortInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER];
+} SharedSortInfo;
+
+/* ----------------
+ * SortState information
+ * ----------------
+ */
+typedef struct SortState
+{
+ ScanState ss; /* its first field is NodeTag */
+ bool randomAccess; /* need random access to sort output? */
+ bool bounded; /* is the result set bounded? */
+ int64 bound; /* if bounded, how many tuples are needed */
+ bool sort_Done; /* sort completed yet? */
+ bool bounded_Done; /* value of bounded we did the sort with */
+ int64 bound_Done; /* value of bound we did the sort with */
+ void *tuplesortstate; /* private state of tuplesort.c */
+ bool am_worker; /* are we a worker? */
+ bool datumSort; /* Datum sort instead of tuple sort? */
+ SharedSortInfo *shared_info; /* one entry per worker */
+} SortState;
+
+/* ----------------
+ * Instrumentation information for IncrementalSort
+ * ----------------
+ */
+typedef struct IncrementalSortGroupInfo
+{
+ int64 groupCount;
+ int64 maxDiskSpaceUsed;
+ int64 totalDiskSpaceUsed;
+ int64 maxMemorySpaceUsed;
+ int64 totalMemorySpaceUsed;
+ bits32 sortMethods; /* bitmask of TuplesortMethod */
+} IncrementalSortGroupInfo;
+
+typedef struct IncrementalSortInfo
+{
+ IncrementalSortGroupInfo fullsortGroupInfo;
+ IncrementalSortGroupInfo prefixsortGroupInfo;
+} IncrementalSortInfo;
+
+/* ----------------
+ * Shared memory container for per-worker incremental sort information
+ * ----------------
+ */
+typedef struct SharedIncrementalSortInfo
+{
+ int num_workers;
+ IncrementalSortInfo sinfo[FLEXIBLE_ARRAY_MEMBER];
+} SharedIncrementalSortInfo;
+
+/* ----------------
+ * IncrementalSortState information
+ * ----------------
+ */
+typedef enum
+{
+ INCSORT_LOADFULLSORT,
+ INCSORT_LOADPREFIXSORT,
+ INCSORT_READFULLSORT,
+ INCSORT_READPREFIXSORT,
+} IncrementalSortExecutionStatus;
+
+typedef struct IncrementalSortState
+{
+ ScanState ss; /* its first field is NodeTag */
+ bool bounded; /* is the result set bounded? */
+ int64 bound; /* if bounded, how many tuples are needed */
+ bool outerNodeDone; /* finished fetching tuples from outer node */
+ int64 bound_Done; /* value of bound we did the sort with */
+ IncrementalSortExecutionStatus execution_status;
+ int64 n_fullsort_remaining;
+ Tuplesortstate *fullsort_state; /* private state of tuplesort.c */
+ Tuplesortstate *prefixsort_state; /* private state of tuplesort.c */
+ /* the keys by which the input path is already sorted */
+ PresortedKeyData *presorted_keys;
+
+ IncrementalSortInfo incsort_info;
+
+ /* slot for pivot tuple defining values of presorted keys within group */
+ TupleTableSlot *group_pivot;
+ TupleTableSlot *transfer_tuple;
+ bool am_worker; /* are we a worker? */
+ SharedIncrementalSortInfo *shared_info; /* one entry per worker */
+} IncrementalSortState;
+
+/* ---------------------
+ * GroupState information
+ * ---------------------
+ */
+typedef struct GroupState
+{
+ ScanState ss; /* its first field is NodeTag */
+ ExprState *eqfunction; /* equality function */
+ bool grp_done; /* indicates completion of Group scan */
+} GroupState;
+
+/* ---------------------
+ * per-worker aggregate information
+ * ---------------------
+ */
+typedef struct AggregateInstrumentation
+{
+ Size hash_mem_peak; /* peak hash table memory usage */
+ uint64 hash_disk_used; /* kB of disk space used */
+ int hash_batches_used; /* batches used during entire execution */
+} AggregateInstrumentation;
+
+/* ----------------
+ * Shared memory container for per-worker aggregate information
+ * ----------------
+ */
+typedef struct SharedAggInfo
+{
+ int num_workers;
+ AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER];
+} SharedAggInfo;
+
+/* ---------------------
+ * AggState information
+ *
+ * ss.ss_ScanTupleSlot refers to output of underlying plan.
+ *
+ * Note: ss.ps.ps_ExprContext contains ecxt_aggvalues and
+ * ecxt_aggnulls arrays, which hold the computed agg values for the current
+ * input group during evaluation of an Agg node's output tuple(s). We
+ * create a second ExprContext, tmpcontext, in which to evaluate input
+ * expressions and run the aggregate transition functions.
+ * ---------------------
+ */
+/* these structs are private in nodeAgg.c: */
+typedef struct AggStatePerAggData *AggStatePerAgg;
+typedef struct AggStatePerTransData *AggStatePerTrans;
+typedef struct AggStatePerGroupData *AggStatePerGroup;
+typedef struct AggStatePerPhaseData *AggStatePerPhase;
+typedef struct AggStatePerHashData *AggStatePerHash;
+
+typedef struct AggState
+{
+ ScanState ss; /* its first field is NodeTag */
+ List *aggs; /* all Aggref nodes in targetlist & quals */
+ int numaggs; /* length of list (could be zero!) */
+ int numtrans; /* number of pertrans items */
+ AggStrategy aggstrategy; /* strategy mode */
+ AggSplit aggsplit; /* agg-splitting mode, see nodes.h */
+ AggStatePerPhase phase; /* pointer to current phase data */
+ int numphases; /* number of phases (including phase 0) */
+ int current_phase; /* current phase number */
+ AggStatePerAgg peragg; /* per-Aggref information */
+ AggStatePerTrans pertrans; /* per-Trans state information */
+ ExprContext *hashcontext; /* econtexts for long-lived data (hashtable) */
+ ExprContext **aggcontexts; /* econtexts for long-lived data (per GS) */
+ ExprContext *tmpcontext; /* econtext for input expressions */
+#define FIELDNO_AGGSTATE_CURAGGCONTEXT 14
+ ExprContext *curaggcontext; /* currently active aggcontext */
+ AggStatePerAgg curperagg; /* currently active aggregate, if any */
+#define FIELDNO_AGGSTATE_CURPERTRANS 16
+ AggStatePerTrans curpertrans; /* currently active trans state, if any */
+ bool input_done; /* indicates end of input */
+ bool agg_done; /* indicates completion of Agg scan */
+ int projected_set; /* The last projected grouping set */
+#define FIELDNO_AGGSTATE_CURRENT_SET 20
+ int current_set; /* The current grouping set being evaluated */
+ Bitmapset *grouped_cols; /* grouped cols in current projection */
+ List *all_grouped_cols; /* list of all grouped cols in DESC order */
+ Bitmapset *colnos_needed; /* all columns needed from the outer plan */
+ int max_colno_needed; /* highest colno needed from outer plan */
+ bool all_cols_needed; /* are all cols from outer plan needed? */
+ /* These fields are for grouping set phase data */
+ int maxsets; /* The max number of sets in any phase */
+ AggStatePerPhase phases; /* array of all phases */
+ Tuplesortstate *sort_in; /* sorted input to phases > 1 */
+ Tuplesortstate *sort_out; /* input is copied here for next phase */
+ TupleTableSlot *sort_slot; /* slot for sort results */
+ /* these fields are used in AGG_PLAIN and AGG_SORTED modes: */
+ AggStatePerGroup *pergroups; /* grouping set indexed array of per-group
+ * pointers */
+ HeapTuple grp_firstTuple; /* copy of first tuple of current group */
+ /* these fields are used in AGG_HASHED and AGG_MIXED modes: */
+ bool table_filled; /* hash table filled yet? */
+ int num_hashes;
+ MemoryContext hash_metacxt; /* memory for hash table itself */
+ struct LogicalTapeSet *hash_tapeset; /* tape set for hash spill tapes */
+ struct HashAggSpill *hash_spills; /* HashAggSpill for each grouping set,
+ * exists only during first pass */
+ TupleTableSlot *hash_spill_rslot; /* for reading spill files */
+ TupleTableSlot *hash_spill_wslot; /* for writing spill files */
+ List *hash_batches; /* hash batches remaining to be processed */
+ bool hash_ever_spilled; /* ever spilled during this execution? */
+ bool hash_spill_mode; /* we hit a limit during the current batch
+ * and we must not create new groups */
+ Size hash_mem_limit; /* limit before spilling hash table */
+ uint64 hash_ngroups_limit; /* limit before spilling hash table */
+ int hash_planned_partitions; /* number of partitions planned
+ * for first pass */
+ double hashentrysize; /* estimate revised during execution */
+ Size hash_mem_peak; /* peak hash table memory usage */
+ uint64 hash_ngroups_current; /* number of groups currently in
+ * memory in all hash tables */
+ uint64 hash_disk_used; /* kB of disk space used */
+ int hash_batches_used; /* batches used during entire execution */
+
+ AggStatePerHash perhash; /* array of per-hashtable data */
+ AggStatePerGroup *hash_pergroup; /* grouping set indexed array of
+ * per-group pointers */
+
+ /* support for evaluation of agg input expressions: */
+#define FIELDNO_AGGSTATE_ALL_PERGROUPS 53
+ AggStatePerGroup *all_pergroups; /* array of first ->pergroups, than
+ * ->hash_pergroup */
+ ProjectionInfo *combinedproj; /* projection machinery */
+ SharedAggInfo *shared_info; /* one entry per worker */
+} AggState;
+
+/* ----------------
+ * WindowAggState information
+ * ----------------
+ */
+/* these structs are private in nodeWindowAgg.c: */
+typedef struct WindowStatePerFuncData *WindowStatePerFunc;
+typedef struct WindowStatePerAggData *WindowStatePerAgg;
+
+/*
+ * WindowAggStatus -- Used to track the status of WindowAggState
+ */
+typedef enum WindowAggStatus
+{
+ WINDOWAGG_DONE, /* No more processing to do */
+ WINDOWAGG_RUN, /* Normal processing of window funcs */
+ WINDOWAGG_PASSTHROUGH, /* Don't eval window funcs */
+ WINDOWAGG_PASSTHROUGH_STRICT /* Pass-through plus don't store new
+ * tuples during spool */
+} WindowAggStatus;
+
+typedef struct WindowAggState
+{
+ ScanState ss; /* its first field is NodeTag */
+
+ /* these fields are filled in by ExecInitExpr: */
+ List *funcs; /* all WindowFunc nodes in targetlist */
+ int numfuncs; /* total number of window functions */
+ int numaggs; /* number that are plain aggregates */
+
+ WindowStatePerFunc perfunc; /* per-window-function information */
+ WindowStatePerAgg peragg; /* per-plain-aggregate information */
+ ExprState *partEqfunction; /* equality funcs for partition columns */
+ ExprState *ordEqfunction; /* equality funcs for ordering columns */
+ Tuplestorestate *buffer; /* stores rows of current partition */
+ int current_ptr; /* read pointer # for current row */
+ int framehead_ptr; /* read pointer # for frame head, if used */
+ int frametail_ptr; /* read pointer # for frame tail, if used */
+ int grouptail_ptr; /* read pointer # for group tail, if used */
+ int64 spooled_rows; /* total # of rows in buffer */
+ int64 currentpos; /* position of current row in partition */
+ int64 frameheadpos; /* current frame head position */
+ int64 frametailpos; /* current frame tail position (frame end+1) */
+ /* use struct pointer to avoid including windowapi.h here */
+ struct WindowObjectData *agg_winobj; /* winobj for aggregate fetches */
+ int64 aggregatedbase; /* start row for current aggregates */
+ int64 aggregatedupto; /* rows before this one are aggregated */
+ WindowAggStatus status; /* run status of WindowAggState */
+
+ int frameOptions; /* frame_clause options, see WindowDef */
+ ExprState *startOffset; /* expression for starting bound offset */
+ ExprState *endOffset; /* expression for ending bound offset */
+ Datum startOffsetValue; /* result of startOffset evaluation */
+ Datum endOffsetValue; /* result of endOffset evaluation */
+
+ /* these fields are used with RANGE offset PRECEDING/FOLLOWING: */
+ FmgrInfo startInRangeFunc; /* in_range function for startOffset */
+ FmgrInfo endInRangeFunc; /* in_range function for endOffset */
+ Oid inRangeColl; /* collation for in_range tests */
+ bool inRangeAsc; /* use ASC sort order for in_range tests? */
+ bool inRangeNullsFirst; /* nulls sort first for in_range tests? */
+
+ /* these fields are used in GROUPS mode: */
+ int64 currentgroup; /* peer group # of current row in partition */
+ int64 frameheadgroup; /* peer group # of frame head row */
+ int64 frametailgroup; /* peer group # of frame tail row */
+ int64 groupheadpos; /* current row's peer group head position */
+ int64 grouptailpos; /* " " " " tail position (group end+1) */
+
+ MemoryContext partcontext; /* context for partition-lifespan data */
+ MemoryContext aggcontext; /* shared context for aggregate working data */
+ MemoryContext curaggcontext; /* current aggregate's working data */
+ ExprContext *tmpcontext; /* short-term evaluation context */
+
+ ExprState *runcondition; /* Condition which must remain true otherwise
+ * execution of the WindowAgg will finish or
+ * go into pass-through mode. NULL when there
+ * is no such condition. */
+
+ bool use_pass_through; /* When false, stop execution when
+ * runcondition is no longer true. Else
+ * just stop evaluating window funcs. */
+ bool top_window; /* true if this is the top-most WindowAgg or
+ * the only WindowAgg in this query level */
+ bool all_first; /* true if the scan is starting */
+ bool partition_spooled; /* true if all tuples in current partition
+ * have been spooled into tuplestore */
+ bool more_partitions; /* true if there's more partitions after
+ * this one */
+ bool framehead_valid; /* true if frameheadpos is known up to
+ * date for current row */
+ bool frametail_valid; /* true if frametailpos is known up to
+ * date for current row */
+ bool grouptail_valid; /* true if grouptailpos is known up to
+ * date for current row */
+
+ TupleTableSlot *first_part_slot; /* first tuple of current or next
+ * partition */
+ TupleTableSlot *framehead_slot; /* first tuple of current frame */
+ TupleTableSlot *frametail_slot; /* first tuple after current frame */
+
+ /* temporary slots for tuples fetched back from tuplestore */
+ TupleTableSlot *agg_row_slot;
+ TupleTableSlot *temp_slot_1;
+ TupleTableSlot *temp_slot_2;
+} WindowAggState;
+
+/* ----------------
+ * UniqueState information
+ *
+ * Unique nodes are used "on top of" sort nodes to discard
+ * duplicate tuples returned from the sort phase. Basically
+ * all it does is compare the current tuple from the subplan
+ * with the previously fetched tuple (stored in its result slot).
+ * If the two are identical in all interesting fields, then
+ * we just fetch another tuple from the sort and try again.
+ * ----------------
+ */
+typedef struct UniqueState
+{
+ PlanState ps; /* its first field is NodeTag */
+ ExprState *eqfunction; /* tuple equality qual */
+} UniqueState;
+
+/* ----------------
+ * GatherState information
+ *
+ * Gather nodes launch 1 or more parallel workers, run a subplan
+ * in those workers, and collect the results.
+ * ----------------
+ */
+typedef struct GatherState
+{
+ PlanState ps; /* its first field is NodeTag */
+ bool initialized; /* workers launched? */
+ bool need_to_scan_locally; /* need to read from local plan? */
+ int64 tuples_needed; /* tuple bound, see ExecSetTupleBound */
+ /* these fields are set up once: */
+ TupleTableSlot *funnel_slot;
+ struct ParallelExecutorInfo *pei;
+ /* all remaining fields are reinitialized during a rescan: */
+ int nworkers_launched; /* original number of workers */
+ int nreaders; /* number of still-active workers */
+ int nextreader; /* next one to try to read from */
+ struct TupleQueueReader **reader; /* array with nreaders active entries */
+} GatherState;
+
+/* ----------------
+ * GatherMergeState information
+ *
+ * Gather merge nodes launch 1 or more parallel workers, run a
+ * subplan which produces sorted output in each worker, and then
+ * merge the results into a single sorted stream.
+ * ----------------
+ */
+struct GMReaderTupleBuffer; /* private in nodeGatherMerge.c */
+
+typedef struct GatherMergeState
+{
+ PlanState ps; /* its first field is NodeTag */
+ bool initialized; /* workers launched? */
+ bool gm_initialized; /* gather_merge_init() done? */
+ bool need_to_scan_locally; /* need to read from local plan? */
+ int64 tuples_needed; /* tuple bound, see ExecSetTupleBound */
+ /* these fields are set up once: */
+ TupleDesc tupDesc; /* descriptor for subplan result tuples */
+ int gm_nkeys; /* number of sort columns */
+ SortSupport gm_sortkeys; /* array of length gm_nkeys */
+ struct ParallelExecutorInfo *pei;
+ /* all remaining fields are reinitialized during a rescan */
+ /* (but the arrays are not reallocated, just cleared) */
+ int nworkers_launched; /* original number of workers */
+ int nreaders; /* number of active workers */
+ TupleTableSlot **gm_slots; /* array with nreaders+1 entries */
+ struct TupleQueueReader **reader; /* array with nreaders active entries */
+ struct GMReaderTupleBuffer *gm_tuple_buffers; /* nreaders tuple buffers */
+ struct binaryheap *gm_heap; /* binary heap of slot indices */
+} GatherMergeState;
+
+/* ----------------
+ * Values displayed by EXPLAIN ANALYZE
+ * ----------------
+ */
+typedef struct HashInstrumentation
+{
+ int nbuckets; /* number of buckets at end of execution */
+ int nbuckets_original; /* planned number of buckets */
+ int nbatch; /* number of batches at end of execution */
+ int nbatch_original; /* planned number of batches */
+ Size space_peak; /* peak memory usage in bytes */
+} HashInstrumentation;
+
+/* ----------------
+ * Shared memory container for per-worker hash information
+ * ----------------
+ */
+typedef struct SharedHashInfo
+{
+ int num_workers;
+ HashInstrumentation hinstrument[FLEXIBLE_ARRAY_MEMBER];
+} SharedHashInfo;
+
+/* ----------------
+ * HashState information
+ * ----------------
+ */
+typedef struct HashState
+{
+ PlanState ps; /* its first field is NodeTag */
+ HashJoinTable hashtable; /* hash table for the hashjoin */
+ List *hashkeys; /* list of ExprState nodes */
+
+ /*
+ * In a parallelized hash join, the leader retains a pointer to the
+ * shared-memory stats area in its shared_info field, and then copies the
+ * shared-memory info back to local storage before DSM shutdown. The
+ * shared_info field remains NULL in workers, or in non-parallel joins.
+ */
+ SharedHashInfo *shared_info;
+
+ /*
+ * If we are collecting hash stats, this points to an initially-zeroed
+ * collection area, which could be either local storage or in shared
+ * memory; either way it's for just one process.
+ */
+ HashInstrumentation *hinstrument;
+
+ /* Parallel hash state. */
+ struct ParallelHashJoinState *parallel_state;
+} HashState;
+
+/* ----------------
+ * SetOpState information
+ *
+ * Even in "sorted" mode, SetOp nodes are more complex than a simple
+ * Unique, since we have to count how many duplicates to return. But
+ * we also support hashing, so this is really more like a cut-down
+ * form of Agg.
+ * ----------------
+ */
+/* this struct is private in nodeSetOp.c: */
+typedef struct SetOpStatePerGroupData *SetOpStatePerGroup;
+
+typedef struct SetOpState
+{
+ PlanState ps; /* its first field is NodeTag */
+ ExprState *eqfunction; /* equality comparator */
+ Oid *eqfuncoids; /* per-grouping-field equality fns */
+ FmgrInfo *hashfunctions; /* per-grouping-field hash fns */
+ bool setop_done; /* indicates completion of output scan */
+ long numOutput; /* number of dups left to output */
+ /* these fields are used in SETOP_SORTED mode: */
+ SetOpStatePerGroup pergroup; /* per-group working state */
+ HeapTuple grp_firstTuple; /* copy of first tuple of current group */
+ /* these fields are used in SETOP_HASHED mode: */
+ TupleHashTable hashtable; /* hash table with one entry per group */
+ MemoryContext tableContext; /* memory context containing hash table */
+ bool table_filled; /* hash table filled yet? */
+ TupleHashIterator hashiter; /* for iterating through hash table */
+} SetOpState;
+
+/* ----------------
+ * LockRowsState information
+ *
+ * LockRows nodes are used to enforce FOR [KEY] UPDATE/SHARE locking.
+ * ----------------
+ */
+typedef struct LockRowsState
+{
+ PlanState ps; /* its first field is NodeTag */
+ List *lr_arowMarks; /* List of ExecAuxRowMarks */
+ EPQState lr_epqstate; /* for evaluating EvalPlanQual rechecks */
+} LockRowsState;
+
+/* ----------------
+ * LimitState information
+ *
+ * Limit nodes are used to enforce LIMIT/OFFSET clauses.
+ * They just select the desired subrange of their subplan's output.
+ *
+ * offset is the number of initial tuples to skip (0 does nothing).
+ * count is the number of tuples to return after skipping the offset tuples.
+ * If no limit count was specified, count is undefined and noCount is true.
+ * When lstate == LIMIT_INITIAL, offset/count/noCount haven't been set yet.
+ * ----------------
+ */
+typedef enum
+{
+ LIMIT_INITIAL, /* initial state for LIMIT node */
+ LIMIT_RESCAN, /* rescan after recomputing parameters */
+ LIMIT_EMPTY, /* there are no returnable rows */
+ LIMIT_INWINDOW, /* have returned a row in the window */
+ LIMIT_WINDOWEND_TIES, /* have returned a tied row */
+ LIMIT_SUBPLANEOF, /* at EOF of subplan (within window) */
+ LIMIT_WINDOWEND, /* stepped off end of window */
+ LIMIT_WINDOWSTART /* stepped off beginning of window */
+} LimitStateCond;
+
+typedef struct LimitState
+{
+ PlanState ps; /* its first field is NodeTag */
+ ExprState *limitOffset; /* OFFSET parameter, or NULL if none */
+ ExprState *limitCount; /* COUNT parameter, or NULL if none */
+ LimitOption limitOption; /* limit specification type */
+ int64 offset; /* current OFFSET value */
+ int64 count; /* current COUNT, if any */
+ bool noCount; /* if true, ignore count */
+ LimitStateCond lstate; /* state machine status, as above */
+ int64 position; /* 1-based index of last tuple returned */
+ TupleTableSlot *subSlot; /* tuple last obtained from subplan */
+ ExprState *eqfunction; /* tuple equality qual in case of WITH TIES
+ * option */
+ TupleTableSlot *last_slot; /* slot for evaluation of ties */
+} LimitState;
+
+#endif /* EXECNODES_H */
diff --git a/pgsql/include/server/nodes/extensible.h b/pgsql/include/server/nodes/extensible.h
new file mode 100644
index 0000000000000000000000000000000000000000..7d51c6033e7186f7d8363118ff932318ab93e2e5
--- /dev/null
+++ b/pgsql/include/server/nodes/extensible.h
@@ -0,0 +1,164 @@
+/*-------------------------------------------------------------------------
+ *
+ * extensible.h
+ * Definitions for extensible nodes and custom scans
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/extensible.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef EXTENSIBLE_H
+#define EXTENSIBLE_H
+
+#include "access/parallel.h"
+#include "commands/explain.h"
+#include "nodes/execnodes.h"
+#include "nodes/pathnodes.h"
+#include "nodes/plannodes.h"
+
+/* maximum length of an extensible node identifier */
+#define EXTNODENAME_MAX_LEN 64
+
+/*
+ * An extensible node is a new type of node defined by an extension. The
+ * type is always T_ExtensibleNode, while the extnodename identifies the
+ * specific type of node. extnodename can be looked up to find the
+ * ExtensibleNodeMethods for this node type.
+ */
+typedef struct ExtensibleNode
+{
+ pg_node_attr(custom_copy_equal, custom_read_write)
+
+ NodeTag type;
+ const char *extnodename; /* identifier of ExtensibleNodeMethods */
+} ExtensibleNode;
+
+/*
+ * node_size is the size of an extensible node of this type in bytes.
+ *
+ * nodeCopy is a function which performs a deep copy from oldnode to newnode.
+ * It does not need to copy type or extnodename, which are copied by the
+ * core system.
+ *
+ * nodeEqual is a function which performs a deep equality comparison between
+ * a and b and returns true or false accordingly. It does not need to compare
+ * type or extnodename, which are compared by the core system.
+ *
+ * nodeOut is a serialization function for the node type. It should use the
+ * output conventions typical for outfuncs.c. It does not need to output
+ * type or extnodename; the core system handles those.
+ *
+ * nodeRead is a deserialization function for the node type. It does not need
+ * to read type or extnodename; the core system handles those. It should fetch
+ * the next token using pg_strtok() from the current input stream, and then
+ * reconstruct the private fields according to the manner in readfuncs.c.
+ *
+ * All callbacks are mandatory.
+ */
+typedef struct ExtensibleNodeMethods
+{
+ const char *extnodename;
+ Size node_size;
+ void (*nodeCopy) (struct ExtensibleNode *newnode,
+ const struct ExtensibleNode *oldnode);
+ bool (*nodeEqual) (const struct ExtensibleNode *a,
+ const struct ExtensibleNode *b);
+ void (*nodeOut) (struct StringInfoData *str,
+ const struct ExtensibleNode *node);
+ void (*nodeRead) (struct ExtensibleNode *node);
+} ExtensibleNodeMethods;
+
+extern void RegisterExtensibleNodeMethods(const ExtensibleNodeMethods *methods);
+extern const ExtensibleNodeMethods *GetExtensibleNodeMethods(const char *extnodename,
+ bool missing_ok);
+
+/*
+ * Flags for custom paths, indicating what capabilities the resulting scan
+ * will have. The flags fields of CustomPath and CustomScan nodes are
+ * bitmasks of these flags.
+ */
+#define CUSTOMPATH_SUPPORT_BACKWARD_SCAN 0x0001
+#define CUSTOMPATH_SUPPORT_MARK_RESTORE 0x0002
+#define CUSTOMPATH_SUPPORT_PROJECTION 0x0004
+
+/*
+ * Custom path methods. Mostly, we just need to know how to convert a
+ * CustomPath to a plan.
+ */
+typedef struct CustomPathMethods
+{
+ const char *CustomName;
+
+ /* Convert Path to a Plan */
+ struct Plan *(*PlanCustomPath) (PlannerInfo *root,
+ RelOptInfo *rel,
+ struct CustomPath *best_path,
+ List *tlist,
+ List *clauses,
+ List *custom_plans);
+ struct List *(*ReparameterizeCustomPathByChild) (PlannerInfo *root,
+ List *custom_private,
+ RelOptInfo *child_rel);
+} CustomPathMethods;
+
+/*
+ * Custom scan. Here again, there's not much to do: we need to be able to
+ * generate a ScanState corresponding to the scan.
+ */
+typedef struct CustomScanMethods
+{
+ const char *CustomName;
+
+ /* Create execution state (CustomScanState) from a CustomScan plan node */
+ Node *(*CreateCustomScanState) (CustomScan *cscan);
+} CustomScanMethods;
+
+/*
+ * Execution-time methods for a CustomScanState. This is more complex than
+ * what we need for a custom path or scan.
+ */
+typedef struct CustomExecMethods
+{
+ const char *CustomName;
+
+ /* Required executor methods */
+ void (*BeginCustomScan) (CustomScanState *node,
+ EState *estate,
+ int eflags);
+ TupleTableSlot *(*ExecCustomScan) (CustomScanState *node);
+ void (*EndCustomScan) (CustomScanState *node);
+ void (*ReScanCustomScan) (CustomScanState *node);
+
+ /* Optional methods: needed if mark/restore is supported */
+ void (*MarkPosCustomScan) (CustomScanState *node);
+ void (*RestrPosCustomScan) (CustomScanState *node);
+
+ /* Optional methods: needed if parallel execution is supported */
+ Size (*EstimateDSMCustomScan) (CustomScanState *node,
+ ParallelContext *pcxt);
+ void (*InitializeDSMCustomScan) (CustomScanState *node,
+ ParallelContext *pcxt,
+ void *coordinate);
+ void (*ReInitializeDSMCustomScan) (CustomScanState *node,
+ ParallelContext *pcxt,
+ void *coordinate);
+ void (*InitializeWorkerCustomScan) (CustomScanState *node,
+ shm_toc *toc,
+ void *coordinate);
+ void (*ShutdownCustomScan) (CustomScanState *node);
+
+ /* Optional: print additional information in EXPLAIN */
+ void (*ExplainCustomScan) (CustomScanState *node,
+ List *ancestors,
+ ExplainState *es);
+} CustomExecMethods;
+
+extern void RegisterCustomScanMethods(const CustomScanMethods *methods);
+extern const CustomScanMethods *GetCustomScanMethods(const char *CustomName,
+ bool missing_ok);
+
+#endif /* EXTENSIBLE_H */
diff --git a/pgsql/include/server/nodes/lockoptions.h b/pgsql/include/server/nodes/lockoptions.h
new file mode 100644
index 0000000000000000000000000000000000000000..bc5e98336f17700d99694e6b07ebb66fb90e8d1f
--- /dev/null
+++ b/pgsql/include/server/nodes/lockoptions.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * lockoptions.h
+ * Common header for some locking-related declarations.
+ *
+ *
+ * Copyright (c) 2014-2023, PostgreSQL Global Development Group
+ *
+ * src/include/nodes/lockoptions.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOCKOPTIONS_H
+#define LOCKOPTIONS_H
+
+/*
+ * This enum represents the different strengths of FOR UPDATE/SHARE clauses.
+ * The ordering here is important, because the highest numerical value takes
+ * precedence when a RTE is specified multiple ways. See applyLockingClause.
+ */
+typedef enum LockClauseStrength
+{
+ LCS_NONE, /* no such clause - only used in PlanRowMark */
+ LCS_FORKEYSHARE, /* FOR KEY SHARE */
+ LCS_FORSHARE, /* FOR SHARE */
+ LCS_FORNOKEYUPDATE, /* FOR NO KEY UPDATE */
+ LCS_FORUPDATE /* FOR UPDATE */
+} LockClauseStrength;
+
+/*
+ * This enum controls how to deal with rows being locked by FOR UPDATE/SHARE
+ * clauses (i.e., it represents the NOWAIT and SKIP LOCKED options).
+ * The ordering here is important, because the highest numerical value takes
+ * precedence when a RTE is specified multiple ways. See applyLockingClause.
+ */
+typedef enum LockWaitPolicy
+{
+ /* Wait for the lock to become available (default behavior) */
+ LockWaitBlock,
+ /* Skip rows that can't be locked (SKIP LOCKED) */
+ LockWaitSkip,
+ /* Raise an error if a row cannot be locked (NOWAIT) */
+ LockWaitError
+} LockWaitPolicy;
+
+/*
+ * Possible lock modes for a tuple.
+ */
+typedef enum LockTupleMode
+{
+ /* SELECT FOR KEY SHARE */
+ LockTupleKeyShare,
+ /* SELECT FOR SHARE */
+ LockTupleShare,
+ /* SELECT FOR NO KEY UPDATE, and UPDATEs that don't modify key columns */
+ LockTupleNoKeyExclusive,
+ /* SELECT FOR UPDATE, UPDATEs that modify key columns, and DELETE */
+ LockTupleExclusive
+} LockTupleMode;
+
+#endif /* LOCKOPTIONS_H */
diff --git a/pgsql/include/server/nodes/makefuncs.h b/pgsql/include/server/nodes/makefuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..3180703005507a4893cf17d32616ee1437898bc8
--- /dev/null
+++ b/pgsql/include/server/nodes/makefuncs.h
@@ -0,0 +1,121 @@
+/*-------------------------------------------------------------------------
+ *
+ * makefuncs.h
+ * prototypes for the creator functions of various nodes
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/makefuncs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MAKEFUNC_H
+#define MAKEFUNC_H
+
+#include "nodes/execnodes.h"
+#include "nodes/parsenodes.h"
+
+
+extern A_Expr *makeA_Expr(A_Expr_Kind kind, List *name,
+ Node *lexpr, Node *rexpr, int location);
+
+extern A_Expr *makeSimpleA_Expr(A_Expr_Kind kind, char *name,
+ Node *lexpr, Node *rexpr, int location);
+
+extern Var *makeVar(int varno,
+ AttrNumber varattno,
+ Oid vartype,
+ int32 vartypmod,
+ Oid varcollid,
+ Index varlevelsup);
+
+extern Var *makeVarFromTargetEntry(int varno,
+ TargetEntry *tle);
+
+extern Var *makeWholeRowVar(RangeTblEntry *rte,
+ int varno,
+ Index varlevelsup,
+ bool allowScalar);
+
+extern TargetEntry *makeTargetEntry(Expr *expr,
+ AttrNumber resno,
+ char *resname,
+ bool resjunk);
+
+extern TargetEntry *flatCopyTargetEntry(TargetEntry *src_tle);
+
+extern FromExpr *makeFromExpr(List *fromlist, Node *quals);
+
+extern Const *makeConst(Oid consttype,
+ int32 consttypmod,
+ Oid constcollid,
+ int constlen,
+ Datum constvalue,
+ bool constisnull,
+ bool constbyval);
+
+extern Const *makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid);
+
+extern Node *makeBoolConst(bool value, bool isnull);
+
+extern Expr *makeBoolExpr(BoolExprType boolop, List *args, int location);
+
+extern Alias *makeAlias(const char *aliasname, List *colnames);
+
+extern RelabelType *makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod,
+ Oid rcollid, CoercionForm rformat);
+
+extern RangeVar *makeRangeVar(char *schemaname, char *relname, int location);
+
+extern TypeName *makeTypeName(char *typnam);
+extern TypeName *makeTypeNameFromNameList(List *names);
+extern TypeName *makeTypeNameFromOid(Oid typeOid, int32 typmod);
+
+extern ColumnDef *makeColumnDef(const char *colname,
+ Oid typeOid, int32 typmod, Oid collOid);
+
+extern FuncExpr *makeFuncExpr(Oid funcid, Oid rettype, List *args,
+ Oid funccollid, Oid inputcollid, CoercionForm fformat);
+
+extern FuncCall *makeFuncCall(List *name, List *args,
+ CoercionForm funcformat, int location);
+
+extern Expr *make_opclause(Oid opno, Oid opresulttype, bool opretset,
+ Expr *leftop, Expr *rightop,
+ Oid opcollid, Oid inputcollid);
+
+extern Expr *make_andclause(List *andclauses);
+extern Expr *make_orclause(List *orclauses);
+extern Expr *make_notclause(Expr *notclause);
+
+extern Node *make_and_qual(Node *qual1, Node *qual2);
+extern Expr *make_ands_explicit(List *andclauses);
+extern List *make_ands_implicit(Expr *clause);
+
+extern IndexInfo *makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid,
+ List *expressions, List *predicates,
+ bool unique, bool nulls_not_distinct,
+ bool isready, bool concurrent,
+ bool summarizing);
+
+extern DefElem *makeDefElem(char *name, Node *arg, int location);
+extern DefElem *makeDefElemExtended(char *nameSpace, char *name, Node *arg,
+ DefElemAction defaction, int location);
+
+extern GroupingSet *makeGroupingSet(GroupingSetKind kind, List *content, int location);
+
+extern VacuumRelation *makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols);
+
+extern JsonFormat *makeJsonFormat(JsonFormatType type, JsonEncoding encoding,
+ int location);
+extern JsonValueExpr *makeJsonValueExpr(Expr *raw_expr, Expr *formatted_expr,
+ JsonFormat *format);
+extern Node *makeJsonKeyValue(Node *key, Node *value);
+extern Node *makeJsonIsPredicate(Node *expr, JsonFormat *format,
+ JsonValueType item_type, bool unique_keys,
+ int location);
+extern JsonEncoding makeJsonEncoding(char *name);
+
+#endif /* MAKEFUNC_H */
diff --git a/pgsql/include/server/nodes/memnodes.h b/pgsql/include/server/nodes/memnodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff6453bb7ac71a9a993a6df4dc70e3e906490897
--- /dev/null
+++ b/pgsql/include/server/nodes/memnodes.h
@@ -0,0 +1,113 @@
+/*-------------------------------------------------------------------------
+ *
+ * memnodes.h
+ * POSTGRES memory context node definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/memnodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MEMNODES_H
+#define MEMNODES_H
+
+#include "nodes/nodes.h"
+
+/*
+ * MemoryContextCounters
+ * Summarization state for MemoryContextStats collection.
+ *
+ * The set of counters in this struct is biased towards AllocSet; if we ever
+ * add any context types that are based on fundamentally different approaches,
+ * we might need more or different counters here. A possible API spec then
+ * would be to print only nonzero counters, but for now we just summarize in
+ * the format historically used by AllocSet.
+ */
+typedef struct MemoryContextCounters
+{
+ Size nblocks; /* Total number of malloc blocks */
+ Size freechunks; /* Total number of free chunks */
+ Size totalspace; /* Total bytes requested from malloc */
+ Size freespace; /* The unused portion of totalspace */
+} MemoryContextCounters;
+
+/*
+ * MemoryContext
+ * A logical context in which memory allocations occur.
+ *
+ * MemoryContext itself is an abstract type that can have multiple
+ * implementations.
+ * The function pointers in MemoryContextMethods define one specific
+ * implementation of MemoryContext --- they are a virtual function table
+ * in C++ terms.
+ *
+ * Node types that are actual implementations of memory contexts must
+ * begin with the same fields as MemoryContextData.
+ *
+ * Note: for largely historical reasons, typedef MemoryContext is a pointer
+ * to the context struct rather than the struct type itself.
+ */
+
+typedef void (*MemoryStatsPrintFunc) (MemoryContext context, void *passthru,
+ const char *stats_string,
+ bool print_to_stderr);
+
+typedef struct MemoryContextMethods
+{
+ void *(*alloc) (MemoryContext context, Size size);
+ /* call this free_p in case someone #define's free() */
+ void (*free_p) (void *pointer);
+ void *(*realloc) (void *pointer, Size size);
+ void (*reset) (MemoryContext context);
+ void (*delete_context) (MemoryContext context);
+ MemoryContext (*get_chunk_context) (void *pointer);
+ Size (*get_chunk_space) (void *pointer);
+ bool (*is_empty) (MemoryContext context);
+ void (*stats) (MemoryContext context,
+ MemoryStatsPrintFunc printfunc, void *passthru,
+ MemoryContextCounters *totals,
+ bool print_to_stderr);
+#ifdef MEMORY_CONTEXT_CHECKING
+ void (*check) (MemoryContext context);
+#endif
+} MemoryContextMethods;
+
+
+typedef struct MemoryContextData
+{
+ pg_node_attr(abstract) /* there are no nodes of this type */
+
+ NodeTag type; /* identifies exact kind of context */
+ /* these two fields are placed here to minimize alignment wastage: */
+ bool isReset; /* T = no space alloced since last reset */
+ bool allowInCritSection; /* allow palloc in critical section */
+ Size mem_allocated; /* track memory allocated for this context */
+ const MemoryContextMethods *methods; /* virtual function table */
+ MemoryContext parent; /* NULL if no parent (toplevel context) */
+ MemoryContext firstchild; /* head of linked list of children */
+ MemoryContext prevchild; /* previous child of same parent */
+ MemoryContext nextchild; /* next child of same parent */
+ const char *name; /* context name (just for debugging) */
+ const char *ident; /* context ID if any (just for debugging) */
+ MemoryContextCallback *reset_cbs; /* list of reset/delete callbacks */
+} MemoryContextData;
+
+/* utils/palloc.h contains typedef struct MemoryContextData *MemoryContext */
+
+
+/*
+ * MemoryContextIsValid
+ * True iff memory context is valid.
+ *
+ * Add new context types to the set accepted by this macro.
+ */
+#define MemoryContextIsValid(context) \
+ ((context) != NULL && \
+ (IsA((context), AllocSetContext) || \
+ IsA((context), SlabContext) || \
+ IsA((context), GenerationContext)))
+
+#endif /* MEMNODES_H */
diff --git a/pgsql/include/server/nodes/miscnodes.h b/pgsql/include/server/nodes/miscnodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..79cc0db4754973795af3fa0d751eec4a05709909
--- /dev/null
+++ b/pgsql/include/server/nodes/miscnodes.h
@@ -0,0 +1,56 @@
+/*-------------------------------------------------------------------------
+ *
+ * miscnodes.h
+ * Definitions for hard-to-classify node types.
+ *
+ * Node types declared here are not part of parse trees, plan trees,
+ * or execution state trees. We only assign them NodeTag values because
+ * IsA() tests provide a convenient way to disambiguate what kind of
+ * structure is being passed through assorted APIs, such as function
+ * "context" pointers.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/miscnodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MISCNODES_H
+#define MISCNODES_H
+
+#include "nodes/nodes.h"
+
+/*
+ * ErrorSaveContext -
+ * function call context node for handling of "soft" errors
+ *
+ * A caller wishing to trap soft errors must initialize a struct like this
+ * with all fields zero/NULL except for the NodeTag. Optionally, set
+ * details_wanted = true if more than the bare knowledge that a soft error
+ * occurred is required. The struct is then passed to a SQL-callable function
+ * via the FunctionCallInfo.context field; or below the level of SQL calls,
+ * it could be passed to a subroutine directly.
+ *
+ * After calling code that might report an error this way, check
+ * error_occurred to see if an error happened. If so, and if details_wanted
+ * is true, error_data has been filled with error details (stored in the
+ * callee's memory context!). FreeErrorData() can be called to release
+ * error_data, although that step is typically not necessary if the called
+ * code was run in a short-lived context.
+ */
+typedef struct ErrorSaveContext
+{
+ NodeTag type;
+ bool error_occurred; /* set to true if we detect a soft error */
+ bool details_wanted; /* does caller want more info than that? */
+ ErrorData *error_data; /* details of error, if so */
+} ErrorSaveContext;
+
+/* Often-useful macro for checking if a soft error was reported */
+#define SOFT_ERROR_OCCURRED(escontext) \
+ ((escontext) != NULL && IsA(escontext, ErrorSaveContext) && \
+ ((ErrorSaveContext *) (escontext))->error_occurred)
+
+#endif /* MISCNODES_H */
diff --git a/pgsql/include/server/nodes/multibitmapset.h b/pgsql/include/server/nodes/multibitmapset.h
new file mode 100644
index 0000000000000000000000000000000000000000..505f017d688a8400a98e0abacca5f1bb8611952d
--- /dev/null
+++ b/pgsql/include/server/nodes/multibitmapset.h
@@ -0,0 +1,39 @@
+/*-------------------------------------------------------------------------
+ *
+ * multibitmapset.h
+ * Lists of Bitmapsets
+ *
+ * A multibitmapset is useful in situations where members of a set can
+ * be identified by two small integers; for example, varno and varattno
+ * of a group of Vars within a query. The implementation is a List of
+ * Bitmapsets, so that the empty set can be represented by NIL. (But,
+ * as with Bitmapsets, that's not the only allowed representation.)
+ * The zero-based index of a List element is the first identifying value,
+ * and the (also zero-based) index of a bit within that Bitmapset is
+ * the second identifying value. There is no expectation that the
+ * Bitmapsets should all be the same size.
+ *
+ * The available operations on multibitmapsets are intended to parallel
+ * those on bitmapsets, for example union and intersection. So far only
+ * a small fraction of that has been built out; we'll add more as needed.
+ *
+ *
+ * Copyright (c) 2022-2023, PostgreSQL Global Development Group
+ *
+ * src/include/nodes/multibitmapset.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MULTIBITMAPSET_H
+#define MULTIBITMAPSET_H
+
+#include "nodes/bitmapset.h"
+#include "nodes/pg_list.h"
+
+extern List *mbms_add_member(List *a, int listidx, int bitidx);
+extern List *mbms_add_members(List *a, const List *b);
+extern List *mbms_int_members(List *a, const List *b);
+extern bool mbms_is_member(int listidx, int bitidx, const List *a);
+extern Bitmapset *mbms_overlap_sets(const List *a, const List *b);
+
+#endif /* MULTIBITMAPSET_H */
diff --git a/pgsql/include/server/nodes/nodeFuncs.h b/pgsql/include/server/nodes/nodeFuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..20921b45b9e1087124743fbb5b48946ba9f70864
--- /dev/null
+++ b/pgsql/include/server/nodes/nodeFuncs.h
@@ -0,0 +1,222 @@
+/*-------------------------------------------------------------------------
+ *
+ * nodeFuncs.h
+ * Various general-purpose manipulations of Node trees
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/nodeFuncs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef NODEFUNCS_H
+#define NODEFUNCS_H
+
+#include "nodes/parsenodes.h"
+
+struct PlanState; /* avoid including execnodes.h too */
+
+
+/* flags bits for query_tree_walker and query_tree_mutator */
+#define QTW_IGNORE_RT_SUBQUERIES 0x01 /* subqueries in rtable */
+#define QTW_IGNORE_CTE_SUBQUERIES 0x02 /* subqueries in cteList */
+#define QTW_IGNORE_RC_SUBQUERIES 0x03 /* both of above */
+#define QTW_IGNORE_JOINALIASES 0x04 /* JOIN alias var lists */
+#define QTW_IGNORE_RANGE_TABLE 0x08 /* skip rangetable entirely */
+#define QTW_EXAMINE_RTES_BEFORE 0x10 /* examine RTE nodes before their
+ * contents */
+#define QTW_EXAMINE_RTES_AFTER 0x20 /* examine RTE nodes after their
+ * contents */
+#define QTW_DONT_COPY_QUERY 0x40 /* do not copy top Query */
+#define QTW_EXAMINE_SORTGROUP 0x80 /* include SortGroupClause lists */
+
+/* callback function for check_functions_in_node */
+typedef bool (*check_function_callback) (Oid func_id, void *context);
+
+/* callback functions for tree walkers */
+typedef bool (*tree_walker_callback) (Node *node, void *context);
+typedef bool (*planstate_tree_walker_callback) (struct PlanState *planstate,
+ void *context);
+
+/* callback functions for tree mutators */
+typedef Node *(*tree_mutator_callback) (Node *node, void *context);
+
+
+extern Oid exprType(const Node *expr);
+extern int32 exprTypmod(const Node *expr);
+extern bool exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod);
+extern Node *applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid,
+ CoercionForm rformat, int rlocation,
+ bool overwrite_ok);
+extern Node *relabel_to_typmod(Node *expr, int32 typmod);
+extern Node *strip_implicit_coercions(Node *node);
+extern bool expression_returns_set(Node *clause);
+
+extern Oid exprCollation(const Node *expr);
+extern Oid exprInputCollation(const Node *expr);
+extern void exprSetCollation(Node *expr, Oid collation);
+extern void exprSetInputCollation(Node *expr, Oid inputcollation);
+
+extern int exprLocation(const Node *expr);
+
+extern void fix_opfuncids(Node *node);
+extern void set_opfuncid(OpExpr *opexpr);
+extern void set_sa_opfuncid(ScalarArrayOpExpr *opexpr);
+
+/* Is clause a FuncExpr clause? */
+static inline bool
+is_funcclause(const void *clause)
+{
+ return clause != NULL && IsA(clause, FuncExpr);
+}
+
+/* Is clause an OpExpr clause? */
+static inline bool
+is_opclause(const void *clause)
+{
+ return clause != NULL && IsA(clause, OpExpr);
+}
+
+/* Extract left arg of a binary opclause, or only arg of a unary opclause */
+static inline Node *
+get_leftop(const void *clause)
+{
+ const OpExpr *expr = (const OpExpr *) clause;
+
+ if (expr->args != NIL)
+ return (Node *) linitial(expr->args);
+ else
+ return NULL;
+}
+
+/* Extract right arg of a binary opclause (NULL if it's a unary opclause) */
+static inline Node *
+get_rightop(const void *clause)
+{
+ const OpExpr *expr = (const OpExpr *) clause;
+
+ if (list_length(expr->args) >= 2)
+ return (Node *) lsecond(expr->args);
+ else
+ return NULL;
+}
+
+/* Is clause an AND clause? */
+static inline bool
+is_andclause(const void *clause)
+{
+ return (clause != NULL &&
+ IsA(clause, BoolExpr) &&
+ ((const BoolExpr *) clause)->boolop == AND_EXPR);
+}
+
+/* Is clause an OR clause? */
+static inline bool
+is_orclause(const void *clause)
+{
+ return (clause != NULL &&
+ IsA(clause, BoolExpr) &&
+ ((const BoolExpr *) clause)->boolop == OR_EXPR);
+}
+
+/* Is clause a NOT clause? */
+static inline bool
+is_notclause(const void *clause)
+{
+ return (clause != NULL &&
+ IsA(clause, BoolExpr) &&
+ ((const BoolExpr *) clause)->boolop == NOT_EXPR);
+}
+
+/* Extract argument from a clause known to be a NOT clause */
+static inline Expr *
+get_notclausearg(const void *notclause)
+{
+ return (Expr *) linitial(((const BoolExpr *) notclause)->args);
+}
+
+extern bool check_functions_in_node(Node *node, check_function_callback checker,
+ void *context);
+
+/*
+ * The following functions are usually passed walker or mutator callbacks
+ * that are declared like "bool walker(Node *node, my_struct *context)"
+ * rather than "bool walker(Node *node, void *context)" as a strict reading
+ * of the C standard would require. Changing the callbacks' declarations
+ * to "void *" would create serious hazards of passing them the wrong context
+ * struct type, so we respectfully decline to support the standard's position
+ * that a pointer to struct is incompatible with "void *". Instead, silence
+ * related compiler warnings by inserting casts into these macro wrappers.
+ */
+
+#define expression_tree_walker(n, w, c) \
+ expression_tree_walker_impl(n, (tree_walker_callback) (w), c)
+#define expression_tree_mutator(n, m, c) \
+ expression_tree_mutator_impl(n, (tree_mutator_callback) (m), c)
+
+#define query_tree_walker(q, w, c, f) \
+ query_tree_walker_impl(q, (tree_walker_callback) (w), c, f)
+#define query_tree_mutator(q, m, c, f) \
+ query_tree_mutator_impl(q, (tree_mutator_callback) (m), c, f)
+
+#define range_table_walker(rt, w, c, f) \
+ range_table_walker_impl(rt, (tree_walker_callback) (w), c, f)
+#define range_table_mutator(rt, m, c, f) \
+ range_table_mutator_impl(rt, (tree_mutator_callback) (m), c, f)
+
+#define range_table_entry_walker(r, w, c, f) \
+ range_table_entry_walker_impl(r, (tree_walker_callback) (w), c, f)
+
+#define query_or_expression_tree_walker(n, w, c, f) \
+ query_or_expression_tree_walker_impl(n, (tree_walker_callback) (w), c, f)
+#define query_or_expression_tree_mutator(n, m, c, f) \
+ query_or_expression_tree_mutator_impl(n, (tree_mutator_callback) (m), c, f)
+
+#define raw_expression_tree_walker(n, w, c) \
+ raw_expression_tree_walker_impl(n, (tree_walker_callback) (w), c)
+
+#define planstate_tree_walker(ps, w, c) \
+ planstate_tree_walker_impl(ps, (planstate_tree_walker_callback) (w), c)
+
+extern bool expression_tree_walker_impl(Node *node,
+ tree_walker_callback walker,
+ void *context);
+extern Node *expression_tree_mutator_impl(Node *node,
+ tree_mutator_callback mutator,
+ void *context);
+
+extern bool query_tree_walker_impl(Query *query,
+ tree_walker_callback walker,
+ void *context, int flags);
+extern Query *query_tree_mutator_impl(Query *query,
+ tree_mutator_callback mutator,
+ void *context, int flags);
+
+extern bool range_table_walker_impl(List *rtable,
+ tree_walker_callback walker,
+ void *context, int flags);
+extern List *range_table_mutator_impl(List *rtable,
+ tree_mutator_callback mutator,
+ void *context, int flags);
+
+extern bool range_table_entry_walker_impl(RangeTblEntry *rte,
+ tree_walker_callback walker,
+ void *context, int flags);
+
+extern bool query_or_expression_tree_walker_impl(Node *node,
+ tree_walker_callback walker,
+ void *context, int flags);
+extern Node *query_or_expression_tree_mutator_impl(Node *node,
+ tree_mutator_callback mutator,
+ void *context, int flags);
+
+extern bool raw_expression_tree_walker_impl(Node *node,
+ tree_walker_callback walker,
+ void *context);
+
+extern bool planstate_tree_walker_impl(struct PlanState *planstate,
+ planstate_tree_walker_callback walker,
+ void *context);
+
+#endif /* NODEFUNCS_H */
diff --git a/pgsql/include/server/nodes/nodes.h b/pgsql/include/server/nodes/nodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..f8e8fe699ab4276d550b54fd0e27428a0c506511
--- /dev/null
+++ b/pgsql/include/server/nodes/nodes.h
@@ -0,0 +1,446 @@
+/*-------------------------------------------------------------------------
+ *
+ * nodes.h
+ * Definitions for tagged nodes.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/nodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef NODES_H
+#define NODES_H
+
+/*
+ * The first field of every node is NodeTag. Each node created (with makeNode)
+ * will have one of the following tags as the value of its first field.
+ *
+ * Note that inserting or deleting node types changes the numbers of other
+ * node types later in the list. This is no problem during development, since
+ * the node numbers are never stored on disk. But don't do it in a released
+ * branch, because that would represent an ABI break for extensions.
+ */
+typedef enum NodeTag
+{
+ T_Invalid = 0,
+
+#include "nodes/nodetags.h"
+} NodeTag;
+
+/*
+ * pg_node_attr() - Used in node definitions to set extra information for
+ * gen_node_support.pl
+ *
+ * Attributes can be attached to a node as a whole (place the attribute
+ * specification on the first line after the struct's opening brace)
+ * or to a specific field (place it at the end of that field's line). The
+ * argument is a comma-separated list of attributes. Unrecognized attributes
+ * cause an error.
+ *
+ * Valid node attributes:
+ *
+ * - abstract: Abstract types are types that cannot be instantiated but that
+ * can be supertypes of other types. We track their fields, so that
+ * subtypes can use them, but we don't emit a node tag, so you can't
+ * instantiate them.
+ *
+ * - custom_copy_equal: Has custom implementations in copyfuncs.c and
+ * equalfuncs.c.
+ *
+ * - custom_read_write: Has custom implementations in outfuncs.c and
+ * readfuncs.c.
+ *
+ * - custom_query_jumble: Has custom implementation in queryjumblefuncs.c.
+ *
+ * - no_copy: Does not support copyObject() at all.
+ *
+ * - no_equal: Does not support equal() at all.
+ *
+ * - no_copy_equal: Shorthand for both no_copy and no_equal.
+ *
+ * - no_query_jumble: Does not support JumbleQuery() at all.
+ *
+ * - no_read: Does not support nodeRead() at all.
+ *
+ * - nodetag_only: Does not support copyObject(), equal(), jumbleQuery()
+ * outNode() or nodeRead().
+ *
+ * - special_read_write: Has special treatment in outNode() and nodeRead().
+ *
+ * - nodetag_number(VALUE): assign the specified nodetag number instead of
+ * an auto-generated number. Typically this would only be used in stable
+ * branches, to give a newly-added node type a number without breaking ABI
+ * by changing the numbers of existing node types.
+ *
+ * Node types can be supertypes of other types whether or not they are marked
+ * abstract: if a node struct appears as the first field of another struct
+ * type, then it is the supertype of that type. The no_copy, no_equal,
+ * no_query_jumble and no_read node attributes are automatically inherited
+ * from the supertype. (Notice that nodetag_only does not inherit, so it's
+ * not quite equivalent to a combination of other attributes.)
+ *
+ * Valid node field attributes:
+ *
+ * - array_size(OTHERFIELD): This field is a dynamically allocated array with
+ * size indicated by the mentioned other field. The other field is either a
+ * scalar or a list, in which case the length of the list is used.
+ *
+ * - copy_as(VALUE): In copyObject(), replace the field's value with VALUE.
+ *
+ * - copy_as_scalar: In copyObject(), copy the field as a scalar value
+ * (e.g. a pointer) even if it is a node-type pointer.
+ *
+ * - equal_as_scalar: In equal(), compare the field as a scalar value
+ * even if it is a node-type pointer.
+ *
+ * - equal_ignore: Ignore the field for equality.
+ *
+ * - equal_ignore_if_zero: Ignore the field for equality if it is zero.
+ * (Otherwise, compare normally.)
+ *
+ * - query_jumble_ignore: Ignore the field for the query jumbling. Note
+ * that typmod and collation information are usually irrelevant for the
+ * query jumbling.
+ *
+ * - query_jumble_location: Mark the field as a location to track. This is
+ * only allowed for integer fields that include "location" in their name.
+ *
+ * - read_as(VALUE): In nodeRead(), replace the field's value with VALUE.
+ *
+ * - read_write_ignore: Ignore the field for read/write. This is only allowed
+ * if the node type is marked no_read or read_as() is also specified.
+ *
+ * - write_only_relids, write_only_nondefault_pathtarget, write_only_req_outer:
+ * Special handling for Path struct; see there.
+ *
+ */
+#define pg_node_attr(...)
+
+/*
+ * The first field of a node of any type is guaranteed to be the NodeTag.
+ * Hence the type of any node can be gotten by casting it to Node. Declaring
+ * a variable to be of Node * (instead of void *) can also facilitate
+ * debugging.
+ */
+typedef struct Node
+{
+ NodeTag type;
+} Node;
+
+#define nodeTag(nodeptr) (((const Node*)(nodeptr))->type)
+
+/*
+ * newNode -
+ * create a new node of the specified size and tag the node with the
+ * specified tag.
+ *
+ * !WARNING!: Avoid using newNode directly. You should be using the
+ * macro makeNode. eg. to create a Query node, use makeNode(Query)
+ *
+ * Note: the size argument should always be a compile-time constant, so the
+ * apparent risk of multiple evaluation doesn't matter in practice.
+ */
+#ifdef __GNUC__
+
+/* With GCC, we can use a compound statement within an expression */
+#define newNode(size, tag) \
+({ Node *_result; \
+ AssertMacro((size) >= sizeof(Node)); /* need the tag, at least */ \
+ _result = (Node *) palloc0fast(size); \
+ _result->type = (tag); \
+ _result; \
+})
+#else
+
+/*
+ * There is no way to dereference the palloc'ed pointer to assign the
+ * tag, and also return the pointer itself, so we need a holder variable.
+ * Fortunately, this macro isn't recursive so we just define
+ * a global variable for this purpose.
+ */
+extern PGDLLIMPORT Node *newNodeMacroHolder;
+
+#define newNode(size, tag) \
+( \
+ AssertMacro((size) >= sizeof(Node)), /* need the tag, at least */ \
+ newNodeMacroHolder = (Node *) palloc0fast(size), \
+ newNodeMacroHolder->type = (tag), \
+ newNodeMacroHolder \
+)
+#endif /* __GNUC__ */
+
+
+#define makeNode(_type_) ((_type_ *) newNode(sizeof(_type_),T_##_type_))
+#define NodeSetTag(nodeptr,t) (((Node*)(nodeptr))->type = (t))
+
+#define IsA(nodeptr,_type_) (nodeTag(nodeptr) == T_##_type_)
+
+/*
+ * castNode(type, ptr) casts ptr to "type *", and if assertions are enabled,
+ * verifies that the node has the appropriate type (using its nodeTag()).
+ *
+ * Use an inline function when assertions are enabled, to avoid multiple
+ * evaluations of the ptr argument (which could e.g. be a function call).
+ */
+#ifdef USE_ASSERT_CHECKING
+static inline Node *
+castNodeImpl(NodeTag type, void *ptr)
+{
+ Assert(ptr == NULL || nodeTag(ptr) == type);
+ return (Node *) ptr;
+}
+#define castNode(_type_, nodeptr) ((_type_ *) castNodeImpl(T_##_type_, nodeptr))
+#else
+#define castNode(_type_, nodeptr) ((_type_ *) (nodeptr))
+#endif /* USE_ASSERT_CHECKING */
+
+
+/* ----------------------------------------------------------------
+ * extern declarations follow
+ * ----------------------------------------------------------------
+ */
+
+/*
+ * nodes/{outfuncs.c,print.c}
+ */
+struct Bitmapset; /* not to include bitmapset.h here */
+struct StringInfoData; /* not to include stringinfo.h here */
+
+extern void outNode(struct StringInfoData *str, const void *obj);
+extern void outToken(struct StringInfoData *str, const char *s);
+extern void outBitmapset(struct StringInfoData *str,
+ const struct Bitmapset *bms);
+extern void outDatum(struct StringInfoData *str, uintptr_t value,
+ int typlen, bool typbyval);
+extern char *nodeToString(const void *obj);
+extern char *bmsToString(const struct Bitmapset *bms);
+
+/*
+ * nodes/{readfuncs.c,read.c}
+ */
+extern void *stringToNode(const char *str);
+#ifdef WRITE_READ_PARSE_PLAN_TREES
+extern void *stringToNodeWithLocations(const char *str);
+#endif
+extern struct Bitmapset *readBitmapset(void);
+extern uintptr_t readDatum(bool typbyval);
+extern bool *readBoolCols(int numCols);
+extern int *readIntCols(int numCols);
+extern Oid *readOidCols(int numCols);
+extern int16 *readAttrNumberCols(int numCols);
+
+/*
+ * nodes/copyfuncs.c
+ */
+extern void *copyObjectImpl(const void *from);
+
+/* cast result back to argument type, if supported by compiler */
+#ifdef HAVE_TYPEOF
+#define copyObject(obj) ((typeof(obj)) copyObjectImpl(obj))
+#else
+#define copyObject(obj) copyObjectImpl(obj)
+#endif
+
+/*
+ * nodes/equalfuncs.c
+ */
+extern bool equal(const void *a, const void *b);
+
+
+/*
+ * Typedefs for identifying qualifier selectivities and plan costs as such.
+ * These are just plain "double"s, but declaring a variable as Selectivity
+ * or Cost makes the intent more obvious.
+ *
+ * These could have gone into plannodes.h or some such, but many files
+ * depend on them...
+ */
+typedef double Selectivity; /* fraction of tuples a qualifier will pass */
+typedef double Cost; /* execution cost (in page-access units) */
+typedef double Cardinality; /* (estimated) number of rows or other integer
+ * count */
+
+
+/*
+ * CmdType -
+ * enums for type of operation represented by a Query or PlannedStmt
+ *
+ * This is needed in both parsenodes.h and plannodes.h, so put it here...
+ */
+typedef enum CmdType
+{
+ CMD_UNKNOWN,
+ CMD_SELECT, /* select stmt */
+ CMD_UPDATE, /* update stmt */
+ CMD_INSERT, /* insert stmt */
+ CMD_DELETE, /* delete stmt */
+ CMD_MERGE, /* merge stmt */
+ CMD_UTILITY, /* cmds like create, destroy, copy, vacuum,
+ * etc. */
+ CMD_NOTHING /* dummy command for instead nothing rules
+ * with qual */
+} CmdType;
+
+
+/*
+ * JoinType -
+ * enums for types of relation joins
+ *
+ * JoinType determines the exact semantics of joining two relations using
+ * a matching qualification. For example, it tells what to do with a tuple
+ * that has no match in the other relation.
+ *
+ * This is needed in both parsenodes.h and plannodes.h, so put it here...
+ */
+typedef enum JoinType
+{
+ /*
+ * The canonical kinds of joins according to the SQL JOIN syntax. Only
+ * these codes can appear in parser output (e.g., JoinExpr nodes).
+ */
+ JOIN_INNER, /* matching tuple pairs only */
+ JOIN_LEFT, /* pairs + unmatched LHS tuples */
+ JOIN_FULL, /* pairs + unmatched LHS + unmatched RHS */
+ JOIN_RIGHT, /* pairs + unmatched RHS tuples */
+
+ /*
+ * Semijoins and anti-semijoins (as defined in relational theory) do not
+ * appear in the SQL JOIN syntax, but there are standard idioms for
+ * representing them (e.g., using EXISTS). The planner recognizes these
+ * cases and converts them to joins. So the planner and executor must
+ * support these codes. NOTE: in JOIN_SEMI output, it is unspecified
+ * which matching RHS row is joined to. In JOIN_ANTI output, the row is
+ * guaranteed to be null-extended.
+ */
+ JOIN_SEMI, /* 1 copy of each LHS row that has match(es) */
+ JOIN_ANTI, /* 1 copy of each LHS row that has no match */
+ JOIN_RIGHT_ANTI, /* 1 copy of each RHS row that has no match */
+
+ /*
+ * These codes are used internally in the planner, but are not supported
+ * by the executor (nor, indeed, by most of the planner).
+ */
+ JOIN_UNIQUE_OUTER, /* LHS path must be made unique */
+ JOIN_UNIQUE_INNER /* RHS path must be made unique */
+
+ /*
+ * We might need additional join types someday.
+ */
+} JoinType;
+
+/*
+ * OUTER joins are those for which pushed-down quals must behave differently
+ * from the join's own quals. This is in fact everything except INNER and
+ * SEMI joins. However, this macro must also exclude the JOIN_UNIQUE symbols
+ * since those are temporary proxies for what will eventually be an INNER
+ * join.
+ *
+ * Note: semijoins are a hybrid case, but we choose to treat them as not
+ * being outer joins. This is okay principally because the SQL syntax makes
+ * it impossible to have a pushed-down qual that refers to the inner relation
+ * of a semijoin; so there is no strong need to distinguish join quals from
+ * pushed-down quals. This is convenient because for almost all purposes,
+ * quals attached to a semijoin can be treated the same as innerjoin quals.
+ */
+#define IS_OUTER_JOIN(jointype) \
+ (((1 << (jointype)) & \
+ ((1 << JOIN_LEFT) | \
+ (1 << JOIN_FULL) | \
+ (1 << JOIN_RIGHT) | \
+ (1 << JOIN_ANTI) | \
+ (1 << JOIN_RIGHT_ANTI))) != 0)
+
+/*
+ * AggStrategy -
+ * overall execution strategies for Agg plan nodes
+ *
+ * This is needed in both pathnodes.h and plannodes.h, so put it here...
+ */
+typedef enum AggStrategy
+{
+ AGG_PLAIN, /* simple agg across all input rows */
+ AGG_SORTED, /* grouped agg, input must be sorted */
+ AGG_HASHED, /* grouped agg, use internal hashtable */
+ AGG_MIXED /* grouped agg, hash and sort both used */
+} AggStrategy;
+
+/*
+ * AggSplit -
+ * splitting (partial aggregation) modes for Agg plan nodes
+ *
+ * This is needed in both pathnodes.h and plannodes.h, so put it here...
+ */
+
+/* Primitive options supported by nodeAgg.c: */
+#define AGGSPLITOP_COMBINE 0x01 /* substitute combinefn for transfn */
+#define AGGSPLITOP_SKIPFINAL 0x02 /* skip finalfn, return state as-is */
+#define AGGSPLITOP_SERIALIZE 0x04 /* apply serialfn to output */
+#define AGGSPLITOP_DESERIALIZE 0x08 /* apply deserialfn to input */
+
+/* Supported operating modes (i.e., useful combinations of these options): */
+typedef enum AggSplit
+{
+ /* Basic, non-split aggregation: */
+ AGGSPLIT_SIMPLE = 0,
+ /* Initial phase of partial aggregation, with serialization: */
+ AGGSPLIT_INITIAL_SERIAL = AGGSPLITOP_SKIPFINAL | AGGSPLITOP_SERIALIZE,
+ /* Final phase of partial aggregation, with deserialization: */
+ AGGSPLIT_FINAL_DESERIAL = AGGSPLITOP_COMBINE | AGGSPLITOP_DESERIALIZE
+} AggSplit;
+
+/* Test whether an AggSplit value selects each primitive option: */
+#define DO_AGGSPLIT_COMBINE(as) (((as) & AGGSPLITOP_COMBINE) != 0)
+#define DO_AGGSPLIT_SKIPFINAL(as) (((as) & AGGSPLITOP_SKIPFINAL) != 0)
+#define DO_AGGSPLIT_SERIALIZE(as) (((as) & AGGSPLITOP_SERIALIZE) != 0)
+#define DO_AGGSPLIT_DESERIALIZE(as) (((as) & AGGSPLITOP_DESERIALIZE) != 0)
+
+/*
+ * SetOpCmd and SetOpStrategy -
+ * overall semantics and execution strategies for SetOp plan nodes
+ *
+ * This is needed in both pathnodes.h and plannodes.h, so put it here...
+ */
+typedef enum SetOpCmd
+{
+ SETOPCMD_INTERSECT,
+ SETOPCMD_INTERSECT_ALL,
+ SETOPCMD_EXCEPT,
+ SETOPCMD_EXCEPT_ALL
+} SetOpCmd;
+
+typedef enum SetOpStrategy
+{
+ SETOP_SORTED, /* input must be sorted */
+ SETOP_HASHED /* use internal hashtable */
+} SetOpStrategy;
+
+/*
+ * OnConflictAction -
+ * "ON CONFLICT" clause type of query
+ *
+ * This is needed in both parsenodes.h and plannodes.h, so put it here...
+ */
+typedef enum OnConflictAction
+{
+ ONCONFLICT_NONE, /* No "ON CONFLICT" clause */
+ ONCONFLICT_NOTHING, /* ON CONFLICT ... DO NOTHING */
+ ONCONFLICT_UPDATE /* ON CONFLICT ... DO UPDATE */
+} OnConflictAction;
+
+/*
+ * LimitOption -
+ * LIMIT option of query
+ *
+ * This is needed in both parsenodes.h and plannodes.h, so put it here...
+ */
+typedef enum LimitOption
+{
+ LIMIT_OPTION_COUNT, /* FETCH FIRST... ONLY */
+ LIMIT_OPTION_WITH_TIES, /* FETCH FIRST... WITH TIES */
+ LIMIT_OPTION_DEFAULT, /* No limit present */
+} LimitOption;
+
+#endif /* NODES_H */
diff --git a/pgsql/include/server/nodes/nodetags.h b/pgsql/include/server/nodes/nodetags.h
new file mode 100644
index 0000000000000000000000000000000000000000..7fa798ffc7409554530dba64a1a1c5fdba13824f
--- /dev/null
+++ b/pgsql/include/server/nodes/nodetags.h
@@ -0,0 +1,471 @@
+/*-------------------------------------------------------------------------
+ *
+ * nodetags.h
+ * Generated node infrastructure code
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES
+ * ******************************
+ * *** DO NOT EDIT THIS FILE! ***
+ * ******************************
+ *
+ * It has been GENERATED by src/backend/nodes/gen_node_support.pl
+ *
+ *-------------------------------------------------------------------------
+ */
+ T_List = 1,
+ T_Alias = 2,
+ T_RangeVar = 3,
+ T_TableFunc = 4,
+ T_IntoClause = 5,
+ T_Var = 6,
+ T_Const = 7,
+ T_Param = 8,
+ T_Aggref = 9,
+ T_GroupingFunc = 10,
+ T_WindowFunc = 11,
+ T_SubscriptingRef = 12,
+ T_FuncExpr = 13,
+ T_NamedArgExpr = 14,
+ T_OpExpr = 15,
+ T_DistinctExpr = 16,
+ T_NullIfExpr = 17,
+ T_ScalarArrayOpExpr = 18,
+ T_BoolExpr = 19,
+ T_SubLink = 20,
+ T_SubPlan = 21,
+ T_AlternativeSubPlan = 22,
+ T_FieldSelect = 23,
+ T_FieldStore = 24,
+ T_RelabelType = 25,
+ T_CoerceViaIO = 26,
+ T_ArrayCoerceExpr = 27,
+ T_ConvertRowtypeExpr = 28,
+ T_CollateExpr = 29,
+ T_CaseExpr = 30,
+ T_CaseWhen = 31,
+ T_CaseTestExpr = 32,
+ T_ArrayExpr = 33,
+ T_RowExpr = 34,
+ T_RowCompareExpr = 35,
+ T_CoalesceExpr = 36,
+ T_MinMaxExpr = 37,
+ T_SQLValueFunction = 38,
+ T_XmlExpr = 39,
+ T_JsonFormat = 40,
+ T_JsonReturning = 41,
+ T_JsonValueExpr = 42,
+ T_JsonConstructorExpr = 43,
+ T_JsonIsPredicate = 44,
+ T_NullTest = 45,
+ T_BooleanTest = 46,
+ T_CoerceToDomain = 47,
+ T_CoerceToDomainValue = 48,
+ T_SetToDefault = 49,
+ T_CurrentOfExpr = 50,
+ T_NextValueExpr = 51,
+ T_InferenceElem = 52,
+ T_TargetEntry = 53,
+ T_RangeTblRef = 54,
+ T_JoinExpr = 55,
+ T_FromExpr = 56,
+ T_OnConflictExpr = 57,
+ T_Query = 58,
+ T_TypeName = 59,
+ T_ColumnRef = 60,
+ T_ParamRef = 61,
+ T_A_Expr = 62,
+ T_A_Const = 63,
+ T_TypeCast = 64,
+ T_CollateClause = 65,
+ T_RoleSpec = 66,
+ T_FuncCall = 67,
+ T_A_Star = 68,
+ T_A_Indices = 69,
+ T_A_Indirection = 70,
+ T_A_ArrayExpr = 71,
+ T_ResTarget = 72,
+ T_MultiAssignRef = 73,
+ T_SortBy = 74,
+ T_WindowDef = 75,
+ T_RangeSubselect = 76,
+ T_RangeFunction = 77,
+ T_RangeTableFunc = 78,
+ T_RangeTableFuncCol = 79,
+ T_RangeTableSample = 80,
+ T_ColumnDef = 81,
+ T_TableLikeClause = 82,
+ T_IndexElem = 83,
+ T_DefElem = 84,
+ T_LockingClause = 85,
+ T_XmlSerialize = 86,
+ T_PartitionElem = 87,
+ T_PartitionSpec = 88,
+ T_PartitionBoundSpec = 89,
+ T_PartitionRangeDatum = 90,
+ T_PartitionCmd = 91,
+ T_RangeTblEntry = 92,
+ T_RTEPermissionInfo = 93,
+ T_RangeTblFunction = 94,
+ T_TableSampleClause = 95,
+ T_WithCheckOption = 96,
+ T_SortGroupClause = 97,
+ T_GroupingSet = 98,
+ T_WindowClause = 99,
+ T_RowMarkClause = 100,
+ T_WithClause = 101,
+ T_InferClause = 102,
+ T_OnConflictClause = 103,
+ T_CTESearchClause = 104,
+ T_CTECycleClause = 105,
+ T_CommonTableExpr = 106,
+ T_MergeWhenClause = 107,
+ T_MergeAction = 108,
+ T_TriggerTransition = 109,
+ T_JsonOutput = 110,
+ T_JsonKeyValue = 111,
+ T_JsonObjectConstructor = 112,
+ T_JsonArrayConstructor = 113,
+ T_JsonArrayQueryConstructor = 114,
+ T_JsonAggConstructor = 115,
+ T_JsonObjectAgg = 116,
+ T_JsonArrayAgg = 117,
+ T_RawStmt = 118,
+ T_InsertStmt = 119,
+ T_DeleteStmt = 120,
+ T_UpdateStmt = 121,
+ T_MergeStmt = 122,
+ T_SelectStmt = 123,
+ T_SetOperationStmt = 124,
+ T_ReturnStmt = 125,
+ T_PLAssignStmt = 126,
+ T_CreateSchemaStmt = 127,
+ T_AlterTableStmt = 128,
+ T_ReplicaIdentityStmt = 129,
+ T_AlterTableCmd = 130,
+ T_AlterCollationStmt = 131,
+ T_AlterDomainStmt = 132,
+ T_GrantStmt = 133,
+ T_ObjectWithArgs = 134,
+ T_AccessPriv = 135,
+ T_GrantRoleStmt = 136,
+ T_AlterDefaultPrivilegesStmt = 137,
+ T_CopyStmt = 138,
+ T_VariableSetStmt = 139,
+ T_VariableShowStmt = 140,
+ T_CreateStmt = 141,
+ T_Constraint = 142,
+ T_CreateTableSpaceStmt = 143,
+ T_DropTableSpaceStmt = 144,
+ T_AlterTableSpaceOptionsStmt = 145,
+ T_AlterTableMoveAllStmt = 146,
+ T_CreateExtensionStmt = 147,
+ T_AlterExtensionStmt = 148,
+ T_AlterExtensionContentsStmt = 149,
+ T_CreateFdwStmt = 150,
+ T_AlterFdwStmt = 151,
+ T_CreateForeignServerStmt = 152,
+ T_AlterForeignServerStmt = 153,
+ T_CreateForeignTableStmt = 154,
+ T_CreateUserMappingStmt = 155,
+ T_AlterUserMappingStmt = 156,
+ T_DropUserMappingStmt = 157,
+ T_ImportForeignSchemaStmt = 158,
+ T_CreatePolicyStmt = 159,
+ T_AlterPolicyStmt = 160,
+ T_CreateAmStmt = 161,
+ T_CreateTrigStmt = 162,
+ T_CreateEventTrigStmt = 163,
+ T_AlterEventTrigStmt = 164,
+ T_CreatePLangStmt = 165,
+ T_CreateRoleStmt = 166,
+ T_AlterRoleStmt = 167,
+ T_AlterRoleSetStmt = 168,
+ T_DropRoleStmt = 169,
+ T_CreateSeqStmt = 170,
+ T_AlterSeqStmt = 171,
+ T_DefineStmt = 172,
+ T_CreateDomainStmt = 173,
+ T_CreateOpClassStmt = 174,
+ T_CreateOpClassItem = 175,
+ T_CreateOpFamilyStmt = 176,
+ T_AlterOpFamilyStmt = 177,
+ T_DropStmt = 178,
+ T_TruncateStmt = 179,
+ T_CommentStmt = 180,
+ T_SecLabelStmt = 181,
+ T_DeclareCursorStmt = 182,
+ T_ClosePortalStmt = 183,
+ T_FetchStmt = 184,
+ T_IndexStmt = 185,
+ T_CreateStatsStmt = 186,
+ T_StatsElem = 187,
+ T_AlterStatsStmt = 188,
+ T_CreateFunctionStmt = 189,
+ T_FunctionParameter = 190,
+ T_AlterFunctionStmt = 191,
+ T_DoStmt = 192,
+ T_InlineCodeBlock = 193,
+ T_CallStmt = 194,
+ T_CallContext = 195,
+ T_RenameStmt = 196,
+ T_AlterObjectDependsStmt = 197,
+ T_AlterObjectSchemaStmt = 198,
+ T_AlterOwnerStmt = 199,
+ T_AlterOperatorStmt = 200,
+ T_AlterTypeStmt = 201,
+ T_RuleStmt = 202,
+ T_NotifyStmt = 203,
+ T_ListenStmt = 204,
+ T_UnlistenStmt = 205,
+ T_TransactionStmt = 206,
+ T_CompositeTypeStmt = 207,
+ T_CreateEnumStmt = 208,
+ T_CreateRangeStmt = 209,
+ T_AlterEnumStmt = 210,
+ T_ViewStmt = 211,
+ T_LoadStmt = 212,
+ T_CreatedbStmt = 213,
+ T_AlterDatabaseStmt = 214,
+ T_AlterDatabaseRefreshCollStmt = 215,
+ T_AlterDatabaseSetStmt = 216,
+ T_DropdbStmt = 217,
+ T_AlterSystemStmt = 218,
+ T_ClusterStmt = 219,
+ T_VacuumStmt = 220,
+ T_VacuumRelation = 221,
+ T_ExplainStmt = 222,
+ T_CreateTableAsStmt = 223,
+ T_RefreshMatViewStmt = 224,
+ T_CheckPointStmt = 225,
+ T_DiscardStmt = 226,
+ T_LockStmt = 227,
+ T_ConstraintsSetStmt = 228,
+ T_ReindexStmt = 229,
+ T_CreateConversionStmt = 230,
+ T_CreateCastStmt = 231,
+ T_CreateTransformStmt = 232,
+ T_PrepareStmt = 233,
+ T_ExecuteStmt = 234,
+ T_DeallocateStmt = 235,
+ T_DropOwnedStmt = 236,
+ T_ReassignOwnedStmt = 237,
+ T_AlterTSDictionaryStmt = 238,
+ T_AlterTSConfigurationStmt = 239,
+ T_PublicationTable = 240,
+ T_PublicationObjSpec = 241,
+ T_CreatePublicationStmt = 242,
+ T_AlterPublicationStmt = 243,
+ T_CreateSubscriptionStmt = 244,
+ T_AlterSubscriptionStmt = 245,
+ T_DropSubscriptionStmt = 246,
+ T_PlannerGlobal = 247,
+ T_PlannerInfo = 248,
+ T_RelOptInfo = 249,
+ T_IndexOptInfo = 250,
+ T_ForeignKeyOptInfo = 251,
+ T_StatisticExtInfo = 252,
+ T_JoinDomain = 253,
+ T_EquivalenceClass = 254,
+ T_EquivalenceMember = 255,
+ T_PathKey = 256,
+ T_PathTarget = 257,
+ T_ParamPathInfo = 258,
+ T_Path = 259,
+ T_IndexPath = 260,
+ T_IndexClause = 261,
+ T_BitmapHeapPath = 262,
+ T_BitmapAndPath = 263,
+ T_BitmapOrPath = 264,
+ T_TidPath = 265,
+ T_TidRangePath = 266,
+ T_SubqueryScanPath = 267,
+ T_ForeignPath = 268,
+ T_CustomPath = 269,
+ T_AppendPath = 270,
+ T_MergeAppendPath = 271,
+ T_GroupResultPath = 272,
+ T_MaterialPath = 273,
+ T_MemoizePath = 274,
+ T_UniquePath = 275,
+ T_GatherPath = 276,
+ T_GatherMergePath = 277,
+ T_NestPath = 278,
+ T_MergePath = 279,
+ T_HashPath = 280,
+ T_ProjectionPath = 281,
+ T_ProjectSetPath = 282,
+ T_SortPath = 283,
+ T_IncrementalSortPath = 284,
+ T_GroupPath = 285,
+ T_UpperUniquePath = 286,
+ T_AggPath = 287,
+ T_GroupingSetData = 288,
+ T_RollupData = 289,
+ T_GroupingSetsPath = 290,
+ T_MinMaxAggPath = 291,
+ T_WindowAggPath = 292,
+ T_SetOpPath = 293,
+ T_RecursiveUnionPath = 294,
+ T_LockRowsPath = 295,
+ T_ModifyTablePath = 296,
+ T_LimitPath = 297,
+ T_RestrictInfo = 298,
+ T_PlaceHolderVar = 299,
+ T_SpecialJoinInfo = 300,
+ T_OuterJoinClauseInfo = 301,
+ T_AppendRelInfo = 302,
+ T_RowIdentityVarInfo = 303,
+ T_PlaceHolderInfo = 304,
+ T_MinMaxAggInfo = 305,
+ T_PlannerParamItem = 306,
+ T_AggInfo = 307,
+ T_AggTransInfo = 308,
+ T_PlannedStmt = 309,
+ T_Result = 310,
+ T_ProjectSet = 311,
+ T_ModifyTable = 312,
+ T_Append = 313,
+ T_MergeAppend = 314,
+ T_RecursiveUnion = 315,
+ T_BitmapAnd = 316,
+ T_BitmapOr = 317,
+ T_SeqScan = 318,
+ T_SampleScan = 319,
+ T_IndexScan = 320,
+ T_IndexOnlyScan = 321,
+ T_BitmapIndexScan = 322,
+ T_BitmapHeapScan = 323,
+ T_TidScan = 324,
+ T_TidRangeScan = 325,
+ T_SubqueryScan = 326,
+ T_FunctionScan = 327,
+ T_ValuesScan = 328,
+ T_TableFuncScan = 329,
+ T_CteScan = 330,
+ T_NamedTuplestoreScan = 331,
+ T_WorkTableScan = 332,
+ T_ForeignScan = 333,
+ T_CustomScan = 334,
+ T_NestLoop = 335,
+ T_NestLoopParam = 336,
+ T_MergeJoin = 337,
+ T_HashJoin = 338,
+ T_Material = 339,
+ T_Memoize = 340,
+ T_Sort = 341,
+ T_IncrementalSort = 342,
+ T_Group = 343,
+ T_Agg = 344,
+ T_WindowAgg = 345,
+ T_Unique = 346,
+ T_Gather = 347,
+ T_GatherMerge = 348,
+ T_Hash = 349,
+ T_SetOp = 350,
+ T_LockRows = 351,
+ T_Limit = 352,
+ T_PlanRowMark = 353,
+ T_PartitionPruneInfo = 354,
+ T_PartitionedRelPruneInfo = 355,
+ T_PartitionPruneStepOp = 356,
+ T_PartitionPruneStepCombine = 357,
+ T_PlanInvalItem = 358,
+ T_ExprState = 359,
+ T_IndexInfo = 360,
+ T_ExprContext = 361,
+ T_ReturnSetInfo = 362,
+ T_ProjectionInfo = 363,
+ T_JunkFilter = 364,
+ T_OnConflictSetState = 365,
+ T_MergeActionState = 366,
+ T_ResultRelInfo = 367,
+ T_EState = 368,
+ T_WindowFuncExprState = 369,
+ T_SetExprState = 370,
+ T_SubPlanState = 371,
+ T_DomainConstraintState = 372,
+ T_ResultState = 373,
+ T_ProjectSetState = 374,
+ T_ModifyTableState = 375,
+ T_AppendState = 376,
+ T_MergeAppendState = 377,
+ T_RecursiveUnionState = 378,
+ T_BitmapAndState = 379,
+ T_BitmapOrState = 380,
+ T_ScanState = 381,
+ T_SeqScanState = 382,
+ T_SampleScanState = 383,
+ T_IndexScanState = 384,
+ T_IndexOnlyScanState = 385,
+ T_BitmapIndexScanState = 386,
+ T_BitmapHeapScanState = 387,
+ T_TidScanState = 388,
+ T_TidRangeScanState = 389,
+ T_SubqueryScanState = 390,
+ T_FunctionScanState = 391,
+ T_ValuesScanState = 392,
+ T_TableFuncScanState = 393,
+ T_CteScanState = 394,
+ T_NamedTuplestoreScanState = 395,
+ T_WorkTableScanState = 396,
+ T_ForeignScanState = 397,
+ T_CustomScanState = 398,
+ T_JoinState = 399,
+ T_NestLoopState = 400,
+ T_MergeJoinState = 401,
+ T_HashJoinState = 402,
+ T_MaterialState = 403,
+ T_MemoizeState = 404,
+ T_SortState = 405,
+ T_IncrementalSortState = 406,
+ T_GroupState = 407,
+ T_AggState = 408,
+ T_WindowAggState = 409,
+ T_UniqueState = 410,
+ T_GatherState = 411,
+ T_GatherMergeState = 412,
+ T_HashState = 413,
+ T_SetOpState = 414,
+ T_LockRowsState = 415,
+ T_LimitState = 416,
+ T_IndexAmRoutine = 417,
+ T_TableAmRoutine = 418,
+ T_TsmRoutine = 419,
+ T_EventTriggerData = 420,
+ T_TriggerData = 421,
+ T_TupleTableSlot = 422,
+ T_FdwRoutine = 423,
+ T_Bitmapset = 424,
+ T_ExtensibleNode = 425,
+ T_ErrorSaveContext = 426,
+ T_IdentifySystemCmd = 427,
+ T_BaseBackupCmd = 428,
+ T_CreateReplicationSlotCmd = 429,
+ T_DropReplicationSlotCmd = 430,
+ T_StartReplicationCmd = 431,
+ T_ReadReplicationSlotCmd = 432,
+ T_TimeLineHistoryCmd = 433,
+ T_SupportRequestSimplify = 434,
+ T_SupportRequestSelectivity = 435,
+ T_SupportRequestCost = 436,
+ T_SupportRequestRows = 437,
+ T_SupportRequestIndexCondition = 438,
+ T_SupportRequestWFuncMonotonic = 439,
+ T_SupportRequestOptimizeWindowClause = 440,
+ T_Integer = 441,
+ T_Float = 442,
+ T_Boolean = 443,
+ T_String = 444,
+ T_BitString = 445,
+ T_ForeignKeyCacheInfo = 446,
+ T_IntList = 447,
+ T_OidList = 448,
+ T_XidList = 449,
+ T_AllocSetContext = 450,
+ T_GenerationContext = 451,
+ T_SlabContext = 452,
+ T_TIDBitmap = 453,
+ T_WindowObjectData = 454,
diff --git a/pgsql/include/server/nodes/params.h b/pgsql/include/server/nodes/params.h
new file mode 100644
index 0000000000000000000000000000000000000000..ad23113a61cfa16b2955686d233bff8ea23b1c8d
--- /dev/null
+++ b/pgsql/include/server/nodes/params.h
@@ -0,0 +1,170 @@
+/*-------------------------------------------------------------------------
+ *
+ * params.h
+ * Support for finding the values associated with Param nodes.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/params.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARAMS_H
+#define PARAMS_H
+
+/* Forward declarations, to avoid including other headers */
+struct Bitmapset;
+struct ExprState;
+struct Param;
+struct ParseState;
+
+
+/*
+ * ParamListInfo
+ *
+ * ParamListInfo structures are used to pass parameters into the executor
+ * for parameterized plans. We support two basic approaches to supplying
+ * parameter values, the "static" way and the "dynamic" way.
+ *
+ * In the static approach, per-parameter data is stored in an array of
+ * ParamExternData structs appended to the ParamListInfo struct.
+ * Each entry in the array defines the value to be substituted for a
+ * PARAM_EXTERN parameter. The "paramid" of a PARAM_EXTERN Param
+ * can range from 1 to numParams.
+ *
+ * Although parameter numbers are normally consecutive, we allow
+ * ptype == InvalidOid to signal an unused array entry.
+ *
+ * pflags is a flags field. Currently the only used bit is:
+ * PARAM_FLAG_CONST signals the planner that it may treat this parameter
+ * as a constant (i.e., generate a plan that works only for this value
+ * of the parameter).
+ *
+ * In the dynamic approach, all access to parameter values is done through
+ * hook functions found in the ParamListInfo struct. In this case,
+ * the ParamExternData array is typically unused and not allocated;
+ * but the legal range of paramid is still 1 to numParams.
+ *
+ * Although the data structure is really an array, not a list, we keep
+ * the old typedef name to avoid unnecessary code changes.
+ *
+ * There are 3 hook functions that can be associated with a ParamListInfo
+ * structure:
+ *
+ * If paramFetch isn't null, it is called to fetch the ParamExternData
+ * for a particular param ID, rather than accessing the relevant element
+ * of the ParamExternData array. This supports the case where the array
+ * isn't there at all, as well as cases where the data in the array
+ * might be obsolete or lazily evaluated. paramFetch must return the
+ * address of a ParamExternData struct describing the specified param ID;
+ * the convention above about ptype == InvalidOid signaling an invalid
+ * param ID still applies. The returned struct can either be placed in
+ * the "workspace" supplied by the caller, or it can be in storage
+ * controlled by the paramFetch hook if that's more convenient.
+ * (In either case, the struct is not expected to be long-lived.)
+ * If "speculative" is true, the paramFetch hook should not risk errors
+ * in trying to fetch the parameter value, and should report an invalid
+ * parameter instead.
+ *
+ * If paramCompile isn't null, then it controls what execExpr.c compiles
+ * for PARAM_EXTERN Param nodes --- typically, this hook would emit a
+ * EEOP_PARAM_CALLBACK step. This allows unnecessary work to be
+ * optimized away in compiled expressions.
+ *
+ * If parserSetup isn't null, then it is called to re-instantiate the
+ * original parsing hooks when a query needs to be re-parsed/planned.
+ * This is especially useful if the types of parameters might change
+ * from time to time, since it can replace the need to supply a fixed
+ * list of parameter types to the parser.
+ *
+ * Notice that the paramFetch and paramCompile hooks are actually passed
+ * the ParamListInfo struct's address; they can therefore access all
+ * three of the "arg" fields, and the distinction between paramFetchArg
+ * and paramCompileArg is rather arbitrary.
+ */
+
+#define PARAM_FLAG_CONST 0x0001 /* parameter is constant */
+
+typedef struct ParamExternData
+{
+ Datum value; /* parameter value */
+ bool isnull; /* is it NULL? */
+ uint16 pflags; /* flag bits, see above */
+ Oid ptype; /* parameter's datatype, or 0 */
+} ParamExternData;
+
+typedef struct ParamListInfoData *ParamListInfo;
+
+typedef ParamExternData *(*ParamFetchHook) (ParamListInfo params,
+ int paramid, bool speculative,
+ ParamExternData *workspace);
+
+typedef void (*ParamCompileHook) (ParamListInfo params, struct Param *param,
+ struct ExprState *state,
+ Datum *resv, bool *resnull);
+
+typedef void (*ParserSetupHook) (struct ParseState *pstate, void *arg);
+
+typedef struct ParamListInfoData
+{
+ ParamFetchHook paramFetch; /* parameter fetch hook */
+ void *paramFetchArg;
+ ParamCompileHook paramCompile; /* parameter compile hook */
+ void *paramCompileArg;
+ ParserSetupHook parserSetup; /* parser setup hook */
+ void *parserSetupArg;
+ char *paramValuesStr; /* params as a single string for errors */
+ int numParams; /* nominal/maximum # of Params represented */
+
+ /*
+ * params[] may be of length zero if paramFetch is supplied; otherwise it
+ * must be of length numParams.
+ */
+ ParamExternData params[FLEXIBLE_ARRAY_MEMBER];
+} ParamListInfoData;
+
+
+/* ----------------
+ * ParamExecData
+ *
+ * ParamExecData entries are used for executor internal parameters
+ * (that is, values being passed into or out of a sub-query). The
+ * paramid of a PARAM_EXEC Param is a (zero-based) index into an
+ * array of ParamExecData records, which is referenced through
+ * es_param_exec_vals or ecxt_param_exec_vals.
+ *
+ * If execPlan is not NULL, it points to a SubPlanState node that needs
+ * to be executed to produce the value. (This is done so that we can have
+ * lazy evaluation of InitPlans: they aren't executed until/unless a
+ * result value is needed.) Otherwise the value is assumed to be valid
+ * when needed.
+ * ----------------
+ */
+
+typedef struct ParamExecData
+{
+ void *execPlan; /* should be "SubPlanState *" */
+ Datum value;
+ bool isnull;
+} ParamExecData;
+
+/* type of argument for ParamsErrorCallback */
+typedef struct ParamsErrorCbData
+{
+ const char *portalName;
+ ParamListInfo params;
+} ParamsErrorCbData;
+
+/* Functions found in src/backend/nodes/params.c */
+extern ParamListInfo makeParamList(int numParams);
+extern ParamListInfo copyParamList(ParamListInfo from);
+extern Size EstimateParamListSpace(ParamListInfo paramLI);
+extern void SerializeParamList(ParamListInfo paramLI, char **start_address);
+extern ParamListInfo RestoreParamList(char **start_address);
+extern char *BuildParamLogString(ParamListInfo params, char **knownTextValues,
+ int maxlen);
+extern void ParamsErrorCallback(void *arg);
+
+#endif /* PARAMS_H */
diff --git a/pgsql/include/server/nodes/parsenodes.h b/pgsql/include/server/nodes/parsenodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..9dca3b652874ae4f0e69e8dae2d4907353e030e0
--- /dev/null
+++ b/pgsql/include/server/nodes/parsenodes.h
@@ -0,0 +1,4050 @@
+/*-------------------------------------------------------------------------
+ *
+ * parsenodes.h
+ * definitions for parse tree nodes
+ *
+ * Many of the node types used in parsetrees include a "location" field.
+ * This is a byte (not character) offset in the original source text, to be
+ * used for positioning an error cursor when there is an error related to
+ * the node. Access to the original source text is needed to make use of
+ * the location. At the topmost (statement) level, we also provide a
+ * statement length, likewise measured in bytes, for convenience in
+ * identifying statement boundaries in multi-statement source strings.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/parsenodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSENODES_H
+#define PARSENODES_H
+
+#include "common/relpath.h"
+#include "nodes/bitmapset.h"
+#include "nodes/lockoptions.h"
+#include "nodes/primnodes.h"
+#include "nodes/value.h"
+#include "partitioning/partdefs.h"
+
+
+typedef enum OverridingKind
+{
+ OVERRIDING_NOT_SET = 0,
+ OVERRIDING_USER_VALUE,
+ OVERRIDING_SYSTEM_VALUE
+} OverridingKind;
+
+/* Possible sources of a Query */
+typedef enum QuerySource
+{
+ QSRC_ORIGINAL, /* original parsetree (explicit query) */
+ QSRC_PARSER, /* added by parse analysis (now unused) */
+ QSRC_INSTEAD_RULE, /* added by unconditional INSTEAD rule */
+ QSRC_QUAL_INSTEAD_RULE, /* added by conditional INSTEAD rule */
+ QSRC_NON_INSTEAD_RULE /* added by non-INSTEAD rule */
+} QuerySource;
+
+/* Sort ordering options for ORDER BY and CREATE INDEX */
+typedef enum SortByDir
+{
+ SORTBY_DEFAULT,
+ SORTBY_ASC,
+ SORTBY_DESC,
+ SORTBY_USING /* not allowed in CREATE INDEX ... */
+} SortByDir;
+
+typedef enum SortByNulls
+{
+ SORTBY_NULLS_DEFAULT,
+ SORTBY_NULLS_FIRST,
+ SORTBY_NULLS_LAST
+} SortByNulls;
+
+/* Options for [ ALL | DISTINCT ] */
+typedef enum SetQuantifier
+{
+ SET_QUANTIFIER_DEFAULT,
+ SET_QUANTIFIER_ALL,
+ SET_QUANTIFIER_DISTINCT
+} SetQuantifier;
+
+/*
+ * Grantable rights are encoded so that we can OR them together in a bitmask.
+ * The present representation of AclItem limits us to 32 distinct rights,
+ * even though AclMode is defined as uint64. See utils/acl.h.
+ *
+ * Caution: changing these codes breaks stored ACLs, hence forces initdb.
+ */
+typedef uint64 AclMode; /* a bitmask of privilege bits */
+
+#define ACL_INSERT (1<<0) /* for relations */
+#define ACL_SELECT (1<<1)
+#define ACL_UPDATE (1<<2)
+#define ACL_DELETE (1<<3)
+#define ACL_TRUNCATE (1<<4)
+#define ACL_REFERENCES (1<<5)
+#define ACL_TRIGGER (1<<6)
+#define ACL_EXECUTE (1<<7) /* for functions */
+#define ACL_USAGE (1<<8) /* for various object types */
+#define ACL_CREATE (1<<9) /* for namespaces and databases */
+#define ACL_CREATE_TEMP (1<<10) /* for databases */
+#define ACL_CONNECT (1<<11) /* for databases */
+#define ACL_SET (1<<12) /* for configuration parameters */
+#define ACL_ALTER_SYSTEM (1<<13) /* for configuration parameters */
+#define N_ACL_RIGHTS 14 /* 1 plus the last 1< 0
+ */
+ List *rteperminfos pg_node_attr(query_jumble_ignore);
+ FromExpr *jointree; /* table join tree (FROM and WHERE clauses);
+ * also USING clause for MERGE */
+
+ List *mergeActionList; /* list of actions for MERGE (only) */
+ /* whether to use outer join */
+ bool mergeUseOuterJoin pg_node_attr(query_jumble_ignore);
+
+ List *targetList; /* target list (of TargetEntry) */
+
+ /* OVERRIDING clause */
+ OverridingKind override pg_node_attr(query_jumble_ignore);
+
+ OnConflictExpr *onConflict; /* ON CONFLICT DO [NOTHING | UPDATE] */
+
+ List *returningList; /* return-values list (of TargetEntry) */
+
+ List *groupClause; /* a list of SortGroupClause's */
+ bool groupDistinct; /* is the group by clause distinct? */
+
+ List *groupingSets; /* a list of GroupingSet's if present */
+
+ Node *havingQual; /* qualifications applied to groups */
+
+ List *windowClause; /* a list of WindowClause's */
+
+ List *distinctClause; /* a list of SortGroupClause's */
+
+ List *sortClause; /* a list of SortGroupClause's */
+
+ Node *limitOffset; /* # of result tuples to skip (int8 expr) */
+ Node *limitCount; /* # of result tuples to return (int8 expr) */
+ LimitOption limitOption; /* limit type */
+
+ List *rowMarks; /* a list of RowMarkClause's */
+
+ Node *setOperations; /* set-operation tree if this is top level of
+ * a UNION/INTERSECT/EXCEPT query */
+
+ /*
+ * A list of pg_constraint OIDs that the query depends on to be
+ * semantically valid
+ */
+ List *constraintDeps pg_node_attr(query_jumble_ignore);
+
+ /* a list of WithCheckOption's (added during rewrite) */
+ List *withCheckOptions pg_node_attr(query_jumble_ignore);
+
+ /*
+ * The following two fields identify the portion of the source text string
+ * containing this query. They are typically only populated in top-level
+ * Queries, not in sub-queries. When not set, they might both be zero, or
+ * both be -1 meaning "unknown".
+ */
+ /* start location, or -1 if unknown */
+ int stmt_location;
+ /* length in bytes; 0 means "rest of string" */
+ int stmt_len pg_node_attr(query_jumble_ignore);
+} Query;
+
+
+/****************************************************************************
+ * Supporting data structures for Parse Trees
+ *
+ * Most of these node types appear in raw parsetrees output by the grammar,
+ * and get transformed to something else by the analyzer. A few of them
+ * are used as-is in transformed querytrees.
+ ****************************************************************************/
+
+/*
+ * TypeName - specifies a type in definitions
+ *
+ * For TypeName structures generated internally, it is often easier to
+ * specify the type by OID than by name. If "names" is NIL then the
+ * actual type OID is given by typeOid, otherwise typeOid is unused.
+ * Similarly, if "typmods" is NIL then the actual typmod is expected to
+ * be prespecified in typemod, otherwise typemod is unused.
+ *
+ * If pct_type is true, then names is actually a field name and we look up
+ * the type of that field. Otherwise (the normal case), names is a type
+ * name possibly qualified with schema and database name.
+ */
+typedef struct TypeName
+{
+ NodeTag type;
+ List *names; /* qualified name (list of String nodes) */
+ Oid typeOid; /* type identified by OID */
+ bool setof; /* is a set? */
+ bool pct_type; /* %TYPE specified? */
+ List *typmods; /* type modifier expression(s) */
+ int32 typemod; /* prespecified type modifier */
+ List *arrayBounds; /* array bounds */
+ int location; /* token location, or -1 if unknown */
+} TypeName;
+
+/*
+ * ColumnRef - specifies a reference to a column, or possibly a whole tuple
+ *
+ * The "fields" list must be nonempty. It can contain String nodes
+ * (representing names) and A_Star nodes (representing occurrence of a '*').
+ * Currently, A_Star must appear only as the last list element --- the grammar
+ * is responsible for enforcing this!
+ *
+ * Note: any container subscripting or selection of fields from composite columns
+ * is represented by an A_Indirection node above the ColumnRef. However,
+ * for simplicity in the normal case, initial field selection from a table
+ * name is represented within ColumnRef and not by adding A_Indirection.
+ */
+typedef struct ColumnRef
+{
+ NodeTag type;
+ List *fields; /* field names (String nodes) or A_Star */
+ int location; /* token location, or -1 if unknown */
+} ColumnRef;
+
+/*
+ * ParamRef - specifies a $n parameter reference
+ */
+typedef struct ParamRef
+{
+ NodeTag type;
+ int number; /* the number of the parameter */
+ int location; /* token location, or -1 if unknown */
+} ParamRef;
+
+/*
+ * A_Expr - infix, prefix, and postfix expressions
+ */
+typedef enum A_Expr_Kind
+{
+ AEXPR_OP, /* normal operator */
+ AEXPR_OP_ANY, /* scalar op ANY (array) */
+ AEXPR_OP_ALL, /* scalar op ALL (array) */
+ AEXPR_DISTINCT, /* IS DISTINCT FROM - name must be "=" */
+ AEXPR_NOT_DISTINCT, /* IS NOT DISTINCT FROM - name must be "=" */
+ AEXPR_NULLIF, /* NULLIF - name must be "=" */
+ AEXPR_IN, /* [NOT] IN - name must be "=" or "<>" */
+ AEXPR_LIKE, /* [NOT] LIKE - name must be "~~" or "!~~" */
+ AEXPR_ILIKE, /* [NOT] ILIKE - name must be "~~*" or "!~~*" */
+ AEXPR_SIMILAR, /* [NOT] SIMILAR - name must be "~" or "!~" */
+ AEXPR_BETWEEN, /* name must be "BETWEEN" */
+ AEXPR_NOT_BETWEEN, /* name must be "NOT BETWEEN" */
+ AEXPR_BETWEEN_SYM, /* name must be "BETWEEN SYMMETRIC" */
+ AEXPR_NOT_BETWEEN_SYM /* name must be "NOT BETWEEN SYMMETRIC" */
+} A_Expr_Kind;
+
+typedef struct A_Expr
+{
+ pg_node_attr(custom_read_write)
+
+ NodeTag type;
+ A_Expr_Kind kind; /* see above */
+ List *name; /* possibly-qualified name of operator */
+ Node *lexpr; /* left argument, or NULL if none */
+ Node *rexpr; /* right argument, or NULL if none */
+ int location; /* token location, or -1 if unknown */
+} A_Expr;
+
+/*
+ * A_Const - a literal constant
+ *
+ * Value nodes are inline for performance. You can treat 'val' as a node,
+ * as in IsA(&val, Integer). 'val' is not valid if isnull is true.
+ */
+union ValUnion
+{
+ Node node;
+ Integer ival;
+ Float fval;
+ Boolean boolval;
+ String sval;
+ BitString bsval;
+};
+
+typedef struct A_Const
+{
+ pg_node_attr(custom_copy_equal, custom_read_write, custom_query_jumble)
+
+ NodeTag type;
+ union ValUnion val;
+ bool isnull; /* SQL NULL constant */
+ int location; /* token location, or -1 if unknown */
+} A_Const;
+
+/*
+ * TypeCast - a CAST expression
+ */
+typedef struct TypeCast
+{
+ NodeTag type;
+ Node *arg; /* the expression being casted */
+ TypeName *typeName; /* the target type */
+ int location; /* token location, or -1 if unknown */
+} TypeCast;
+
+/*
+ * CollateClause - a COLLATE expression
+ */
+typedef struct CollateClause
+{
+ NodeTag type;
+ Node *arg; /* input expression */
+ List *collname; /* possibly-qualified collation name */
+ int location; /* token location, or -1 if unknown */
+} CollateClause;
+
+/*
+ * RoleSpec - a role name or one of a few special values.
+ */
+typedef enum RoleSpecType
+{
+ ROLESPEC_CSTRING, /* role name is stored as a C string */
+ ROLESPEC_CURRENT_ROLE, /* role spec is CURRENT_ROLE */
+ ROLESPEC_CURRENT_USER, /* role spec is CURRENT_USER */
+ ROLESPEC_SESSION_USER, /* role spec is SESSION_USER */
+ ROLESPEC_PUBLIC /* role name is "public" */
+} RoleSpecType;
+
+typedef struct RoleSpec
+{
+ NodeTag type;
+ RoleSpecType roletype; /* Type of this rolespec */
+ char *rolename; /* filled only for ROLESPEC_CSTRING */
+ int location; /* token location, or -1 if unknown */
+} RoleSpec;
+
+/*
+ * FuncCall - a function or aggregate invocation
+ *
+ * agg_order (if not NIL) indicates we saw 'foo(... ORDER BY ...)', or if
+ * agg_within_group is true, it was 'foo(...) WITHIN GROUP (ORDER BY ...)'.
+ * agg_star indicates we saw a 'foo(*)' construct, while agg_distinct
+ * indicates we saw 'foo(DISTINCT ...)'. In any of these cases, the
+ * construct *must* be an aggregate call. Otherwise, it might be either an
+ * aggregate or some other kind of function. However, if FILTER or OVER is
+ * present it had better be an aggregate or window function.
+ *
+ * Normally, you'd initialize this via makeFuncCall() and then only change the
+ * parts of the struct its defaults don't match afterwards, as needed.
+ */
+typedef struct FuncCall
+{
+ NodeTag type;
+ List *funcname; /* qualified name of function */
+ List *args; /* the arguments (list of exprs) */
+ List *agg_order; /* ORDER BY (list of SortBy) */
+ Node *agg_filter; /* FILTER clause, if any */
+ struct WindowDef *over; /* OVER clause, if any */
+ bool agg_within_group; /* ORDER BY appeared in WITHIN GROUP */
+ bool agg_star; /* argument was really '*' */
+ bool agg_distinct; /* arguments were labeled DISTINCT */
+ bool func_variadic; /* last argument was labeled VARIADIC */
+ CoercionForm funcformat; /* how to display this node */
+ int location; /* token location, or -1 if unknown */
+} FuncCall;
+
+/*
+ * A_Star - '*' representing all columns of a table or compound field
+ *
+ * This can appear within ColumnRef.fields, A_Indirection.indirection, and
+ * ResTarget.indirection lists.
+ */
+typedef struct A_Star
+{
+ NodeTag type;
+} A_Star;
+
+/*
+ * A_Indices - array subscript or slice bounds ([idx] or [lidx:uidx])
+ *
+ * In slice case, either or both of lidx and uidx can be NULL (omitted).
+ * In non-slice case, uidx holds the single subscript and lidx is always NULL.
+ */
+typedef struct A_Indices
+{
+ NodeTag type;
+ bool is_slice; /* true if slice (i.e., colon present) */
+ Node *lidx; /* slice lower bound, if any */
+ Node *uidx; /* subscript, or slice upper bound if any */
+} A_Indices;
+
+/*
+ * A_Indirection - select a field and/or array element from an expression
+ *
+ * The indirection list can contain A_Indices nodes (representing
+ * subscripting), String nodes (representing field selection --- the
+ * string value is the name of the field to select), and A_Star nodes
+ * (representing selection of all fields of a composite type).
+ * For example, a complex selection operation like
+ * (foo).field1[42][7].field2
+ * would be represented with a single A_Indirection node having a 4-element
+ * indirection list.
+ *
+ * Currently, A_Star must appear only as the last list element --- the grammar
+ * is responsible for enforcing this!
+ */
+typedef struct A_Indirection
+{
+ NodeTag type;
+ Node *arg; /* the thing being selected from */
+ List *indirection; /* subscripts and/or field names and/or * */
+} A_Indirection;
+
+/*
+ * A_ArrayExpr - an ARRAY[] construct
+ */
+typedef struct A_ArrayExpr
+{
+ NodeTag type;
+ List *elements; /* array element expressions */
+ int location; /* token location, or -1 if unknown */
+} A_ArrayExpr;
+
+/*
+ * ResTarget -
+ * result target (used in target list of pre-transformed parse trees)
+ *
+ * In a SELECT target list, 'name' is the column label from an
+ * 'AS ColumnLabel' clause, or NULL if there was none, and 'val' is the
+ * value expression itself. The 'indirection' field is not used.
+ *
+ * INSERT uses ResTarget in its target-column-names list. Here, 'name' is
+ * the name of the destination column, 'indirection' stores any subscripts
+ * attached to the destination, and 'val' is not used.
+ *
+ * In an UPDATE target list, 'name' is the name of the destination column,
+ * 'indirection' stores any subscripts attached to the destination, and
+ * 'val' is the expression to assign.
+ *
+ * See A_Indirection for more info about what can appear in 'indirection'.
+ */
+typedef struct ResTarget
+{
+ NodeTag type;
+ char *name; /* column name or NULL */
+ List *indirection; /* subscripts, field names, and '*', or NIL */
+ Node *val; /* the value expression to compute or assign */
+ int location; /* token location, or -1 if unknown */
+} ResTarget;
+
+/*
+ * MultiAssignRef - element of a row source expression for UPDATE
+ *
+ * In an UPDATE target list, when we have SET (a,b,c) = row-valued-expression,
+ * we generate separate ResTarget items for each of a,b,c. Their "val" trees
+ * are MultiAssignRef nodes numbered 1..n, linking to a common copy of the
+ * row-valued-expression (which parse analysis will process only once, when
+ * handling the MultiAssignRef with colno=1).
+ */
+typedef struct MultiAssignRef
+{
+ NodeTag type;
+ Node *source; /* the row-valued expression */
+ int colno; /* column number for this target (1..n) */
+ int ncolumns; /* number of targets in the construct */
+} MultiAssignRef;
+
+/*
+ * SortBy - for ORDER BY clause
+ */
+typedef struct SortBy
+{
+ NodeTag type;
+ Node *node; /* expression to sort on */
+ SortByDir sortby_dir; /* ASC/DESC/USING/default */
+ SortByNulls sortby_nulls; /* NULLS FIRST/LAST */
+ List *useOp; /* name of op to use, if SORTBY_USING */
+ int location; /* operator location, or -1 if none/unknown */
+} SortBy;
+
+/*
+ * WindowDef - raw representation of WINDOW and OVER clauses
+ *
+ * For entries in a WINDOW list, "name" is the window name being defined.
+ * For OVER clauses, we use "name" for the "OVER window" syntax, or "refname"
+ * for the "OVER (window)" syntax, which is subtly different --- the latter
+ * implies overriding the window frame clause.
+ */
+typedef struct WindowDef
+{
+ NodeTag type;
+ char *name; /* window's own name */
+ char *refname; /* referenced window name, if any */
+ List *partitionClause; /* PARTITION BY expression list */
+ List *orderClause; /* ORDER BY (list of SortBy) */
+ int frameOptions; /* frame_clause options, see below */
+ Node *startOffset; /* expression for starting bound, if any */
+ Node *endOffset; /* expression for ending bound, if any */
+ int location; /* parse location, or -1 if none/unknown */
+} WindowDef;
+
+/*
+ * frameOptions is an OR of these bits. The NONDEFAULT and BETWEEN bits are
+ * used so that ruleutils.c can tell which properties were specified and
+ * which were defaulted; the correct behavioral bits must be set either way.
+ * The START_foo and END_foo options must come in pairs of adjacent bits for
+ * the convenience of gram.y, even though some of them are useless/invalid.
+ */
+#define FRAMEOPTION_NONDEFAULT 0x00001 /* any specified? */
+#define FRAMEOPTION_RANGE 0x00002 /* RANGE behavior */
+#define FRAMEOPTION_ROWS 0x00004 /* ROWS behavior */
+#define FRAMEOPTION_GROUPS 0x00008 /* GROUPS behavior */
+#define FRAMEOPTION_BETWEEN 0x00010 /* BETWEEN given? */
+#define FRAMEOPTION_START_UNBOUNDED_PRECEDING 0x00020 /* start is U. P. */
+#define FRAMEOPTION_END_UNBOUNDED_PRECEDING 0x00040 /* (disallowed) */
+#define FRAMEOPTION_START_UNBOUNDED_FOLLOWING 0x00080 /* (disallowed) */
+#define FRAMEOPTION_END_UNBOUNDED_FOLLOWING 0x00100 /* end is U. F. */
+#define FRAMEOPTION_START_CURRENT_ROW 0x00200 /* start is C. R. */
+#define FRAMEOPTION_END_CURRENT_ROW 0x00400 /* end is C. R. */
+#define FRAMEOPTION_START_OFFSET_PRECEDING 0x00800 /* start is O. P. */
+#define FRAMEOPTION_END_OFFSET_PRECEDING 0x01000 /* end is O. P. */
+#define FRAMEOPTION_START_OFFSET_FOLLOWING 0x02000 /* start is O. F. */
+#define FRAMEOPTION_END_OFFSET_FOLLOWING 0x04000 /* end is O. F. */
+#define FRAMEOPTION_EXCLUDE_CURRENT_ROW 0x08000 /* omit C.R. */
+#define FRAMEOPTION_EXCLUDE_GROUP 0x10000 /* omit C.R. & peers */
+#define FRAMEOPTION_EXCLUDE_TIES 0x20000 /* omit C.R.'s peers */
+
+#define FRAMEOPTION_START_OFFSET \
+ (FRAMEOPTION_START_OFFSET_PRECEDING | FRAMEOPTION_START_OFFSET_FOLLOWING)
+#define FRAMEOPTION_END_OFFSET \
+ (FRAMEOPTION_END_OFFSET_PRECEDING | FRAMEOPTION_END_OFFSET_FOLLOWING)
+#define FRAMEOPTION_EXCLUSION \
+ (FRAMEOPTION_EXCLUDE_CURRENT_ROW | FRAMEOPTION_EXCLUDE_GROUP | \
+ FRAMEOPTION_EXCLUDE_TIES)
+
+#define FRAMEOPTION_DEFAULTS \
+ (FRAMEOPTION_RANGE | FRAMEOPTION_START_UNBOUNDED_PRECEDING | \
+ FRAMEOPTION_END_CURRENT_ROW)
+
+/*
+ * RangeSubselect - subquery appearing in a FROM clause
+ */
+typedef struct RangeSubselect
+{
+ NodeTag type;
+ bool lateral; /* does it have LATERAL prefix? */
+ Node *subquery; /* the untransformed sub-select clause */
+ Alias *alias; /* table alias & optional column aliases */
+} RangeSubselect;
+
+/*
+ * RangeFunction - function call appearing in a FROM clause
+ *
+ * functions is a List because we use this to represent the construct
+ * ROWS FROM(func1(...), func2(...), ...). Each element of this list is a
+ * two-element sublist, the first element being the untransformed function
+ * call tree, and the second element being a possibly-empty list of ColumnDef
+ * nodes representing any columndef list attached to that function within the
+ * ROWS FROM() syntax.
+ *
+ * alias and coldeflist represent any alias and/or columndef list attached
+ * at the top level. (We disallow coldeflist appearing both here and
+ * per-function, but that's checked in parse analysis, not by the grammar.)
+ */
+typedef struct RangeFunction
+{
+ NodeTag type;
+ bool lateral; /* does it have LATERAL prefix? */
+ bool ordinality; /* does it have WITH ORDINALITY suffix? */
+ bool is_rowsfrom; /* is result of ROWS FROM() syntax? */
+ List *functions; /* per-function information, see above */
+ Alias *alias; /* table alias & optional column aliases */
+ List *coldeflist; /* list of ColumnDef nodes to describe result
+ * of function returning RECORD */
+} RangeFunction;
+
+/*
+ * RangeTableFunc - raw form of "table functions" such as XMLTABLE
+ */
+typedef struct RangeTableFunc
+{
+ NodeTag type;
+ bool lateral; /* does it have LATERAL prefix? */
+ Node *docexpr; /* document expression */
+ Node *rowexpr; /* row generator expression */
+ List *namespaces; /* list of namespaces as ResTarget */
+ List *columns; /* list of RangeTableFuncCol */
+ Alias *alias; /* table alias & optional column aliases */
+ int location; /* token location, or -1 if unknown */
+} RangeTableFunc;
+
+/*
+ * RangeTableFuncCol - one column in a RangeTableFunc->columns
+ *
+ * If for_ordinality is true (FOR ORDINALITY), then the column is an int4
+ * column and the rest of the fields are ignored.
+ */
+typedef struct RangeTableFuncCol
+{
+ NodeTag type;
+ char *colname; /* name of generated column */
+ TypeName *typeName; /* type of generated column */
+ bool for_ordinality; /* does it have FOR ORDINALITY? */
+ bool is_not_null; /* does it have NOT NULL? */
+ Node *colexpr; /* column filter expression */
+ Node *coldefexpr; /* column default value expression */
+ int location; /* token location, or -1 if unknown */
+} RangeTableFuncCol;
+
+/*
+ * RangeTableSample - TABLESAMPLE appearing in a raw FROM clause
+ *
+ * This node, appearing only in raw parse trees, represents
+ * TABLESAMPLE () REPEATABLE ()
+ * Currently, the can only be a RangeVar, but we might in future
+ * allow RangeSubselect and other options. Note that the RangeTableSample
+ * is wrapped around the node representing the , rather than being
+ * a subfield of it.
+ */
+typedef struct RangeTableSample
+{
+ NodeTag type;
+ Node *relation; /* relation to be sampled */
+ List *method; /* sampling method name (possibly qualified) */
+ List *args; /* argument(s) for sampling method */
+ Node *repeatable; /* REPEATABLE expression, or NULL if none */
+ int location; /* method name location, or -1 if unknown */
+} RangeTableSample;
+
+/*
+ * ColumnDef - column definition (used in various creates)
+ *
+ * If the column has a default value, we may have the value expression
+ * in either "raw" form (an untransformed parse tree) or "cooked" form
+ * (a post-parse-analysis, executable expression tree), depending on
+ * how this ColumnDef node was created (by parsing, or by inheritance
+ * from an existing relation). We should never have both in the same node!
+ *
+ * Similarly, we may have a COLLATE specification in either raw form
+ * (represented as a CollateClause with arg==NULL) or cooked form
+ * (the collation's OID).
+ *
+ * The constraints list may contain a CONSTR_DEFAULT item in a raw
+ * parsetree produced by gram.y, but transformCreateStmt will remove
+ * the item and set raw_default instead. CONSTR_DEFAULT items
+ * should not appear in any subsequent processing.
+ */
+typedef struct ColumnDef
+{
+ NodeTag type;
+ char *colname; /* name of column */
+ TypeName *typeName; /* type of column */
+ char *compression; /* compression method for column */
+ int inhcount; /* number of times column is inherited */
+ bool is_local; /* column has local (non-inherited) def'n */
+ bool is_not_null; /* NOT NULL constraint specified? */
+ bool is_from_type; /* column definition came from table type */
+ char storage; /* attstorage setting, or 0 for default */
+ char *storage_name; /* attstorage setting name or NULL for default */
+ Node *raw_default; /* default value (untransformed parse tree) */
+ Node *cooked_default; /* default value (transformed expr tree) */
+ char identity; /* attidentity setting */
+ RangeVar *identitySequence; /* to store identity sequence name for
+ * ALTER TABLE ... ADD COLUMN */
+ char generated; /* attgenerated setting */
+ CollateClause *collClause; /* untransformed COLLATE spec, if any */
+ Oid collOid; /* collation OID (InvalidOid if not set) */
+ List *constraints; /* other constraints on column */
+ List *fdwoptions; /* per-column FDW options */
+ int location; /* parse location, or -1 if none/unknown */
+} ColumnDef;
+
+/*
+ * TableLikeClause - CREATE TABLE ( ... LIKE ... ) clause
+ */
+typedef struct TableLikeClause
+{
+ NodeTag type;
+ RangeVar *relation;
+ bits32 options; /* OR of TableLikeOption flags */
+ Oid relationOid; /* If table has been looked up, its OID */
+} TableLikeClause;
+
+typedef enum TableLikeOption
+{
+ CREATE_TABLE_LIKE_COMMENTS = 1 << 0,
+ CREATE_TABLE_LIKE_COMPRESSION = 1 << 1,
+ CREATE_TABLE_LIKE_CONSTRAINTS = 1 << 2,
+ CREATE_TABLE_LIKE_DEFAULTS = 1 << 3,
+ CREATE_TABLE_LIKE_GENERATED = 1 << 4,
+ CREATE_TABLE_LIKE_IDENTITY = 1 << 5,
+ CREATE_TABLE_LIKE_INDEXES = 1 << 6,
+ CREATE_TABLE_LIKE_STATISTICS = 1 << 7,
+ CREATE_TABLE_LIKE_STORAGE = 1 << 8,
+ CREATE_TABLE_LIKE_ALL = PG_INT32_MAX
+} TableLikeOption;
+
+/*
+ * IndexElem - index parameters (used in CREATE INDEX, and in ON CONFLICT)
+ *
+ * For a plain index attribute, 'name' is the name of the table column to
+ * index, and 'expr' is NULL. For an index expression, 'name' is NULL and
+ * 'expr' is the expression tree.
+ */
+typedef struct IndexElem
+{
+ NodeTag type;
+ char *name; /* name of attribute to index, or NULL */
+ Node *expr; /* expression to index, or NULL */
+ char *indexcolname; /* name for index column; NULL = default */
+ List *collation; /* name of collation; NIL = default */
+ List *opclass; /* name of desired opclass; NIL = default */
+ List *opclassopts; /* opclass-specific options, or NIL */
+ SortByDir ordering; /* ASC/DESC/default */
+ SortByNulls nulls_ordering; /* FIRST/LAST/default */
+} IndexElem;
+
+/*
+ * DefElem - a generic "name = value" option definition
+ *
+ * In some contexts the name can be qualified. Also, certain SQL commands
+ * allow a SET/ADD/DROP action to be attached to option settings, so it's
+ * convenient to carry a field for that too. (Note: currently, it is our
+ * practice that the grammar allows namespace and action only in statements
+ * where they are relevant; C code can just ignore those fields in other
+ * statements.)
+ */
+typedef enum DefElemAction
+{
+ DEFELEM_UNSPEC, /* no action given */
+ DEFELEM_SET,
+ DEFELEM_ADD,
+ DEFELEM_DROP
+} DefElemAction;
+
+typedef struct DefElem
+{
+ NodeTag type;
+ char *defnamespace; /* NULL if unqualified name */
+ char *defname;
+ Node *arg; /* typically Integer, Float, String, or
+ * TypeName */
+ DefElemAction defaction; /* unspecified action, or SET/ADD/DROP */
+ int location; /* token location, or -1 if unknown */
+} DefElem;
+
+/*
+ * LockingClause - raw representation of FOR [NO KEY] UPDATE/[KEY] SHARE
+ * options
+ *
+ * Note: lockedRels == NIL means "all relations in query". Otherwise it
+ * is a list of RangeVar nodes. (We use RangeVar mainly because it carries
+ * a location field --- currently, parse analysis insists on unqualified
+ * names in LockingClause.)
+ */
+typedef struct LockingClause
+{
+ NodeTag type;
+ List *lockedRels; /* FOR [KEY] UPDATE/SHARE relations */
+ LockClauseStrength strength;
+ LockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
+} LockingClause;
+
+/*
+ * XMLSERIALIZE (in raw parse tree only)
+ */
+typedef struct XmlSerialize
+{
+ NodeTag type;
+ XmlOptionType xmloption; /* DOCUMENT or CONTENT */
+ Node *expr;
+ TypeName *typeName;
+ bool indent; /* [NO] INDENT */
+ int location; /* token location, or -1 if unknown */
+} XmlSerialize;
+
+/* Partitioning related definitions */
+
+/*
+ * PartitionElem - parse-time representation of a single partition key
+ *
+ * expr can be either a raw expression tree or a parse-analyzed expression.
+ * We don't store these on-disk, though.
+ */
+typedef struct PartitionElem
+{
+ NodeTag type;
+ char *name; /* name of column to partition on, or NULL */
+ Node *expr; /* expression to partition on, or NULL */
+ List *collation; /* name of collation; NIL = default */
+ List *opclass; /* name of desired opclass; NIL = default */
+ int location; /* token location, or -1 if unknown */
+} PartitionElem;
+
+typedef enum PartitionStrategy
+{
+ PARTITION_STRATEGY_LIST = 'l',
+ PARTITION_STRATEGY_RANGE = 'r',
+ PARTITION_STRATEGY_HASH = 'h'
+} PartitionStrategy;
+
+/*
+ * PartitionSpec - parse-time representation of a partition key specification
+ *
+ * This represents the key space we will be partitioning on.
+ */
+typedef struct PartitionSpec
+{
+ NodeTag type;
+ PartitionStrategy strategy;
+ List *partParams; /* List of PartitionElems */
+ int location; /* token location, or -1 if unknown */
+} PartitionSpec;
+
+/*
+ * PartitionBoundSpec - a partition bound specification
+ *
+ * This represents the portion of the partition key space assigned to a
+ * particular partition. These are stored on disk in pg_class.relpartbound.
+ */
+struct PartitionBoundSpec
+{
+ NodeTag type;
+
+ char strategy; /* see PARTITION_STRATEGY codes above */
+ bool is_default; /* is it a default partition bound? */
+
+ /* Partitioning info for HASH strategy: */
+ int modulus;
+ int remainder;
+
+ /* Partitioning info for LIST strategy: */
+ List *listdatums; /* List of Consts (or A_Consts in raw tree) */
+
+ /* Partitioning info for RANGE strategy: */
+ List *lowerdatums; /* List of PartitionRangeDatums */
+ List *upperdatums; /* List of PartitionRangeDatums */
+
+ int location; /* token location, or -1 if unknown */
+};
+
+/*
+ * PartitionRangeDatum - one of the values in a range partition bound
+ *
+ * This can be MINVALUE, MAXVALUE or a specific bounded value.
+ */
+typedef enum PartitionRangeDatumKind
+{
+ PARTITION_RANGE_DATUM_MINVALUE = -1, /* less than any other value */
+ PARTITION_RANGE_DATUM_VALUE = 0, /* a specific (bounded) value */
+ PARTITION_RANGE_DATUM_MAXVALUE = 1 /* greater than any other value */
+} PartitionRangeDatumKind;
+
+typedef struct PartitionRangeDatum
+{
+ NodeTag type;
+
+ PartitionRangeDatumKind kind;
+ Node *value; /* Const (or A_Const in raw tree), if kind is
+ * PARTITION_RANGE_DATUM_VALUE, else NULL */
+
+ int location; /* token location, or -1 if unknown */
+} PartitionRangeDatum;
+
+/*
+ * PartitionCmd - info for ALTER TABLE/INDEX ATTACH/DETACH PARTITION commands
+ */
+typedef struct PartitionCmd
+{
+ NodeTag type;
+ RangeVar *name; /* name of partition to attach/detach */
+ PartitionBoundSpec *bound; /* FOR VALUES, if attaching */
+ bool concurrent;
+} PartitionCmd;
+
+/****************************************************************************
+ * Nodes for a Query tree
+ ****************************************************************************/
+
+/*--------------------
+ * RangeTblEntry -
+ * A range table is a List of RangeTblEntry nodes.
+ *
+ * A range table entry may represent a plain relation, a sub-select in
+ * FROM, or the result of a JOIN clause. (Only explicit JOIN syntax
+ * produces an RTE, not the implicit join resulting from multiple FROM
+ * items. This is because we only need the RTE to deal with SQL features
+ * like outer joins and join-output-column aliasing.) Other special
+ * RTE types also exist, as indicated by RTEKind.
+ *
+ * Note that we consider RTE_RELATION to cover anything that has a pg_class
+ * entry. relkind distinguishes the sub-cases.
+ *
+ * alias is an Alias node representing the AS alias-clause attached to the
+ * FROM expression, or NULL if no clause.
+ *
+ * eref is the table reference name and column reference names (either
+ * real or aliases). Note that system columns (OID etc) are not included
+ * in the column list.
+ * eref->aliasname is required to be present, and should generally be used
+ * to identify the RTE for error messages etc.
+ *
+ * In RELATION RTEs, the colnames in both alias and eref are indexed by
+ * physical attribute number; this means there must be colname entries for
+ * dropped columns. When building an RTE we insert empty strings ("") for
+ * dropped columns. Note however that a stored rule may have nonempty
+ * colnames for columns dropped since the rule was created (and for that
+ * matter the colnames might be out of date due to column renamings).
+ * The same comments apply to FUNCTION RTEs when a function's return type
+ * is a named composite type.
+ *
+ * In JOIN RTEs, the colnames in both alias and eref are one-to-one with
+ * joinaliasvars entries. A JOIN RTE will omit columns of its inputs when
+ * those columns are known to be dropped at parse time. Again, however,
+ * a stored rule might contain entries for columns dropped since the rule
+ * was created. (This is only possible for columns not actually referenced
+ * in the rule.) When loading a stored rule, we replace the joinaliasvars
+ * items for any such columns with null pointers. (We can't simply delete
+ * them from the joinaliasvars list, because that would affect the attnums
+ * of Vars referencing the rest of the list.)
+ *
+ * inh is true for relation references that should be expanded to include
+ * inheritance children, if the rel has any. This *must* be false for
+ * RTEs other than RTE_RELATION entries.
+ *
+ * inFromCl marks those range variables that are listed in the FROM clause.
+ * It's false for RTEs that are added to a query behind the scenes, such
+ * as the NEW and OLD variables for a rule, or the subqueries of a UNION.
+ * This flag is not used during parsing (except in transformLockingClause,
+ * q.v.); the parser now uses a separate "namespace" data structure to
+ * control visibility. But it is needed by ruleutils.c to determine
+ * whether RTEs should be shown in decompiled queries.
+ *
+ * securityQuals is a list of security barrier quals (boolean expressions),
+ * to be tested in the listed order before returning a row from the
+ * relation. It is always NIL in parser output. Entries are added by the
+ * rewriter to implement security-barrier views and/or row-level security.
+ * Note that the planner turns each boolean expression into an implicitly
+ * AND'ed sublist, as is its usual habit with qualification expressions.
+ *--------------------
+ */
+typedef enum RTEKind
+{
+ RTE_RELATION, /* ordinary relation reference */
+ RTE_SUBQUERY, /* subquery in FROM */
+ RTE_JOIN, /* join */
+ RTE_FUNCTION, /* function in FROM */
+ RTE_TABLEFUNC, /* TableFunc(.., column list) */
+ RTE_VALUES, /* VALUES (), (), ... */
+ RTE_CTE, /* common table expr (WITH list element) */
+ RTE_NAMEDTUPLESTORE, /* tuplestore, e.g. for AFTER triggers */
+ RTE_RESULT /* RTE represents an empty FROM clause; such
+ * RTEs are added by the planner, they're not
+ * present during parsing or rewriting */
+} RTEKind;
+
+typedef struct RangeTblEntry
+{
+ pg_node_attr(custom_read_write, custom_query_jumble)
+
+ NodeTag type;
+
+ RTEKind rtekind; /* see above */
+
+ /*
+ * XXX the fields applicable to only some rte kinds should be merged into
+ * a union. I didn't do this yet because the diffs would impact a lot of
+ * code that is being actively worked on. FIXME someday.
+ */
+
+ /*
+ * Fields valid for a plain relation RTE (else zero):
+ *
+ * rellockmode is really LOCKMODE, but it's declared int to avoid having
+ * to include lock-related headers here. It must be RowExclusiveLock if
+ * the RTE is an INSERT/UPDATE/DELETE/MERGE target, else RowShareLock if
+ * the RTE is a SELECT FOR UPDATE/FOR SHARE target, else AccessShareLock.
+ *
+ * Note: in some cases, rule expansion may result in RTEs that are marked
+ * with RowExclusiveLock even though they are not the target of the
+ * current query; this happens if a DO ALSO rule simply scans the original
+ * target table. We leave such RTEs with their original lockmode so as to
+ * avoid getting an additional, lesser lock.
+ *
+ * perminfoindex is 1-based index of the RTEPermissionInfo belonging to
+ * this RTE in the containing struct's list of same; 0 if permissions need
+ * not be checked for this RTE.
+ *
+ * As a special case, relid, relkind, rellockmode, and perminfoindex can
+ * also be set (nonzero) in an RTE_SUBQUERY RTE. This occurs when we
+ * convert an RTE_RELATION RTE naming a view into an RTE_SUBQUERY
+ * containing the view's query. We still need to perform run-time locking
+ * and permission checks on the view, even though it's not directly used
+ * in the query anymore, and the most expedient way to do that is to
+ * retain these fields from the old state of the RTE.
+ *
+ * As a special case, RTE_NAMEDTUPLESTORE can also set relid to indicate
+ * that the tuple format of the tuplestore is the same as the referenced
+ * relation. This allows plans referencing AFTER trigger transition
+ * tables to be invalidated if the underlying table is altered.
+ */
+ Oid relid; /* OID of the relation */
+ char relkind; /* relation kind (see pg_class.relkind) */
+ int rellockmode; /* lock level that query requires on the rel */
+ struct TableSampleClause *tablesample; /* sampling info, or NULL */
+ Index perminfoindex;
+
+ /*
+ * Fields valid for a subquery RTE (else NULL):
+ */
+ Query *subquery; /* the sub-query */
+ bool security_barrier; /* is from security_barrier view? */
+
+ /*
+ * Fields valid for a join RTE (else NULL/zero):
+ *
+ * joinaliasvars is a list of (usually) Vars corresponding to the columns
+ * of the join result. An alias Var referencing column K of the join
+ * result can be replaced by the K'th element of joinaliasvars --- but to
+ * simplify the task of reverse-listing aliases correctly, we do not do
+ * that until planning time. In detail: an element of joinaliasvars can
+ * be a Var of one of the join's input relations, or such a Var with an
+ * implicit coercion to the join's output column type, or a COALESCE
+ * expression containing the two input column Vars (possibly coerced).
+ * Elements beyond the first joinmergedcols entries are always just Vars,
+ * and are never referenced from elsewhere in the query (that is, join
+ * alias Vars are generated only for merged columns). We keep these
+ * entries only because they're needed in expandRTE() and similar code.
+ *
+ * Vars appearing within joinaliasvars are marked with varnullingrels sets
+ * that describe the nulling effects of this join and lower ones. This is
+ * essential for FULL JOIN cases, because the COALESCE expression only
+ * describes the semantics correctly if its inputs have been nulled by the
+ * join. For other cases, it allows expandRTE() to generate a valid
+ * representation of the join's output without consulting additional
+ * parser state.
+ *
+ * Within a Query loaded from a stored rule, it is possible for non-merged
+ * joinaliasvars items to be null pointers, which are placeholders for
+ * (necessarily unreferenced) columns dropped since the rule was made.
+ * Also, once planning begins, joinaliasvars items can be almost anything,
+ * as a result of subquery-flattening substitutions.
+ *
+ * joinleftcols is an integer list of physical column numbers of the left
+ * join input rel that are included in the join; likewise joinrighttcols
+ * for the right join input rel. (Which rels those are can be determined
+ * from the associated JoinExpr.) If the join is USING/NATURAL, then the
+ * first joinmergedcols entries in each list identify the merged columns.
+ * The merged columns come first in the join output, then remaining
+ * columns of the left input, then remaining columns of the right.
+ *
+ * Note that input columns could have been dropped after creation of a
+ * stored rule, if they are not referenced in the query (in particular,
+ * merged columns could not be dropped); this is not accounted for in
+ * joinleftcols/joinrighttcols.
+ */
+ JoinType jointype; /* type of join */
+ int joinmergedcols; /* number of merged (JOIN USING) columns */
+ List *joinaliasvars; /* list of alias-var expansions */
+ List *joinleftcols; /* left-side input column numbers */
+ List *joinrightcols; /* right-side input column numbers */
+
+ /*
+ * join_using_alias is an alias clause attached directly to JOIN/USING. It
+ * is different from the alias field (below) in that it does not hide the
+ * range variables of the tables being joined.
+ */
+ Alias *join_using_alias;
+
+ /*
+ * Fields valid for a function RTE (else NIL/zero):
+ *
+ * When funcordinality is true, the eref->colnames list includes an alias
+ * for the ordinality column. The ordinality column is otherwise
+ * implicit, and must be accounted for "by hand" in places such as
+ * expandRTE().
+ */
+ List *functions; /* list of RangeTblFunction nodes */
+ bool funcordinality; /* is this called WITH ORDINALITY? */
+
+ /*
+ * Fields valid for a TableFunc RTE (else NULL):
+ */
+ TableFunc *tablefunc;
+
+ /*
+ * Fields valid for a values RTE (else NIL):
+ */
+ List *values_lists; /* list of expression lists */
+
+ /*
+ * Fields valid for a CTE RTE (else NULL/zero):
+ */
+ char *ctename; /* name of the WITH list item */
+ Index ctelevelsup; /* number of query levels up */
+ bool self_reference; /* is this a recursive self-reference? */
+
+ /*
+ * Fields valid for CTE, VALUES, ENR, and TableFunc RTEs (else NIL):
+ *
+ * We need these for CTE RTEs so that the types of self-referential
+ * columns are well-defined. For VALUES RTEs, storing these explicitly
+ * saves having to re-determine the info by scanning the values_lists. For
+ * ENRs, we store the types explicitly here (we could get the information
+ * from the catalogs if 'relid' was supplied, but we'd still need these
+ * for TupleDesc-based ENRs, so we might as well always store the type
+ * info here). For TableFuncs, these fields are redundant with data in
+ * the TableFunc node, but keeping them here allows some code sharing with
+ * the other cases.
+ *
+ * For ENRs only, we have to consider the possibility of dropped columns.
+ * A dropped column is included in these lists, but it will have zeroes in
+ * all three lists (as well as an empty-string entry in eref). Testing
+ * for zero coltype is the standard way to detect a dropped column.
+ */
+ List *coltypes; /* OID list of column type OIDs */
+ List *coltypmods; /* integer list of column typmods */
+ List *colcollations; /* OID list of column collation OIDs */
+
+ /*
+ * Fields valid for ENR RTEs (else NULL/zero):
+ */
+ char *enrname; /* name of ephemeral named relation */
+ Cardinality enrtuples; /* estimated or actual from caller */
+
+ /*
+ * Fields valid in all RTEs:
+ */
+ Alias *alias; /* user-written alias clause, if any */
+ Alias *eref; /* expanded reference names */
+ bool lateral; /* subquery, function, or values is LATERAL? */
+ bool inh; /* inheritance requested? */
+ bool inFromCl; /* present in FROM clause? */
+ List *securityQuals; /* security barrier quals to apply, if any */
+} RangeTblEntry;
+
+/*
+ * RTEPermissionInfo
+ * Per-relation information for permission checking. Added to the Query
+ * node by the parser when adding the corresponding RTE to the query
+ * range table and subsequently editorialized on by the rewriter if
+ * needed after rule expansion.
+ *
+ * Only the relations directly mentioned in the query are checked for
+ * access permissions by the core executor, so only their RTEPermissionInfos
+ * are present in the Query. However, extensions may want to check inheritance
+ * children too, depending on the value of rte->inh, so it's copied in 'inh'
+ * for their perusal.
+ *
+ * requiredPerms and checkAsUser specify run-time access permissions checks
+ * to be performed at query startup. The user must have *all* of the
+ * permissions that are OR'd together in requiredPerms (never 0!). If
+ * checkAsUser is not zero, then do the permissions checks using the access
+ * rights of that user, not the current effective user ID. (This allows rules
+ * to act as setuid gateways.)
+ *
+ * For SELECT/INSERT/UPDATE permissions, if the user doesn't have table-wide
+ * permissions then it is sufficient to have the permissions on all columns
+ * identified in selectedCols (for SELECT) and/or insertedCols and/or
+ * updatedCols (INSERT with ON CONFLICT DO UPDATE may have all 3).
+ * selectedCols, insertedCols and updatedCols are bitmapsets, which cannot have
+ * negative integer members, so we subtract FirstLowInvalidHeapAttributeNumber
+ * from column numbers before storing them in these fields. A whole-row Var
+ * reference is represented by setting the bit for InvalidAttrNumber.
+ *
+ * updatedCols is also used in some other places, for example, to determine
+ * which triggers to fire and in FDWs to know which changed columns they need
+ * to ship off.
+ */
+typedef struct RTEPermissionInfo
+{
+ NodeTag type;
+
+ Oid relid; /* relation OID */
+ bool inh; /* separately check inheritance children? */
+ AclMode requiredPerms; /* bitmask of required access permissions */
+ Oid checkAsUser; /* if valid, check access as this role */
+ Bitmapset *selectedCols; /* columns needing SELECT permission */
+ Bitmapset *insertedCols; /* columns needing INSERT permission */
+ Bitmapset *updatedCols; /* columns needing UPDATE permission */
+} RTEPermissionInfo;
+
+/*
+ * RangeTblFunction -
+ * RangeTblEntry subsidiary data for one function in a FUNCTION RTE.
+ *
+ * If the function had a column definition list (required for an
+ * otherwise-unspecified RECORD result), funccolnames lists the names given
+ * in the definition list, funccoltypes lists their declared column types,
+ * funccoltypmods lists their typmods, funccolcollations their collations.
+ * Otherwise, those fields are NIL.
+ *
+ * Notice we don't attempt to store info about the results of functions
+ * returning named composite types, because those can change from time to
+ * time. We do however remember how many columns we thought the type had
+ * (including dropped columns!), so that we can successfully ignore any
+ * columns added after the query was parsed.
+ *
+ * The query jumbling only needs to track the function expression.
+ */
+typedef struct RangeTblFunction
+{
+ NodeTag type;
+
+ Node *funcexpr; /* expression tree for func call */
+ /* number of columns it contributes to RTE */
+ int funccolcount pg_node_attr(query_jumble_ignore);
+ /* These fields record the contents of a column definition list, if any: */
+ /* column names (list of String) */
+ List *funccolnames pg_node_attr(query_jumble_ignore);
+ /* OID list of column type OIDs */
+ List *funccoltypes pg_node_attr(query_jumble_ignore);
+ /* integer list of column typmods */
+ List *funccoltypmods pg_node_attr(query_jumble_ignore);
+ /* OID list of column collation OIDs */
+ List *funccolcollations pg_node_attr(query_jumble_ignore);
+
+ /* This is set during planning for use by the executor: */
+ /* PARAM_EXEC Param IDs affecting this func */
+ Bitmapset *funcparams pg_node_attr(query_jumble_ignore);
+} RangeTblFunction;
+
+/*
+ * TableSampleClause - TABLESAMPLE appearing in a transformed FROM clause
+ *
+ * Unlike RangeTableSample, this is a subnode of the relevant RangeTblEntry.
+ */
+typedef struct TableSampleClause
+{
+ NodeTag type;
+ Oid tsmhandler; /* OID of the tablesample handler function */
+ List *args; /* tablesample argument expression(s) */
+ Expr *repeatable; /* REPEATABLE expression, or NULL if none */
+} TableSampleClause;
+
+/*
+ * WithCheckOption -
+ * representation of WITH CHECK OPTION checks to be applied to new tuples
+ * when inserting/updating an auto-updatable view, or RLS WITH CHECK
+ * policies to be applied when inserting/updating a relation with RLS.
+ */
+typedef enum WCOKind
+{
+ WCO_VIEW_CHECK, /* WCO on an auto-updatable view */
+ WCO_RLS_INSERT_CHECK, /* RLS INSERT WITH CHECK policy */
+ WCO_RLS_UPDATE_CHECK, /* RLS UPDATE WITH CHECK policy */
+ WCO_RLS_CONFLICT_CHECK, /* RLS ON CONFLICT DO UPDATE USING policy */
+ WCO_RLS_MERGE_UPDATE_CHECK, /* RLS MERGE UPDATE USING policy */
+ WCO_RLS_MERGE_DELETE_CHECK /* RLS MERGE DELETE USING policy */
+} WCOKind;
+
+typedef struct WithCheckOption
+{
+ NodeTag type;
+ WCOKind kind; /* kind of WCO */
+ char *relname; /* name of relation that specified the WCO */
+ char *polname; /* name of RLS policy being checked */
+ Node *qual; /* constraint qual to check */
+ bool cascaded; /* true for a cascaded WCO on a view */
+} WithCheckOption;
+
+/*
+ * SortGroupClause -
+ * representation of ORDER BY, GROUP BY, PARTITION BY,
+ * DISTINCT, DISTINCT ON items
+ *
+ * You might think that ORDER BY is only interested in defining ordering,
+ * and GROUP/DISTINCT are only interested in defining equality. However,
+ * one way to implement grouping is to sort and then apply a "uniq"-like
+ * filter. So it's also interesting to keep track of possible sort operators
+ * for GROUP/DISTINCT, and in particular to try to sort for the grouping
+ * in a way that will also yield a requested ORDER BY ordering. So we need
+ * to be able to compare ORDER BY and GROUP/DISTINCT lists, which motivates
+ * the decision to give them the same representation.
+ *
+ * tleSortGroupRef must match ressortgroupref of exactly one entry of the
+ * query's targetlist; that is the expression to be sorted or grouped by.
+ * eqop is the OID of the equality operator.
+ * sortop is the OID of the ordering operator (a "<" or ">" operator),
+ * or InvalidOid if not available.
+ * nulls_first means about what you'd expect. If sortop is InvalidOid
+ * then nulls_first is meaningless and should be set to false.
+ * hashable is true if eqop is hashable (note this condition also depends
+ * on the datatype of the input expression).
+ *
+ * In an ORDER BY item, all fields must be valid. (The eqop isn't essential
+ * here, but it's cheap to get it along with the sortop, and requiring it
+ * to be valid eases comparisons to grouping items.) Note that this isn't
+ * actually enough information to determine an ordering: if the sortop is
+ * collation-sensitive, a collation OID is needed too. We don't store the
+ * collation in SortGroupClause because it's not available at the time the
+ * parser builds the SortGroupClause; instead, consult the exposed collation
+ * of the referenced targetlist expression to find out what it is.
+ *
+ * In a grouping item, eqop must be valid. If the eqop is a btree equality
+ * operator, then sortop should be set to a compatible ordering operator.
+ * We prefer to set eqop/sortop/nulls_first to match any ORDER BY item that
+ * the query presents for the same tlist item. If there is none, we just
+ * use the default ordering op for the datatype.
+ *
+ * If the tlist item's type has a hash opclass but no btree opclass, then
+ * we will set eqop to the hash equality operator, sortop to InvalidOid,
+ * and nulls_first to false. A grouping item of this kind can only be
+ * implemented by hashing, and of course it'll never match an ORDER BY item.
+ *
+ * The hashable flag is provided since we generally have the requisite
+ * information readily available when the SortGroupClause is constructed,
+ * and it's relatively expensive to get it again later. Note there is no
+ * need for a "sortable" flag since OidIsValid(sortop) serves the purpose.
+ *
+ * A query might have both ORDER BY and DISTINCT (or DISTINCT ON) clauses.
+ * In SELECT DISTINCT, the distinctClause list is as long or longer than the
+ * sortClause list, while in SELECT DISTINCT ON it's typically shorter.
+ * The two lists must match up to the end of the shorter one --- the parser
+ * rearranges the distinctClause if necessary to make this true. (This
+ * restriction ensures that only one sort step is needed to both satisfy the
+ * ORDER BY and set up for the Unique step. This is semantically necessary
+ * for DISTINCT ON, and presents no real drawback for DISTINCT.)
+ */
+typedef struct SortGroupClause
+{
+ NodeTag type;
+ Index tleSortGroupRef; /* reference into targetlist */
+ Oid eqop; /* the equality operator ('=' op) */
+ Oid sortop; /* the ordering operator ('<' op), or 0 */
+ bool nulls_first; /* do NULLs come before normal values? */
+ /* can eqop be implemented by hashing? */
+ bool hashable pg_node_attr(query_jumble_ignore);
+} SortGroupClause;
+
+/*
+ * GroupingSet -
+ * representation of CUBE, ROLLUP and GROUPING SETS clauses
+ *
+ * In a Query with grouping sets, the groupClause contains a flat list of
+ * SortGroupClause nodes for each distinct expression used. The actual
+ * structure of the GROUP BY clause is given by the groupingSets tree.
+ *
+ * In the raw parser output, GroupingSet nodes (of all types except SIMPLE
+ * which is not used) are potentially mixed in with the expressions in the
+ * groupClause of the SelectStmt. (An expression can't contain a GroupingSet,
+ * but a list may mix GroupingSet and expression nodes.) At this stage, the
+ * content of each node is a list of expressions, some of which may be RowExprs
+ * which represent sublists rather than actual row constructors, and nested
+ * GroupingSet nodes where legal in the grammar. The structure directly
+ * reflects the query syntax.
+ *
+ * In parse analysis, the transformed expressions are used to build the tlist
+ * and groupClause list (of SortGroupClause nodes), and the groupingSets tree
+ * is eventually reduced to a fixed format:
+ *
+ * EMPTY nodes represent (), and obviously have no content
+ *
+ * SIMPLE nodes represent a list of one or more expressions to be treated as an
+ * atom by the enclosing structure; the content is an integer list of
+ * ressortgroupref values (see SortGroupClause)
+ *
+ * CUBE and ROLLUP nodes contain a list of one or more SIMPLE nodes.
+ *
+ * SETS nodes contain a list of EMPTY, SIMPLE, CUBE or ROLLUP nodes, but after
+ * parse analysis they cannot contain more SETS nodes; enough of the syntactic
+ * transforms of the spec have been applied that we no longer have arbitrarily
+ * deep nesting (though we still preserve the use of cube/rollup).
+ *
+ * Note that if the groupingSets tree contains no SIMPLE nodes (only EMPTY
+ * nodes at the leaves), then the groupClause will be empty, but this is still
+ * an aggregation query (similar to using aggs or HAVING without GROUP BY).
+ *
+ * As an example, the following clause:
+ *
+ * GROUP BY GROUPING SETS ((a,b), CUBE(c,(d,e)))
+ *
+ * looks like this after raw parsing:
+ *
+ * SETS( RowExpr(a,b) , CUBE( c, RowExpr(d,e) ) )
+ *
+ * and parse analysis converts it to:
+ *
+ * SETS( SIMPLE(1,2), CUBE( SIMPLE(3), SIMPLE(4,5) ) )
+ */
+typedef enum GroupingSetKind
+{
+ GROUPING_SET_EMPTY,
+ GROUPING_SET_SIMPLE,
+ GROUPING_SET_ROLLUP,
+ GROUPING_SET_CUBE,
+ GROUPING_SET_SETS
+} GroupingSetKind;
+
+typedef struct GroupingSet
+{
+ NodeTag type;
+ GroupingSetKind kind pg_node_attr(query_jumble_ignore);
+ List *content;
+ int location;
+} GroupingSet;
+
+/*
+ * WindowClause -
+ * transformed representation of WINDOW and OVER clauses
+ *
+ * A parsed Query's windowClause list contains these structs. "name" is set
+ * if the clause originally came from WINDOW, and is NULL if it originally
+ * was an OVER clause (but note that we collapse out duplicate OVERs).
+ * partitionClause and orderClause are lists of SortGroupClause structs.
+ * If we have RANGE with offset PRECEDING/FOLLOWING, the semantics of that are
+ * specified by startInRangeFunc/inRangeColl/inRangeAsc/inRangeNullsFirst
+ * for the start offset, or endInRangeFunc/inRange* for the end offset.
+ * winref is an ID number referenced by WindowFunc nodes; it must be unique
+ * among the members of a Query's windowClause list.
+ * When refname isn't null, the partitionClause is always copied from there;
+ * the orderClause might or might not be copied (see copiedOrder); the framing
+ * options are never copied, per spec.
+ *
+ * The information relevant for the query jumbling is the partition clause
+ * type and its bounds.
+ */
+typedef struct WindowClause
+{
+ NodeTag type;
+ /* window name (NULL in an OVER clause) */
+ char *name pg_node_attr(query_jumble_ignore);
+ /* referenced window name, if any */
+ char *refname pg_node_attr(query_jumble_ignore);
+ List *partitionClause; /* PARTITION BY list */
+ /* ORDER BY list */
+ List *orderClause;
+ int frameOptions; /* frame_clause options, see WindowDef */
+ Node *startOffset; /* expression for starting bound, if any */
+ Node *endOffset; /* expression for ending bound, if any */
+ /* qual to help short-circuit execution */
+ List *runCondition pg_node_attr(query_jumble_ignore);
+ /* in_range function for startOffset */
+ Oid startInRangeFunc pg_node_attr(query_jumble_ignore);
+ /* in_range function for endOffset */
+ Oid endInRangeFunc pg_node_attr(query_jumble_ignore);
+ /* collation for in_range tests */
+ Oid inRangeColl pg_node_attr(query_jumble_ignore);
+ /* use ASC sort order for in_range tests? */
+ bool inRangeAsc pg_node_attr(query_jumble_ignore);
+ /* nulls sort first for in_range tests? */
+ bool inRangeNullsFirst pg_node_attr(query_jumble_ignore);
+ Index winref; /* ID referenced by window functions */
+ /* did we copy orderClause from refname? */
+ bool copiedOrder pg_node_attr(query_jumble_ignore);
+} WindowClause;
+
+/*
+ * RowMarkClause -
+ * parser output representation of FOR [KEY] UPDATE/SHARE clauses
+ *
+ * Query.rowMarks contains a separate RowMarkClause node for each relation
+ * identified as a FOR [KEY] UPDATE/SHARE target. If one of these clauses
+ * is applied to a subquery, we generate RowMarkClauses for all normal and
+ * subquery rels in the subquery, but they are marked pushedDown = true to
+ * distinguish them from clauses that were explicitly written at this query
+ * level. Also, Query.hasForUpdate tells whether there were explicit FOR
+ * UPDATE/SHARE/KEY SHARE clauses in the current query level.
+ */
+typedef struct RowMarkClause
+{
+ NodeTag type;
+ Index rti; /* range table index of target relation */
+ LockClauseStrength strength;
+ LockWaitPolicy waitPolicy; /* NOWAIT and SKIP LOCKED */
+ bool pushedDown; /* pushed down from higher query level? */
+} RowMarkClause;
+
+/*
+ * WithClause -
+ * representation of WITH clause
+ *
+ * Note: WithClause does not propagate into the Query representation;
+ * but CommonTableExpr does.
+ */
+typedef struct WithClause
+{
+ NodeTag type;
+ List *ctes; /* list of CommonTableExprs */
+ bool recursive; /* true = WITH RECURSIVE */
+ int location; /* token location, or -1 if unknown */
+} WithClause;
+
+/*
+ * InferClause -
+ * ON CONFLICT unique index inference clause
+ *
+ * Note: InferClause does not propagate into the Query representation.
+ */
+typedef struct InferClause
+{
+ NodeTag type;
+ List *indexElems; /* IndexElems to infer unique index */
+ Node *whereClause; /* qualification (partial-index predicate) */
+ char *conname; /* Constraint name, or NULL if unnamed */
+ int location; /* token location, or -1 if unknown */
+} InferClause;
+
+/*
+ * OnConflictClause -
+ * representation of ON CONFLICT clause
+ *
+ * Note: OnConflictClause does not propagate into the Query representation.
+ */
+typedef struct OnConflictClause
+{
+ NodeTag type;
+ OnConflictAction action; /* DO NOTHING or UPDATE? */
+ InferClause *infer; /* Optional index inference clause */
+ List *targetList; /* the target list (of ResTarget) */
+ Node *whereClause; /* qualifications */
+ int location; /* token location, or -1 if unknown */
+} OnConflictClause;
+
+/*
+ * CommonTableExpr -
+ * representation of WITH list element
+ */
+
+typedef enum CTEMaterialize
+{
+ CTEMaterializeDefault, /* no option specified */
+ CTEMaterializeAlways, /* MATERIALIZED */
+ CTEMaterializeNever /* NOT MATERIALIZED */
+} CTEMaterialize;
+
+typedef struct CTESearchClause
+{
+ NodeTag type;
+ List *search_col_list;
+ bool search_breadth_first;
+ char *search_seq_column;
+ int location;
+} CTESearchClause;
+
+typedef struct CTECycleClause
+{
+ NodeTag type;
+ List *cycle_col_list;
+ char *cycle_mark_column;
+ Node *cycle_mark_value;
+ Node *cycle_mark_default;
+ char *cycle_path_column;
+ int location;
+ /* These fields are set during parse analysis: */
+ Oid cycle_mark_type; /* common type of _value and _default */
+ int cycle_mark_typmod;
+ Oid cycle_mark_collation;
+ Oid cycle_mark_neop; /* <> operator for type */
+} CTECycleClause;
+
+typedef struct CommonTableExpr
+{
+ NodeTag type;
+
+ /*
+ * Query name (never qualified). The string name is included in the query
+ * jumbling because RTE_CTE RTEs need it.
+ */
+ char *ctename;
+ /* optional list of column names */
+ List *aliascolnames pg_node_attr(query_jumble_ignore);
+ CTEMaterialize ctematerialized; /* is this an optimization fence? */
+ /* SelectStmt/InsertStmt/etc before parse analysis, Query afterwards: */
+ Node *ctequery; /* the CTE's subquery */
+ CTESearchClause *search_clause pg_node_attr(query_jumble_ignore);
+ CTECycleClause *cycle_clause pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+ /* These fields are set during parse analysis: */
+ /* is this CTE actually recursive? */
+ bool cterecursive pg_node_attr(query_jumble_ignore);
+
+ /*
+ * Number of RTEs referencing this CTE (excluding internal
+ * self-references), irrelevant for query jumbling.
+ */
+ int cterefcount pg_node_attr(query_jumble_ignore);
+ /* list of output column names */
+ List *ctecolnames pg_node_attr(query_jumble_ignore);
+ /* OID list of output column type OIDs */
+ List *ctecoltypes pg_node_attr(query_jumble_ignore);
+ /* integer list of output column typmods */
+ List *ctecoltypmods pg_node_attr(query_jumble_ignore);
+ /* OID list of column collation OIDs */
+ List *ctecolcollations pg_node_attr(query_jumble_ignore);
+} CommonTableExpr;
+
+/* Convenience macro to get the output tlist of a CTE's query */
+#define GetCTETargetList(cte) \
+ (AssertMacro(IsA((cte)->ctequery, Query)), \
+ ((Query *) (cte)->ctequery)->commandType == CMD_SELECT ? \
+ ((Query *) (cte)->ctequery)->targetList : \
+ ((Query *) (cte)->ctequery)->returningList)
+
+/*
+ * MergeWhenClause -
+ * raw parser representation of a WHEN clause in a MERGE statement
+ *
+ * This is transformed into MergeAction by parse analysis
+ */
+typedef struct MergeWhenClause
+{
+ NodeTag type;
+ bool matched; /* true=MATCHED, false=NOT MATCHED */
+ CmdType commandType; /* INSERT/UPDATE/DELETE/DO NOTHING */
+ OverridingKind override; /* OVERRIDING clause */
+ Node *condition; /* WHEN conditions (raw parser) */
+ List *targetList; /* INSERT/UPDATE targetlist */
+ /* the following members are only used in INSERT actions */
+ List *values; /* VALUES to INSERT, or NULL */
+} MergeWhenClause;
+
+/*
+ * MergeAction -
+ * Transformed representation of a WHEN clause in a MERGE statement
+ */
+typedef struct MergeAction
+{
+ NodeTag type;
+ bool matched; /* true=MATCHED, false=NOT MATCHED */
+ CmdType commandType; /* INSERT/UPDATE/DELETE/DO NOTHING */
+ /* OVERRIDING clause */
+ OverridingKind override pg_node_attr(query_jumble_ignore);
+ Node *qual; /* transformed WHEN conditions */
+ List *targetList; /* the target list (of TargetEntry) */
+ /* target attribute numbers of an UPDATE */
+ List *updateColnos pg_node_attr(query_jumble_ignore);
+} MergeAction;
+
+/*
+ * TriggerTransition -
+ * representation of transition row or table naming clause
+ *
+ * Only transition tables are initially supported in the syntax, and only for
+ * AFTER triggers, but other permutations are accepted by the parser so we can
+ * give a meaningful message from C code.
+ */
+typedef struct TriggerTransition
+{
+ NodeTag type;
+ char *name;
+ bool isNew;
+ bool isTable;
+} TriggerTransition;
+
+/* Nodes for SQL/JSON support */
+
+/*
+ * JsonOutput -
+ * representation of JSON output clause (RETURNING type [FORMAT format])
+ */
+typedef struct JsonOutput
+{
+ NodeTag type;
+ TypeName *typeName; /* RETURNING type name, if specified */
+ JsonReturning *returning; /* RETURNING FORMAT clause and type Oids */
+} JsonOutput;
+
+/*
+ * JsonKeyValue -
+ * untransformed representation of JSON object key-value pair for
+ * JSON_OBJECT() and JSON_OBJECTAGG()
+ */
+typedef struct JsonKeyValue
+{
+ NodeTag type;
+ Expr *key; /* key expression */
+ JsonValueExpr *value; /* JSON value expression */
+} JsonKeyValue;
+
+/*
+ * JsonObjectConstructor -
+ * untransformed representation of JSON_OBJECT() constructor
+ */
+typedef struct JsonObjectConstructor
+{
+ NodeTag type;
+ List *exprs; /* list of JsonKeyValue pairs */
+ JsonOutput *output; /* RETURNING clause, if specified */
+ bool absent_on_null; /* skip NULL values? */
+ bool unique; /* check key uniqueness? */
+ int location; /* token location, or -1 if unknown */
+} JsonObjectConstructor;
+
+/*
+ * JsonArrayConstructor -
+ * untransformed representation of JSON_ARRAY(element,...) constructor
+ */
+typedef struct JsonArrayConstructor
+{
+ NodeTag type;
+ List *exprs; /* list of JsonValueExpr elements */
+ JsonOutput *output; /* RETURNING clause, if specified */
+ bool absent_on_null; /* skip NULL elements? */
+ int location; /* token location, or -1 if unknown */
+} JsonArrayConstructor;
+
+/*
+ * JsonArrayQueryConstructor -
+ * untransformed representation of JSON_ARRAY(subquery) constructor
+ */
+typedef struct JsonArrayQueryConstructor
+{
+ NodeTag type;
+ Node *query; /* subquery */
+ JsonOutput *output; /* RETURNING clause, if specified */
+ JsonFormat *format; /* FORMAT clause for subquery, if specified */
+ bool absent_on_null; /* skip NULL elements? */
+ int location; /* token location, or -1 if unknown */
+} JsonArrayQueryConstructor;
+
+/*
+ * JsonAggConstructor -
+ * common fields of untransformed representation of
+ * JSON_ARRAYAGG() and JSON_OBJECTAGG()
+ */
+typedef struct JsonAggConstructor
+{
+ NodeTag type;
+ JsonOutput *output; /* RETURNING clause, if any */
+ Node *agg_filter; /* FILTER clause, if any */
+ List *agg_order; /* ORDER BY clause, if any */
+ struct WindowDef *over; /* OVER clause, if any */
+ int location; /* token location, or -1 if unknown */
+} JsonAggConstructor;
+
+/*
+ * JsonObjectAgg -
+ * untransformed representation of JSON_OBJECTAGG()
+ */
+typedef struct JsonObjectAgg
+{
+ NodeTag type;
+ JsonAggConstructor *constructor; /* common fields */
+ JsonKeyValue *arg; /* object key-value pair */
+ bool absent_on_null; /* skip NULL values? */
+ bool unique; /* check key uniqueness? */
+} JsonObjectAgg;
+
+/*
+ * JsonArrayAgg -
+ * untransformed representation of JSON_ARRAYAGG()
+ */
+typedef struct JsonArrayAgg
+{
+ NodeTag type;
+ JsonAggConstructor *constructor; /* common fields */
+ JsonValueExpr *arg; /* array element expression */
+ bool absent_on_null; /* skip NULL elements? */
+} JsonArrayAgg;
+
+
+/*****************************************************************************
+ * Raw Grammar Output Statements
+ *****************************************************************************/
+
+/*
+ * RawStmt --- container for any one statement's raw parse tree
+ *
+ * Parse analysis converts a raw parse tree headed by a RawStmt node into
+ * an analyzed statement headed by a Query node. For optimizable statements,
+ * the conversion is complex. For utility statements, the parser usually just
+ * transfers the raw parse tree (sans RawStmt) into the utilityStmt field of
+ * the Query node, and all the useful work happens at execution time.
+ *
+ * stmt_location/stmt_len identify the portion of the source text string
+ * containing this raw statement (useful for multi-statement strings).
+ *
+ * This is irrelevant for query jumbling, as this is not used in parsed
+ * queries.
+ */
+typedef struct RawStmt
+{
+ pg_node_attr(no_query_jumble)
+
+ NodeTag type;
+ Node *stmt; /* raw parse tree */
+ int stmt_location; /* start location, or -1 if unknown */
+ int stmt_len; /* length in bytes; 0 means "rest of string" */
+} RawStmt;
+
+/*****************************************************************************
+ * Optimizable Statements
+ *****************************************************************************/
+
+/* ----------------------
+ * Insert Statement
+ *
+ * The source expression is represented by SelectStmt for both the
+ * SELECT and VALUES cases. If selectStmt is NULL, then the query
+ * is INSERT ... DEFAULT VALUES.
+ * ----------------------
+ */
+typedef struct InsertStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* relation to insert into */
+ List *cols; /* optional: names of the target columns */
+ Node *selectStmt; /* the source SELECT/VALUES, or NULL */
+ OnConflictClause *onConflictClause; /* ON CONFLICT clause */
+ List *returningList; /* list of expressions to return */
+ WithClause *withClause; /* WITH clause */
+ OverridingKind override; /* OVERRIDING clause */
+} InsertStmt;
+
+/* ----------------------
+ * Delete Statement
+ * ----------------------
+ */
+typedef struct DeleteStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* relation to delete from */
+ List *usingClause; /* optional using clause for more tables */
+ Node *whereClause; /* qualifications */
+ List *returningList; /* list of expressions to return */
+ WithClause *withClause; /* WITH clause */
+} DeleteStmt;
+
+/* ----------------------
+ * Update Statement
+ * ----------------------
+ */
+typedef struct UpdateStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* relation to update */
+ List *targetList; /* the target list (of ResTarget) */
+ Node *whereClause; /* qualifications */
+ List *fromClause; /* optional from clause for more tables */
+ List *returningList; /* list of expressions to return */
+ WithClause *withClause; /* WITH clause */
+} UpdateStmt;
+
+/* ----------------------
+ * Merge Statement
+ * ----------------------
+ */
+typedef struct MergeStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* target relation to merge into */
+ Node *sourceRelation; /* source relation */
+ Node *joinCondition; /* join condition between source and target */
+ List *mergeWhenClauses; /* list of MergeWhenClause(es) */
+ WithClause *withClause; /* WITH clause */
+} MergeStmt;
+
+/* ----------------------
+ * Select Statement
+ *
+ * A "simple" SELECT is represented in the output of gram.y by a single
+ * SelectStmt node; so is a VALUES construct. A query containing set
+ * operators (UNION, INTERSECT, EXCEPT) is represented by a tree of SelectStmt
+ * nodes, in which the leaf nodes are component SELECTs and the internal nodes
+ * represent UNION, INTERSECT, or EXCEPT operators. Using the same node
+ * type for both leaf and internal nodes allows gram.y to stick ORDER BY,
+ * LIMIT, etc, clause values into a SELECT statement without worrying
+ * whether it is a simple or compound SELECT.
+ * ----------------------
+ */
+typedef enum SetOperation
+{
+ SETOP_NONE = 0,
+ SETOP_UNION,
+ SETOP_INTERSECT,
+ SETOP_EXCEPT
+} SetOperation;
+
+typedef struct SelectStmt
+{
+ NodeTag type;
+
+ /*
+ * These fields are used only in "leaf" SelectStmts.
+ */
+ List *distinctClause; /* NULL, list of DISTINCT ON exprs, or
+ * lcons(NIL,NIL) for all (SELECT DISTINCT) */
+ IntoClause *intoClause; /* target for SELECT INTO */
+ List *targetList; /* the target list (of ResTarget) */
+ List *fromClause; /* the FROM clause */
+ Node *whereClause; /* WHERE qualification */
+ List *groupClause; /* GROUP BY clauses */
+ bool groupDistinct; /* Is this GROUP BY DISTINCT? */
+ Node *havingClause; /* HAVING conditional-expression */
+ List *windowClause; /* WINDOW window_name AS (...), ... */
+
+ /*
+ * In a "leaf" node representing a VALUES list, the above fields are all
+ * null, and instead this field is set. Note that the elements of the
+ * sublists are just expressions, without ResTarget decoration. Also note
+ * that a list element can be DEFAULT (represented as a SetToDefault
+ * node), regardless of the context of the VALUES list. It's up to parse
+ * analysis to reject that where not valid.
+ */
+ List *valuesLists; /* untransformed list of expression lists */
+
+ /*
+ * These fields are used in both "leaf" SelectStmts and upper-level
+ * SelectStmts.
+ */
+ List *sortClause; /* sort clause (a list of SortBy's) */
+ Node *limitOffset; /* # of result tuples to skip */
+ Node *limitCount; /* # of result tuples to return */
+ LimitOption limitOption; /* limit type */
+ List *lockingClause; /* FOR UPDATE (list of LockingClause's) */
+ WithClause *withClause; /* WITH clause */
+
+ /*
+ * These fields are used only in upper-level SelectStmts.
+ */
+ SetOperation op; /* type of set op */
+ bool all; /* ALL specified? */
+ struct SelectStmt *larg; /* left child */
+ struct SelectStmt *rarg; /* right child */
+ /* Eventually add fields for CORRESPONDING spec here */
+} SelectStmt;
+
+
+/* ----------------------
+ * Set Operation node for post-analysis query trees
+ *
+ * After parse analysis, a SELECT with set operations is represented by a
+ * top-level Query node containing the leaf SELECTs as subqueries in its
+ * range table. Its setOperations field shows the tree of set operations,
+ * with leaf SelectStmt nodes replaced by RangeTblRef nodes, and internal
+ * nodes replaced by SetOperationStmt nodes. Information about the output
+ * column types is added, too. (Note that the child nodes do not necessarily
+ * produce these types directly, but we've checked that their output types
+ * can be coerced to the output column type.) Also, if it's not UNION ALL,
+ * information about the types' sort/group semantics is provided in the form
+ * of a SortGroupClause list (same representation as, eg, DISTINCT).
+ * The resolved common column collations are provided too; but note that if
+ * it's not UNION ALL, it's okay for a column to not have a common collation,
+ * so a member of the colCollations list could be InvalidOid even though the
+ * column has a collatable type.
+ * ----------------------
+ */
+typedef struct SetOperationStmt
+{
+ NodeTag type;
+ SetOperation op; /* type of set op */
+ bool all; /* ALL specified? */
+ Node *larg; /* left child */
+ Node *rarg; /* right child */
+ /* Eventually add fields for CORRESPONDING spec here */
+
+ /* Fields derived during parse analysis (irrelevant for query jumbling): */
+ /* OID list of output column type OIDs */
+ List *colTypes pg_node_attr(query_jumble_ignore);
+ /* integer list of output column typmods */
+ List *colTypmods pg_node_attr(query_jumble_ignore);
+ /* OID list of output column collation OIDs */
+ List *colCollations pg_node_attr(query_jumble_ignore);
+ /* a list of SortGroupClause's */
+ List *groupClauses pg_node_attr(query_jumble_ignore);
+ /* groupClauses is NIL if UNION ALL, but must be set otherwise */
+} SetOperationStmt;
+
+
+/*
+ * RETURN statement (inside SQL function body)
+ */
+typedef struct ReturnStmt
+{
+ NodeTag type;
+ Node *returnval;
+} ReturnStmt;
+
+
+/* ----------------------
+ * PL/pgSQL Assignment Statement
+ *
+ * Like SelectStmt, this is transformed into a SELECT Query.
+ * However, the targetlist of the result looks more like an UPDATE.
+ * ----------------------
+ */
+typedef struct PLAssignStmt
+{
+ NodeTag type;
+
+ char *name; /* initial column name */
+ List *indirection; /* subscripts and field names, if any */
+ int nnames; /* number of names to use in ColumnRef */
+ SelectStmt *val; /* the PL/pgSQL expression to assign */
+ int location; /* name's token location, or -1 if unknown */
+} PLAssignStmt;
+
+
+/*****************************************************************************
+ * Other Statements (no optimizations required)
+ *
+ * These are not touched by parser/analyze.c except to put them into
+ * the utilityStmt field of a Query. This is eventually passed to
+ * ProcessUtility (by-passing rewriting and planning). Some of the
+ * statements do need attention from parse analysis, and this is
+ * done by routines in parser/parse_utilcmd.c after ProcessUtility
+ * receives the command for execution.
+ * DECLARE CURSOR, EXPLAIN, and CREATE TABLE AS are special cases:
+ * they contain optimizable statements, which get processed normally
+ * by parser/analyze.c.
+ *****************************************************************************/
+
+/*
+ * When a command can act on several kinds of objects with only one
+ * parse structure required, use these constants to designate the
+ * object type. Note that commands typically don't support all the types.
+ */
+
+typedef enum ObjectType
+{
+ OBJECT_ACCESS_METHOD,
+ OBJECT_AGGREGATE,
+ OBJECT_AMOP,
+ OBJECT_AMPROC,
+ OBJECT_ATTRIBUTE, /* type's attribute, when distinct from column */
+ OBJECT_CAST,
+ OBJECT_COLUMN,
+ OBJECT_COLLATION,
+ OBJECT_CONVERSION,
+ OBJECT_DATABASE,
+ OBJECT_DEFAULT,
+ OBJECT_DEFACL,
+ OBJECT_DOMAIN,
+ OBJECT_DOMCONSTRAINT,
+ OBJECT_EVENT_TRIGGER,
+ OBJECT_EXTENSION,
+ OBJECT_FDW,
+ OBJECT_FOREIGN_SERVER,
+ OBJECT_FOREIGN_TABLE,
+ OBJECT_FUNCTION,
+ OBJECT_INDEX,
+ OBJECT_LANGUAGE,
+ OBJECT_LARGEOBJECT,
+ OBJECT_MATVIEW,
+ OBJECT_OPCLASS,
+ OBJECT_OPERATOR,
+ OBJECT_OPFAMILY,
+ OBJECT_PARAMETER_ACL,
+ OBJECT_POLICY,
+ OBJECT_PROCEDURE,
+ OBJECT_PUBLICATION,
+ OBJECT_PUBLICATION_NAMESPACE,
+ OBJECT_PUBLICATION_REL,
+ OBJECT_ROLE,
+ OBJECT_ROUTINE,
+ OBJECT_RULE,
+ OBJECT_SCHEMA,
+ OBJECT_SEQUENCE,
+ OBJECT_SUBSCRIPTION,
+ OBJECT_STATISTIC_EXT,
+ OBJECT_TABCONSTRAINT,
+ OBJECT_TABLE,
+ OBJECT_TABLESPACE,
+ OBJECT_TRANSFORM,
+ OBJECT_TRIGGER,
+ OBJECT_TSCONFIGURATION,
+ OBJECT_TSDICTIONARY,
+ OBJECT_TSPARSER,
+ OBJECT_TSTEMPLATE,
+ OBJECT_TYPE,
+ OBJECT_USER_MAPPING,
+ OBJECT_VIEW
+} ObjectType;
+
+/* ----------------------
+ * Create Schema Statement
+ *
+ * NOTE: the schemaElts list contains raw parsetrees for component statements
+ * of the schema, such as CREATE TABLE, GRANT, etc. These are analyzed and
+ * executed after the schema itself is created.
+ * ----------------------
+ */
+typedef struct CreateSchemaStmt
+{
+ NodeTag type;
+ char *schemaname; /* the name of the schema to create */
+ RoleSpec *authrole; /* the owner of the created schema */
+ List *schemaElts; /* schema components (list of parsenodes) */
+ bool if_not_exists; /* just do nothing if schema already exists? */
+} CreateSchemaStmt;
+
+typedef enum DropBehavior
+{
+ DROP_RESTRICT, /* drop fails if any dependent objects */
+ DROP_CASCADE /* remove dependent objects too */
+} DropBehavior;
+
+/* ----------------------
+ * Alter Table
+ * ----------------------
+ */
+typedef struct AlterTableStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* table to work on */
+ List *cmds; /* list of subcommands */
+ ObjectType objtype; /* type of object */
+ bool missing_ok; /* skip error if table missing */
+} AlterTableStmt;
+
+typedef enum AlterTableType
+{
+ AT_AddColumn, /* add column */
+ AT_AddColumnToView, /* implicitly via CREATE OR REPLACE VIEW */
+ AT_ColumnDefault, /* alter column default */
+ AT_CookedColumnDefault, /* add a pre-cooked column default */
+ AT_DropNotNull, /* alter column drop not null */
+ AT_SetNotNull, /* alter column set not null */
+ AT_DropExpression, /* alter column drop expression */
+ AT_CheckNotNull, /* check column is already marked not null */
+ AT_SetStatistics, /* alter column set statistics */
+ AT_SetOptions, /* alter column set ( options ) */
+ AT_ResetOptions, /* alter column reset ( options ) */
+ AT_SetStorage, /* alter column set storage */
+ AT_SetCompression, /* alter column set compression */
+ AT_DropColumn, /* drop column */
+ AT_AddIndex, /* add index */
+ AT_ReAddIndex, /* internal to commands/tablecmds.c */
+ AT_AddConstraint, /* add constraint */
+ AT_ReAddConstraint, /* internal to commands/tablecmds.c */
+ AT_ReAddDomainConstraint, /* internal to commands/tablecmds.c */
+ AT_AlterConstraint, /* alter constraint */
+ AT_ValidateConstraint, /* validate constraint */
+ AT_AddIndexConstraint, /* add constraint using existing index */
+ AT_DropConstraint, /* drop constraint */
+ AT_ReAddComment, /* internal to commands/tablecmds.c */
+ AT_AlterColumnType, /* alter column type */
+ AT_AlterColumnGenericOptions, /* alter column OPTIONS (...) */
+ AT_ChangeOwner, /* change owner */
+ AT_ClusterOn, /* CLUSTER ON */
+ AT_DropCluster, /* SET WITHOUT CLUSTER */
+ AT_SetLogged, /* SET LOGGED */
+ AT_SetUnLogged, /* SET UNLOGGED */
+ AT_DropOids, /* SET WITHOUT OIDS */
+ AT_SetAccessMethod, /* SET ACCESS METHOD */
+ AT_SetTableSpace, /* SET TABLESPACE */
+ AT_SetRelOptions, /* SET (...) -- AM specific parameters */
+ AT_ResetRelOptions, /* RESET (...) -- AM specific parameters */
+ AT_ReplaceRelOptions, /* replace reloption list in its entirety */
+ AT_EnableTrig, /* ENABLE TRIGGER name */
+ AT_EnableAlwaysTrig, /* ENABLE ALWAYS TRIGGER name */
+ AT_EnableReplicaTrig, /* ENABLE REPLICA TRIGGER name */
+ AT_DisableTrig, /* DISABLE TRIGGER name */
+ AT_EnableTrigAll, /* ENABLE TRIGGER ALL */
+ AT_DisableTrigAll, /* DISABLE TRIGGER ALL */
+ AT_EnableTrigUser, /* ENABLE TRIGGER USER */
+ AT_DisableTrigUser, /* DISABLE TRIGGER USER */
+ AT_EnableRule, /* ENABLE RULE name */
+ AT_EnableAlwaysRule, /* ENABLE ALWAYS RULE name */
+ AT_EnableReplicaRule, /* ENABLE REPLICA RULE name */
+ AT_DisableRule, /* DISABLE RULE name */
+ AT_AddInherit, /* INHERIT parent */
+ AT_DropInherit, /* NO INHERIT parent */
+ AT_AddOf, /* OF */
+ AT_DropOf, /* NOT OF */
+ AT_ReplicaIdentity, /* REPLICA IDENTITY */
+ AT_EnableRowSecurity, /* ENABLE ROW SECURITY */
+ AT_DisableRowSecurity, /* DISABLE ROW SECURITY */
+ AT_ForceRowSecurity, /* FORCE ROW SECURITY */
+ AT_NoForceRowSecurity, /* NO FORCE ROW SECURITY */
+ AT_GenericOptions, /* OPTIONS (...) */
+ AT_AttachPartition, /* ATTACH PARTITION */
+ AT_DetachPartition, /* DETACH PARTITION */
+ AT_DetachPartitionFinalize, /* DETACH PARTITION FINALIZE */
+ AT_AddIdentity, /* ADD IDENTITY */
+ AT_SetIdentity, /* SET identity column options */
+ AT_DropIdentity, /* DROP IDENTITY */
+ AT_ReAddStatistics /* internal to commands/tablecmds.c */
+} AlterTableType;
+
+typedef struct ReplicaIdentityStmt
+{
+ NodeTag type;
+ char identity_type;
+ char *name;
+} ReplicaIdentityStmt;
+
+typedef struct AlterTableCmd /* one subcommand of an ALTER TABLE */
+{
+ NodeTag type;
+ AlterTableType subtype; /* Type of table alteration to apply */
+ char *name; /* column, constraint, or trigger to act on,
+ * or tablespace */
+ int16 num; /* attribute number for columns referenced by
+ * number */
+ RoleSpec *newowner;
+ Node *def; /* definition of new column, index,
+ * constraint, or parent table */
+ DropBehavior behavior; /* RESTRICT or CASCADE for DROP cases */
+ bool missing_ok; /* skip error if missing? */
+ bool recurse; /* exec-time recursion */
+} AlterTableCmd;
+
+
+/* ----------------------
+ * Alter Collation
+ * ----------------------
+ */
+typedef struct AlterCollationStmt
+{
+ NodeTag type;
+ List *collname;
+} AlterCollationStmt;
+
+
+/* ----------------------
+ * Alter Domain
+ *
+ * The fields are used in different ways by the different variants of
+ * this command.
+ * ----------------------
+ */
+typedef struct AlterDomainStmt
+{
+ NodeTag type;
+ char subtype; /*------------
+ * T = alter column default
+ * N = alter column drop not null
+ * O = alter column set not null
+ * C = add constraint
+ * X = drop constraint
+ *------------
+ */
+ List *typeName; /* domain to work on */
+ char *name; /* column or constraint name to act on */
+ Node *def; /* definition of default or constraint */
+ DropBehavior behavior; /* RESTRICT or CASCADE for DROP cases */
+ bool missing_ok; /* skip error if missing? */
+} AlterDomainStmt;
+
+
+/* ----------------------
+ * Grant|Revoke Statement
+ * ----------------------
+ */
+typedef enum GrantTargetType
+{
+ ACL_TARGET_OBJECT, /* grant on specific named object(s) */
+ ACL_TARGET_ALL_IN_SCHEMA, /* grant on all objects in given schema(s) */
+ ACL_TARGET_DEFAULTS /* ALTER DEFAULT PRIVILEGES */
+} GrantTargetType;
+
+typedef struct GrantStmt
+{
+ NodeTag type;
+ bool is_grant; /* true = GRANT, false = REVOKE */
+ GrantTargetType targtype; /* type of the grant target */
+ ObjectType objtype; /* kind of object being operated on */
+ List *objects; /* list of RangeVar nodes, ObjectWithArgs
+ * nodes, or plain names (as String values) */
+ List *privileges; /* list of AccessPriv nodes */
+ /* privileges == NIL denotes ALL PRIVILEGES */
+ List *grantees; /* list of RoleSpec nodes */
+ bool grant_option; /* grant or revoke grant option */
+ RoleSpec *grantor;
+ DropBehavior behavior; /* drop behavior (for REVOKE) */
+} GrantStmt;
+
+/*
+ * ObjectWithArgs represents a function/procedure/operator name plus parameter
+ * identification.
+ *
+ * objargs includes only the types of the input parameters of the object.
+ * In some contexts, that will be all we have, and it's enough to look up
+ * objects according to the traditional Postgres rules (i.e., when only input
+ * arguments matter).
+ *
+ * objfuncargs, if not NIL, carries the full specification of the parameter
+ * list, including parameter mode annotations.
+ *
+ * Some grammar productions can set args_unspecified = true instead of
+ * providing parameter info. In this case, lookup will succeed only if
+ * the object name is unique. Note that otherwise, NIL parameter lists
+ * mean zero arguments.
+ */
+typedef struct ObjectWithArgs
+{
+ NodeTag type;
+ List *objname; /* qualified name of function/operator */
+ List *objargs; /* list of Typename nodes (input args only) */
+ List *objfuncargs; /* list of FunctionParameter nodes */
+ bool args_unspecified; /* argument list was omitted? */
+} ObjectWithArgs;
+
+/*
+ * An access privilege, with optional list of column names
+ * priv_name == NULL denotes ALL PRIVILEGES (only used with a column list)
+ * cols == NIL denotes "all columns"
+ * Note that simple "ALL PRIVILEGES" is represented as a NIL list, not
+ * an AccessPriv with both fields null.
+ */
+typedef struct AccessPriv
+{
+ NodeTag type;
+ char *priv_name; /* string name of privilege */
+ List *cols; /* list of String */
+} AccessPriv;
+
+/* ----------------------
+ * Grant/Revoke Role Statement
+ *
+ * Note: because of the parsing ambiguity with the GRANT
+ * statement, granted_roles is a list of AccessPriv; the execution code
+ * should complain if any column lists appear. grantee_roles is a list
+ * of role names, as String values.
+ * ----------------------
+ */
+typedef struct GrantRoleStmt
+{
+ NodeTag type;
+ List *granted_roles; /* list of roles to be granted/revoked */
+ List *grantee_roles; /* list of member roles to add/delete */
+ bool is_grant; /* true = GRANT, false = REVOKE */
+ List *opt; /* options e.g. WITH GRANT OPTION */
+ RoleSpec *grantor; /* set grantor to other than current role */
+ DropBehavior behavior; /* drop behavior (for REVOKE) */
+} GrantRoleStmt;
+
+/* ----------------------
+ * Alter Default Privileges Statement
+ * ----------------------
+ */
+typedef struct AlterDefaultPrivilegesStmt
+{
+ NodeTag type;
+ List *options; /* list of DefElem */
+ GrantStmt *action; /* GRANT/REVOKE action (with objects=NIL) */
+} AlterDefaultPrivilegesStmt;
+
+/* ----------------------
+ * Copy Statement
+ *
+ * We support "COPY relation FROM file", "COPY relation TO file", and
+ * "COPY (query) TO file". In any given CopyStmt, exactly one of "relation"
+ * and "query" must be non-NULL.
+ * ----------------------
+ */
+typedef struct CopyStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* the relation to copy */
+ Node *query; /* the query (SELECT or DML statement with
+ * RETURNING) to copy, as a raw parse tree */
+ List *attlist; /* List of column names (as Strings), or NIL
+ * for all columns */
+ bool is_from; /* TO or FROM */
+ bool is_program; /* is 'filename' a program to popen? */
+ char *filename; /* filename, or NULL for STDIN/STDOUT */
+ List *options; /* List of DefElem nodes */
+ Node *whereClause; /* WHERE condition (or NULL) */
+} CopyStmt;
+
+/* ----------------------
+ * SET Statement (includes RESET)
+ *
+ * "SET var TO DEFAULT" and "RESET var" are semantically equivalent, but we
+ * preserve the distinction in VariableSetKind for CreateCommandTag().
+ * ----------------------
+ */
+typedef enum VariableSetKind
+{
+ VAR_SET_VALUE, /* SET var = value */
+ VAR_SET_DEFAULT, /* SET var TO DEFAULT */
+ VAR_SET_CURRENT, /* SET var FROM CURRENT */
+ VAR_SET_MULTI, /* special case for SET TRANSACTION ... */
+ VAR_RESET, /* RESET var */
+ VAR_RESET_ALL /* RESET ALL */
+} VariableSetKind;
+
+typedef struct VariableSetStmt
+{
+ NodeTag type;
+ VariableSetKind kind;
+ char *name; /* variable to be set */
+ List *args; /* List of A_Const nodes */
+ bool is_local; /* SET LOCAL? */
+} VariableSetStmt;
+
+/* ----------------------
+ * Show Statement
+ * ----------------------
+ */
+typedef struct VariableShowStmt
+{
+ NodeTag type;
+ char *name;
+} VariableShowStmt;
+
+/* ----------------------
+ * Create Table Statement
+ *
+ * NOTE: in the raw gram.y output, ColumnDef and Constraint nodes are
+ * intermixed in tableElts, and constraints is NIL. After parse analysis,
+ * tableElts contains just ColumnDefs, and constraints contains just
+ * Constraint nodes (in fact, only CONSTR_CHECK nodes, in the present
+ * implementation).
+ * ----------------------
+ */
+
+typedef struct CreateStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* relation to create */
+ List *tableElts; /* column definitions (list of ColumnDef) */
+ List *inhRelations; /* relations to inherit from (list of
+ * RangeVar) */
+ PartitionBoundSpec *partbound; /* FOR VALUES clause */
+ PartitionSpec *partspec; /* PARTITION BY clause */
+ TypeName *ofTypename; /* OF typename */
+ List *constraints; /* constraints (list of Constraint nodes) */
+ List *options; /* options from WITH clause */
+ OnCommitAction oncommit; /* what do we do at COMMIT? */
+ char *tablespacename; /* table space to use, or NULL */
+ char *accessMethod; /* table access method */
+ bool if_not_exists; /* just do nothing if it already exists? */
+} CreateStmt;
+
+/* ----------
+ * Definitions for constraints in CreateStmt
+ *
+ * Note that column defaults are treated as a type of constraint,
+ * even though that's a bit odd semantically.
+ *
+ * For constraints that use expressions (CONSTR_CHECK, CONSTR_DEFAULT)
+ * we may have the expression in either "raw" form (an untransformed
+ * parse tree) or "cooked" form (the nodeToString representation of
+ * an executable expression tree), depending on how this Constraint
+ * node was created (by parsing, or by inheritance from an existing
+ * relation). We should never have both in the same node!
+ *
+ * FKCONSTR_ACTION_xxx values are stored into pg_constraint.confupdtype
+ * and pg_constraint.confdeltype columns; FKCONSTR_MATCH_xxx values are
+ * stored into pg_constraint.confmatchtype. Changing the code values may
+ * require an initdb!
+ *
+ * If skip_validation is true then we skip checking that the existing rows
+ * in the table satisfy the constraint, and just install the catalog entries
+ * for the constraint. A new FK constraint is marked as valid iff
+ * initially_valid is true. (Usually skip_validation and initially_valid
+ * are inverses, but we can set both true if the table is known empty.)
+ *
+ * Constraint attributes (DEFERRABLE etc) are initially represented as
+ * separate Constraint nodes for simplicity of parsing. parse_utilcmd.c makes
+ * a pass through the constraints list to insert the info into the appropriate
+ * Constraint node.
+ * ----------
+ */
+
+typedef enum ConstrType /* types of constraints */
+{
+ CONSTR_NULL, /* not standard SQL, but a lot of people
+ * expect it */
+ CONSTR_NOTNULL,
+ CONSTR_DEFAULT,
+ CONSTR_IDENTITY,
+ CONSTR_GENERATED,
+ CONSTR_CHECK,
+ CONSTR_PRIMARY,
+ CONSTR_UNIQUE,
+ CONSTR_EXCLUSION,
+ CONSTR_FOREIGN,
+ CONSTR_ATTR_DEFERRABLE, /* attributes for previous constraint node */
+ CONSTR_ATTR_NOT_DEFERRABLE,
+ CONSTR_ATTR_DEFERRED,
+ CONSTR_ATTR_IMMEDIATE
+} ConstrType;
+
+/* Foreign key action codes */
+#define FKCONSTR_ACTION_NOACTION 'a'
+#define FKCONSTR_ACTION_RESTRICT 'r'
+#define FKCONSTR_ACTION_CASCADE 'c'
+#define FKCONSTR_ACTION_SETNULL 'n'
+#define FKCONSTR_ACTION_SETDEFAULT 'd'
+
+/* Foreign key matchtype codes */
+#define FKCONSTR_MATCH_FULL 'f'
+#define FKCONSTR_MATCH_PARTIAL 'p'
+#define FKCONSTR_MATCH_SIMPLE 's'
+
+typedef struct Constraint
+{
+ pg_node_attr(custom_read_write)
+
+ NodeTag type;
+ ConstrType contype; /* see above */
+
+ /* Fields used for most/all constraint types: */
+ char *conname; /* Constraint name, or NULL if unnamed */
+ bool deferrable; /* DEFERRABLE? */
+ bool initdeferred; /* INITIALLY DEFERRED? */
+ int location; /* token location, or -1 if unknown */
+
+ /* Fields used for constraints with expressions (CHECK and DEFAULT): */
+ bool is_no_inherit; /* is constraint non-inheritable? */
+ Node *raw_expr; /* expr, as untransformed parse tree */
+ char *cooked_expr; /* expr, as nodeToString representation */
+ char generated_when; /* ALWAYS or BY DEFAULT */
+
+ /* Fields used for unique constraints (UNIQUE and PRIMARY KEY): */
+ bool nulls_not_distinct; /* null treatment for UNIQUE constraints */
+ List *keys; /* String nodes naming referenced key
+ * column(s) */
+ List *including; /* String nodes naming referenced nonkey
+ * column(s) */
+
+ /* Fields used for EXCLUSION constraints: */
+ List *exclusions; /* list of (IndexElem, operator name) pairs */
+
+ /* Fields used for index constraints (UNIQUE, PRIMARY KEY, EXCLUSION): */
+ List *options; /* options from WITH clause */
+ char *indexname; /* existing index to use; otherwise NULL */
+ char *indexspace; /* index tablespace; NULL for default */
+ bool reset_default_tblspc; /* reset default_tablespace prior to
+ * creating the index */
+ /* These could be, but currently are not, used for UNIQUE/PKEY: */
+ char *access_method; /* index access method; NULL for default */
+ Node *where_clause; /* partial index predicate */
+
+ /* Fields used for FOREIGN KEY constraints: */
+ RangeVar *pktable; /* Primary key table */
+ List *fk_attrs; /* Attributes of foreign key */
+ List *pk_attrs; /* Corresponding attrs in PK table */
+ char fk_matchtype; /* FULL, PARTIAL, SIMPLE */
+ char fk_upd_action; /* ON UPDATE action */
+ char fk_del_action; /* ON DELETE action */
+ List *fk_del_set_cols; /* ON DELETE SET NULL/DEFAULT (col1, col2) */
+ List *old_conpfeqop; /* pg_constraint.conpfeqop of my former self */
+ Oid old_pktable_oid; /* pg_constraint.confrelid of my former
+ * self */
+
+ /* Fields used for constraints that allow a NOT VALID specification */
+ bool skip_validation; /* skip validation of existing rows? */
+ bool initially_valid; /* mark the new constraint as valid? */
+} Constraint;
+
+/* ----------------------
+ * Create/Drop Table Space Statements
+ * ----------------------
+ */
+
+typedef struct CreateTableSpaceStmt
+{
+ NodeTag type;
+ char *tablespacename;
+ RoleSpec *owner;
+ char *location;
+ List *options;
+} CreateTableSpaceStmt;
+
+typedef struct DropTableSpaceStmt
+{
+ NodeTag type;
+ char *tablespacename;
+ bool missing_ok; /* skip error if missing? */
+} DropTableSpaceStmt;
+
+typedef struct AlterTableSpaceOptionsStmt
+{
+ NodeTag type;
+ char *tablespacename;
+ List *options;
+ bool isReset;
+} AlterTableSpaceOptionsStmt;
+
+typedef struct AlterTableMoveAllStmt
+{
+ NodeTag type;
+ char *orig_tablespacename;
+ ObjectType objtype; /* Object type to move */
+ List *roles; /* List of roles to move objects of */
+ char *new_tablespacename;
+ bool nowait;
+} AlterTableMoveAllStmt;
+
+/* ----------------------
+ * Create/Alter Extension Statements
+ * ----------------------
+ */
+
+typedef struct CreateExtensionStmt
+{
+ NodeTag type;
+ char *extname;
+ bool if_not_exists; /* just do nothing if it already exists? */
+ List *options; /* List of DefElem nodes */
+} CreateExtensionStmt;
+
+/* Only used for ALTER EXTENSION UPDATE; later might need an action field */
+typedef struct AlterExtensionStmt
+{
+ NodeTag type;
+ char *extname;
+ List *options; /* List of DefElem nodes */
+} AlterExtensionStmt;
+
+typedef struct AlterExtensionContentsStmt
+{
+ NodeTag type;
+ char *extname; /* Extension's name */
+ int action; /* +1 = add object, -1 = drop object */
+ ObjectType objtype; /* Object's type */
+ Node *object; /* Qualified name of the object */
+} AlterExtensionContentsStmt;
+
+/* ----------------------
+ * Create/Alter FOREIGN DATA WRAPPER Statements
+ * ----------------------
+ */
+
+typedef struct CreateFdwStmt
+{
+ NodeTag type;
+ char *fdwname; /* foreign-data wrapper name */
+ List *func_options; /* HANDLER/VALIDATOR options */
+ List *options; /* generic options to FDW */
+} CreateFdwStmt;
+
+typedef struct AlterFdwStmt
+{
+ NodeTag type;
+ char *fdwname; /* foreign-data wrapper name */
+ List *func_options; /* HANDLER/VALIDATOR options */
+ List *options; /* generic options to FDW */
+} AlterFdwStmt;
+
+/* ----------------------
+ * Create/Alter FOREIGN SERVER Statements
+ * ----------------------
+ */
+
+typedef struct CreateForeignServerStmt
+{
+ NodeTag type;
+ char *servername; /* server name */
+ char *servertype; /* optional server type */
+ char *version; /* optional server version */
+ char *fdwname; /* FDW name */
+ bool if_not_exists; /* just do nothing if it already exists? */
+ List *options; /* generic options to server */
+} CreateForeignServerStmt;
+
+typedef struct AlterForeignServerStmt
+{
+ NodeTag type;
+ char *servername; /* server name */
+ char *version; /* optional server version */
+ List *options; /* generic options to server */
+ bool has_version; /* version specified */
+} AlterForeignServerStmt;
+
+/* ----------------------
+ * Create FOREIGN TABLE Statement
+ * ----------------------
+ */
+
+typedef struct CreateForeignTableStmt
+{
+ CreateStmt base;
+ char *servername;
+ List *options;
+} CreateForeignTableStmt;
+
+/* ----------------------
+ * Create/Drop USER MAPPING Statements
+ * ----------------------
+ */
+
+typedef struct CreateUserMappingStmt
+{
+ NodeTag type;
+ RoleSpec *user; /* user role */
+ char *servername; /* server name */
+ bool if_not_exists; /* just do nothing if it already exists? */
+ List *options; /* generic options to server */
+} CreateUserMappingStmt;
+
+typedef struct AlterUserMappingStmt
+{
+ NodeTag type;
+ RoleSpec *user; /* user role */
+ char *servername; /* server name */
+ List *options; /* generic options to server */
+} AlterUserMappingStmt;
+
+typedef struct DropUserMappingStmt
+{
+ NodeTag type;
+ RoleSpec *user; /* user role */
+ char *servername; /* server name */
+ bool missing_ok; /* ignore missing mappings */
+} DropUserMappingStmt;
+
+/* ----------------------
+ * Import Foreign Schema Statement
+ * ----------------------
+ */
+
+typedef enum ImportForeignSchemaType
+{
+ FDW_IMPORT_SCHEMA_ALL, /* all relations wanted */
+ FDW_IMPORT_SCHEMA_LIMIT_TO, /* include only listed tables in import */
+ FDW_IMPORT_SCHEMA_EXCEPT /* exclude listed tables from import */
+} ImportForeignSchemaType;
+
+typedef struct ImportForeignSchemaStmt
+{
+ NodeTag type;
+ char *server_name; /* FDW server name */
+ char *remote_schema; /* remote schema name to query */
+ char *local_schema; /* local schema to create objects in */
+ ImportForeignSchemaType list_type; /* type of table list */
+ List *table_list; /* List of RangeVar */
+ List *options; /* list of options to pass to FDW */
+} ImportForeignSchemaStmt;
+
+/*----------------------
+ * Create POLICY Statement
+ *----------------------
+ */
+typedef struct CreatePolicyStmt
+{
+ NodeTag type;
+ char *policy_name; /* Policy's name */
+ RangeVar *table; /* the table name the policy applies to */
+ char *cmd_name; /* the command name the policy applies to */
+ bool permissive; /* restrictive or permissive policy */
+ List *roles; /* the roles associated with the policy */
+ Node *qual; /* the policy's condition */
+ Node *with_check; /* the policy's WITH CHECK condition. */
+} CreatePolicyStmt;
+
+/*----------------------
+ * Alter POLICY Statement
+ *----------------------
+ */
+typedef struct AlterPolicyStmt
+{
+ NodeTag type;
+ char *policy_name; /* Policy's name */
+ RangeVar *table; /* the table name the policy applies to */
+ List *roles; /* the roles associated with the policy */
+ Node *qual; /* the policy's condition */
+ Node *with_check; /* the policy's WITH CHECK condition. */
+} AlterPolicyStmt;
+
+/*----------------------
+ * Create ACCESS METHOD Statement
+ *----------------------
+ */
+typedef struct CreateAmStmt
+{
+ NodeTag type;
+ char *amname; /* access method name */
+ List *handler_name; /* handler function name */
+ char amtype; /* type of access method */
+} CreateAmStmt;
+
+/* ----------------------
+ * Create TRIGGER Statement
+ * ----------------------
+ */
+typedef struct CreateTrigStmt
+{
+ NodeTag type;
+ bool replace; /* replace trigger if already exists */
+ bool isconstraint; /* This is a constraint trigger */
+ char *trigname; /* TRIGGER's name */
+ RangeVar *relation; /* relation trigger is on */
+ List *funcname; /* qual. name of function to call */
+ List *args; /* list of String or NIL */
+ bool row; /* ROW/STATEMENT */
+ /* timing uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
+ int16 timing; /* BEFORE, AFTER, or INSTEAD */
+ /* events uses the TRIGGER_TYPE bits defined in catalog/pg_trigger.h */
+ int16 events; /* "OR" of INSERT/UPDATE/DELETE/TRUNCATE */
+ List *columns; /* column names, or NIL for all columns */
+ Node *whenClause; /* qual expression, or NULL if none */
+ /* explicitly named transition data */
+ List *transitionRels; /* TriggerTransition nodes, or NIL if none */
+ /* The remaining fields are only used for constraint triggers */
+ bool deferrable; /* [NOT] DEFERRABLE */
+ bool initdeferred; /* INITIALLY {DEFERRED|IMMEDIATE} */
+ RangeVar *constrrel; /* opposite relation, if RI trigger */
+} CreateTrigStmt;
+
+/* ----------------------
+ * Create EVENT TRIGGER Statement
+ * ----------------------
+ */
+typedef struct CreateEventTrigStmt
+{
+ NodeTag type;
+ char *trigname; /* TRIGGER's name */
+ char *eventname; /* event's identifier */
+ List *whenclause; /* list of DefElems indicating filtering */
+ List *funcname; /* qual. name of function to call */
+} CreateEventTrigStmt;
+
+/* ----------------------
+ * Alter EVENT TRIGGER Statement
+ * ----------------------
+ */
+typedef struct AlterEventTrigStmt
+{
+ NodeTag type;
+ char *trigname; /* TRIGGER's name */
+ char tgenabled; /* trigger's firing configuration WRT
+ * session_replication_role */
+} AlterEventTrigStmt;
+
+/* ----------------------
+ * Create LANGUAGE Statements
+ * ----------------------
+ */
+typedef struct CreatePLangStmt
+{
+ NodeTag type;
+ bool replace; /* T => replace if already exists */
+ char *plname; /* PL name */
+ List *plhandler; /* PL call handler function (qual. name) */
+ List *plinline; /* optional inline function (qual. name) */
+ List *plvalidator; /* optional validator function (qual. name) */
+ bool pltrusted; /* PL is trusted */
+} CreatePLangStmt;
+
+/* ----------------------
+ * Create/Alter/Drop Role Statements
+ *
+ * Note: these node types are also used for the backwards-compatible
+ * Create/Alter/Drop User/Group statements. In the ALTER and DROP cases
+ * there's really no need to distinguish what the original spelling was,
+ * but for CREATE we mark the type because the defaults vary.
+ * ----------------------
+ */
+typedef enum RoleStmtType
+{
+ ROLESTMT_ROLE,
+ ROLESTMT_USER,
+ ROLESTMT_GROUP
+} RoleStmtType;
+
+typedef struct CreateRoleStmt
+{
+ NodeTag type;
+ RoleStmtType stmt_type; /* ROLE/USER/GROUP */
+ char *role; /* role name */
+ List *options; /* List of DefElem nodes */
+} CreateRoleStmt;
+
+typedef struct AlterRoleStmt
+{
+ NodeTag type;
+ RoleSpec *role; /* role */
+ List *options; /* List of DefElem nodes */
+ int action; /* +1 = add members, -1 = drop members */
+} AlterRoleStmt;
+
+typedef struct AlterRoleSetStmt
+{
+ NodeTag type;
+ RoleSpec *role; /* role */
+ char *database; /* database name, or NULL */
+ VariableSetStmt *setstmt; /* SET or RESET subcommand */
+} AlterRoleSetStmt;
+
+typedef struct DropRoleStmt
+{
+ NodeTag type;
+ List *roles; /* List of roles to remove */
+ bool missing_ok; /* skip error if a role is missing? */
+} DropRoleStmt;
+
+/* ----------------------
+ * {Create|Alter} SEQUENCE Statement
+ * ----------------------
+ */
+
+typedef struct CreateSeqStmt
+{
+ NodeTag type;
+ RangeVar *sequence; /* the sequence to create */
+ List *options;
+ Oid ownerId; /* ID of owner, or InvalidOid for default */
+ bool for_identity;
+ bool if_not_exists; /* just do nothing if it already exists? */
+} CreateSeqStmt;
+
+typedef struct AlterSeqStmt
+{
+ NodeTag type;
+ RangeVar *sequence; /* the sequence to alter */
+ List *options;
+ bool for_identity;
+ bool missing_ok; /* skip error if a role is missing? */
+} AlterSeqStmt;
+
+/* ----------------------
+ * Create {Aggregate|Operator|Type} Statement
+ * ----------------------
+ */
+typedef struct DefineStmt
+{
+ NodeTag type;
+ ObjectType kind; /* aggregate, operator, type */
+ bool oldstyle; /* hack to signal old CREATE AGG syntax */
+ List *defnames; /* qualified name (list of String) */
+ List *args; /* a list of TypeName (if needed) */
+ List *definition; /* a list of DefElem */
+ bool if_not_exists; /* just do nothing if it already exists? */
+ bool replace; /* replace if already exists? */
+} DefineStmt;
+
+/* ----------------------
+ * Create Domain Statement
+ * ----------------------
+ */
+typedef struct CreateDomainStmt
+{
+ NodeTag type;
+ List *domainname; /* qualified name (list of String) */
+ TypeName *typeName; /* the base type */
+ CollateClause *collClause; /* untransformed COLLATE spec, if any */
+ List *constraints; /* constraints (list of Constraint nodes) */
+} CreateDomainStmt;
+
+/* ----------------------
+ * Create Operator Class Statement
+ * ----------------------
+ */
+typedef struct CreateOpClassStmt
+{
+ NodeTag type;
+ List *opclassname; /* qualified name (list of String) */
+ List *opfamilyname; /* qualified name (ditto); NIL if omitted */
+ char *amname; /* name of index AM opclass is for */
+ TypeName *datatype; /* datatype of indexed column */
+ List *items; /* List of CreateOpClassItem nodes */
+ bool isDefault; /* Should be marked as default for type? */
+} CreateOpClassStmt;
+
+#define OPCLASS_ITEM_OPERATOR 1
+#define OPCLASS_ITEM_FUNCTION 2
+#define OPCLASS_ITEM_STORAGETYPE 3
+
+typedef struct CreateOpClassItem
+{
+ NodeTag type;
+ int itemtype; /* see codes above */
+ ObjectWithArgs *name; /* operator or function name and args */
+ int number; /* strategy num or support proc num */
+ List *order_family; /* only used for ordering operators */
+ List *class_args; /* amproclefttype/amprocrighttype or
+ * amoplefttype/amoprighttype */
+ /* fields used for a storagetype item: */
+ TypeName *storedtype; /* datatype stored in index */
+} CreateOpClassItem;
+
+/* ----------------------
+ * Create Operator Family Statement
+ * ----------------------
+ */
+typedef struct CreateOpFamilyStmt
+{
+ NodeTag type;
+ List *opfamilyname; /* qualified name (list of String) */
+ char *amname; /* name of index AM opfamily is for */
+} CreateOpFamilyStmt;
+
+/* ----------------------
+ * Alter Operator Family Statement
+ * ----------------------
+ */
+typedef struct AlterOpFamilyStmt
+{
+ NodeTag type;
+ List *opfamilyname; /* qualified name (list of String) */
+ char *amname; /* name of index AM opfamily is for */
+ bool isDrop; /* ADD or DROP the items? */
+ List *items; /* List of CreateOpClassItem nodes */
+} AlterOpFamilyStmt;
+
+/* ----------------------
+ * Drop Table|Sequence|View|Index|Type|Domain|Conversion|Schema Statement
+ * ----------------------
+ */
+
+typedef struct DropStmt
+{
+ NodeTag type;
+ List *objects; /* list of names */
+ ObjectType removeType; /* object type */
+ DropBehavior behavior; /* RESTRICT or CASCADE behavior */
+ bool missing_ok; /* skip error if object is missing? */
+ bool concurrent; /* drop index concurrently? */
+} DropStmt;
+
+/* ----------------------
+ * Truncate Table Statement
+ * ----------------------
+ */
+typedef struct TruncateStmt
+{
+ NodeTag type;
+ List *relations; /* relations (RangeVars) to be truncated */
+ bool restart_seqs; /* restart owned sequences? */
+ DropBehavior behavior; /* RESTRICT or CASCADE behavior */
+} TruncateStmt;
+
+/* ----------------------
+ * Comment On Statement
+ * ----------------------
+ */
+typedef struct CommentStmt
+{
+ NodeTag type;
+ ObjectType objtype; /* Object's type */
+ Node *object; /* Qualified name of the object */
+ char *comment; /* Comment to insert, or NULL to remove */
+} CommentStmt;
+
+/* ----------------------
+ * SECURITY LABEL Statement
+ * ----------------------
+ */
+typedef struct SecLabelStmt
+{
+ NodeTag type;
+ ObjectType objtype; /* Object's type */
+ Node *object; /* Qualified name of the object */
+ char *provider; /* Label provider (or NULL) */
+ char *label; /* New security label to be assigned */
+} SecLabelStmt;
+
+/* ----------------------
+ * Declare Cursor Statement
+ *
+ * The "query" field is initially a raw parse tree, and is converted to a
+ * Query node during parse analysis. Note that rewriting and planning
+ * of the query are always postponed until execution.
+ * ----------------------
+ */
+#define CURSOR_OPT_BINARY 0x0001 /* BINARY */
+#define CURSOR_OPT_SCROLL 0x0002 /* SCROLL explicitly given */
+#define CURSOR_OPT_NO_SCROLL 0x0004 /* NO SCROLL explicitly given */
+#define CURSOR_OPT_INSENSITIVE 0x0008 /* INSENSITIVE */
+#define CURSOR_OPT_ASENSITIVE 0x0010 /* ASENSITIVE */
+#define CURSOR_OPT_HOLD 0x0020 /* WITH HOLD */
+/* these planner-control flags do not correspond to any SQL grammar: */
+#define CURSOR_OPT_FAST_PLAN 0x0100 /* prefer fast-start plan */
+#define CURSOR_OPT_GENERIC_PLAN 0x0200 /* force use of generic plan */
+#define CURSOR_OPT_CUSTOM_PLAN 0x0400 /* force use of custom plan */
+#define CURSOR_OPT_PARALLEL_OK 0x0800 /* parallel mode OK */
+
+typedef struct DeclareCursorStmt
+{
+ NodeTag type;
+ char *portalname; /* name of the portal (cursor) */
+ int options; /* bitmask of options (see above) */
+ Node *query; /* the query (see comments above) */
+} DeclareCursorStmt;
+
+/* ----------------------
+ * Close Portal Statement
+ * ----------------------
+ */
+typedef struct ClosePortalStmt
+{
+ NodeTag type;
+ char *portalname; /* name of the portal (cursor) */
+ /* NULL means CLOSE ALL */
+} ClosePortalStmt;
+
+/* ----------------------
+ * Fetch Statement (also Move)
+ * ----------------------
+ */
+typedef enum FetchDirection
+{
+ /* for these, howMany is how many rows to fetch; FETCH_ALL means ALL */
+ FETCH_FORWARD,
+ FETCH_BACKWARD,
+ /* for these, howMany indicates a position; only one row is fetched */
+ FETCH_ABSOLUTE,
+ FETCH_RELATIVE
+} FetchDirection;
+
+#define FETCH_ALL LONG_MAX
+
+typedef struct FetchStmt
+{
+ NodeTag type;
+ FetchDirection direction; /* see above */
+ long howMany; /* number of rows, or position argument */
+ char *portalname; /* name of portal (cursor) */
+ bool ismove; /* true if MOVE */
+} FetchStmt;
+
+/* ----------------------
+ * Create Index Statement
+ *
+ * This represents creation of an index and/or an associated constraint.
+ * If isconstraint is true, we should create a pg_constraint entry along
+ * with the index. But if indexOid isn't InvalidOid, we are not creating an
+ * index, just a UNIQUE/PKEY constraint using an existing index. isconstraint
+ * must always be true in this case, and the fields describing the index
+ * properties are empty.
+ * ----------------------
+ */
+typedef struct IndexStmt
+{
+ NodeTag type;
+ char *idxname; /* name of new index, or NULL for default */
+ RangeVar *relation; /* relation to build index on */
+ char *accessMethod; /* name of access method (eg. btree) */
+ char *tableSpace; /* tablespace, or NULL for default */
+ List *indexParams; /* columns to index: a list of IndexElem */
+ List *indexIncludingParams; /* additional columns to index: a list
+ * of IndexElem */
+ List *options; /* WITH clause options: a list of DefElem */
+ Node *whereClause; /* qualification (partial-index predicate) */
+ List *excludeOpNames; /* exclusion operator names, or NIL if none */
+ char *idxcomment; /* comment to apply to index, or NULL */
+ Oid indexOid; /* OID of an existing index, if any */
+ RelFileNumber oldNumber; /* relfilenumber of existing storage, if any */
+ SubTransactionId oldCreateSubid; /* rd_createSubid of oldNumber */
+ SubTransactionId oldFirstRelfilelocatorSubid; /* rd_firstRelfilelocatorSubid
+ * of oldNumber */
+ bool unique; /* is index unique? */
+ bool nulls_not_distinct; /* null treatment for UNIQUE constraints */
+ bool primary; /* is index a primary key? */
+ bool isconstraint; /* is it for a pkey/unique constraint? */
+ bool deferrable; /* is the constraint DEFERRABLE? */
+ bool initdeferred; /* is the constraint INITIALLY DEFERRED? */
+ bool transformed; /* true when transformIndexStmt is finished */
+ bool concurrent; /* should this be a concurrent index build? */
+ bool if_not_exists; /* just do nothing if index already exists? */
+ bool reset_default_tblspc; /* reset default_tablespace prior to
+ * executing */
+} IndexStmt;
+
+/* ----------------------
+ * Create Statistics Statement
+ * ----------------------
+ */
+typedef struct CreateStatsStmt
+{
+ NodeTag type;
+ List *defnames; /* qualified name (list of String) */
+ List *stat_types; /* stat types (list of String) */
+ List *exprs; /* expressions to build statistics on */
+ List *relations; /* rels to build stats on (list of RangeVar) */
+ char *stxcomment; /* comment to apply to stats, or NULL */
+ bool transformed; /* true when transformStatsStmt is finished */
+ bool if_not_exists; /* do nothing if stats name already exists */
+} CreateStatsStmt;
+
+/*
+ * StatsElem - statistics parameters (used in CREATE STATISTICS)
+ *
+ * For a plain attribute, 'name' is the name of the referenced table column
+ * and 'expr' is NULL. For an expression, 'name' is NULL and 'expr' is the
+ * expression tree.
+ */
+typedef struct StatsElem
+{
+ NodeTag type;
+ char *name; /* name of attribute to index, or NULL */
+ Node *expr; /* expression to index, or NULL */
+} StatsElem;
+
+
+/* ----------------------
+ * Alter Statistics Statement
+ * ----------------------
+ */
+typedef struct AlterStatsStmt
+{
+ NodeTag type;
+ List *defnames; /* qualified name (list of String) */
+ int stxstattarget; /* statistics target */
+ bool missing_ok; /* skip error if statistics object is missing */
+} AlterStatsStmt;
+
+/* ----------------------
+ * Create Function Statement
+ * ----------------------
+ */
+typedef struct CreateFunctionStmt
+{
+ NodeTag type;
+ bool is_procedure; /* it's really CREATE PROCEDURE */
+ bool replace; /* T => replace if already exists */
+ List *funcname; /* qualified name of function to create */
+ List *parameters; /* a list of FunctionParameter */
+ TypeName *returnType; /* the return type */
+ List *options; /* a list of DefElem */
+ Node *sql_body;
+} CreateFunctionStmt;
+
+typedef enum FunctionParameterMode
+{
+ /* the assigned enum values appear in pg_proc, don't change 'em! */
+ FUNC_PARAM_IN = 'i', /* input only */
+ FUNC_PARAM_OUT = 'o', /* output only */
+ FUNC_PARAM_INOUT = 'b', /* both */
+ FUNC_PARAM_VARIADIC = 'v', /* variadic (always input) */
+ FUNC_PARAM_TABLE = 't', /* table function output column */
+ /* this is not used in pg_proc: */
+ FUNC_PARAM_DEFAULT = 'd' /* default; effectively same as IN */
+} FunctionParameterMode;
+
+typedef struct FunctionParameter
+{
+ NodeTag type;
+ char *name; /* parameter name, or NULL if not given */
+ TypeName *argType; /* TypeName for parameter type */
+ FunctionParameterMode mode; /* IN/OUT/etc */
+ Node *defexpr; /* raw default expr, or NULL if not given */
+} FunctionParameter;
+
+typedef struct AlterFunctionStmt
+{
+ NodeTag type;
+ ObjectType objtype;
+ ObjectWithArgs *func; /* name and args of function */
+ List *actions; /* list of DefElem */
+} AlterFunctionStmt;
+
+/* ----------------------
+ * DO Statement
+ *
+ * DoStmt is the raw parser output, InlineCodeBlock is the execution-time API
+ * ----------------------
+ */
+typedef struct DoStmt
+{
+ NodeTag type;
+ List *args; /* List of DefElem nodes */
+} DoStmt;
+
+typedef struct InlineCodeBlock
+{
+ pg_node_attr(nodetag_only) /* this is not a member of parse trees */
+
+ NodeTag type;
+ char *source_text; /* source text of anonymous code block */
+ Oid langOid; /* OID of selected language */
+ bool langIsTrusted; /* trusted property of the language */
+ bool atomic; /* atomic execution context */
+} InlineCodeBlock;
+
+/* ----------------------
+ * CALL statement
+ *
+ * OUT-mode arguments are removed from the transformed funcexpr. The outargs
+ * list contains copies of the expressions for all output arguments, in the
+ * order of the procedure's declared arguments. (outargs is never evaluated,
+ * but is useful to the caller as a reference for what to assign to.)
+ * The transformed call state is not relevant in the query jumbling, only the
+ * function call is.
+ * ----------------------
+ */
+typedef struct CallStmt
+{
+ NodeTag type;
+ FuncCall *funccall; /* from the parser */
+ /* transformed call, with only input args */
+ FuncExpr *funcexpr pg_node_attr(query_jumble_ignore);
+ /* transformed output-argument expressions */
+ List *outargs pg_node_attr(query_jumble_ignore);
+} CallStmt;
+
+typedef struct CallContext
+{
+ pg_node_attr(nodetag_only) /* this is not a member of parse trees */
+
+ NodeTag type;
+ bool atomic;
+} CallContext;
+
+/* ----------------------
+ * Alter Object Rename Statement
+ * ----------------------
+ */
+typedef struct RenameStmt
+{
+ NodeTag type;
+ ObjectType renameType; /* OBJECT_TABLE, OBJECT_COLUMN, etc */
+ ObjectType relationType; /* if column name, associated relation type */
+ RangeVar *relation; /* in case it's a table */
+ Node *object; /* in case it's some other object */
+ char *subname; /* name of contained object (column, rule,
+ * trigger, etc) */
+ char *newname; /* the new name */
+ DropBehavior behavior; /* RESTRICT or CASCADE behavior */
+ bool missing_ok; /* skip error if missing? */
+} RenameStmt;
+
+/* ----------------------
+ * ALTER object DEPENDS ON EXTENSION extname
+ * ----------------------
+ */
+typedef struct AlterObjectDependsStmt
+{
+ NodeTag type;
+ ObjectType objectType; /* OBJECT_FUNCTION, OBJECT_TRIGGER, etc */
+ RangeVar *relation; /* in case a table is involved */
+ Node *object; /* name of the object */
+ String *extname; /* extension name */
+ bool remove; /* set true to remove dep rather than add */
+} AlterObjectDependsStmt;
+
+/* ----------------------
+ * ALTER object SET SCHEMA Statement
+ * ----------------------
+ */
+typedef struct AlterObjectSchemaStmt
+{
+ NodeTag type;
+ ObjectType objectType; /* OBJECT_TABLE, OBJECT_TYPE, etc */
+ RangeVar *relation; /* in case it's a table */
+ Node *object; /* in case it's some other object */
+ char *newschema; /* the new schema */
+ bool missing_ok; /* skip error if missing? */
+} AlterObjectSchemaStmt;
+
+/* ----------------------
+ * Alter Object Owner Statement
+ * ----------------------
+ */
+typedef struct AlterOwnerStmt
+{
+ NodeTag type;
+ ObjectType objectType; /* OBJECT_TABLE, OBJECT_TYPE, etc */
+ RangeVar *relation; /* in case it's a table */
+ Node *object; /* in case it's some other object */
+ RoleSpec *newowner; /* the new owner */
+} AlterOwnerStmt;
+
+/* ----------------------
+ * Alter Operator Set ( this-n-that )
+ * ----------------------
+ */
+typedef struct AlterOperatorStmt
+{
+ NodeTag type;
+ ObjectWithArgs *opername; /* operator name and argument types */
+ List *options; /* List of DefElem nodes */
+} AlterOperatorStmt;
+
+/* ------------------------
+ * Alter Type Set ( this-n-that )
+ * ------------------------
+ */
+typedef struct AlterTypeStmt
+{
+ NodeTag type;
+ List *typeName; /* type name (possibly qualified) */
+ List *options; /* List of DefElem nodes */
+} AlterTypeStmt;
+
+/* ----------------------
+ * Create Rule Statement
+ * ----------------------
+ */
+typedef struct RuleStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* relation the rule is for */
+ char *rulename; /* name of the rule */
+ Node *whereClause; /* qualifications */
+ CmdType event; /* SELECT, INSERT, etc */
+ bool instead; /* is a 'do instead'? */
+ List *actions; /* the action statements */
+ bool replace; /* OR REPLACE */
+} RuleStmt;
+
+/* ----------------------
+ * Notify Statement
+ * ----------------------
+ */
+typedef struct NotifyStmt
+{
+ NodeTag type;
+ char *conditionname; /* condition name to notify */
+ char *payload; /* the payload string, or NULL if none */
+} NotifyStmt;
+
+/* ----------------------
+ * Listen Statement
+ * ----------------------
+ */
+typedef struct ListenStmt
+{
+ NodeTag type;
+ char *conditionname; /* condition name to listen on */
+} ListenStmt;
+
+/* ----------------------
+ * Unlisten Statement
+ * ----------------------
+ */
+typedef struct UnlistenStmt
+{
+ NodeTag type;
+ char *conditionname; /* name to unlisten on, or NULL for all */
+} UnlistenStmt;
+
+/* ----------------------
+ * {Begin|Commit|Rollback} Transaction Statement
+ * ----------------------
+ */
+typedef enum TransactionStmtKind
+{
+ TRANS_STMT_BEGIN,
+ TRANS_STMT_START, /* semantically identical to BEGIN */
+ TRANS_STMT_COMMIT,
+ TRANS_STMT_ROLLBACK,
+ TRANS_STMT_SAVEPOINT,
+ TRANS_STMT_RELEASE,
+ TRANS_STMT_ROLLBACK_TO,
+ TRANS_STMT_PREPARE,
+ TRANS_STMT_COMMIT_PREPARED,
+ TRANS_STMT_ROLLBACK_PREPARED
+} TransactionStmtKind;
+
+typedef struct TransactionStmt
+{
+ NodeTag type;
+ TransactionStmtKind kind; /* see above */
+ List *options; /* for BEGIN/START commands */
+ char *savepoint_name; /* for savepoint commands */
+ char *gid; /* for two-phase-commit related commands */
+ bool chain; /* AND CHAIN option */
+} TransactionStmt;
+
+/* ----------------------
+ * Create Type Statement, composite types
+ * ----------------------
+ */
+typedef struct CompositeTypeStmt
+{
+ NodeTag type;
+ RangeVar *typevar; /* the composite type to be created */
+ List *coldeflist; /* list of ColumnDef nodes */
+} CompositeTypeStmt;
+
+/* ----------------------
+ * Create Type Statement, enum types
+ * ----------------------
+ */
+typedef struct CreateEnumStmt
+{
+ NodeTag type;
+ List *typeName; /* qualified name (list of String) */
+ List *vals; /* enum values (list of String) */
+} CreateEnumStmt;
+
+/* ----------------------
+ * Create Type Statement, range types
+ * ----------------------
+ */
+typedef struct CreateRangeStmt
+{
+ NodeTag type;
+ List *typeName; /* qualified name (list of String) */
+ List *params; /* range parameters (list of DefElem) */
+} CreateRangeStmt;
+
+/* ----------------------
+ * Alter Type Statement, enum types
+ * ----------------------
+ */
+typedef struct AlterEnumStmt
+{
+ NodeTag type;
+ List *typeName; /* qualified name (list of String) */
+ char *oldVal; /* old enum value's name, if renaming */
+ char *newVal; /* new enum value's name */
+ char *newValNeighbor; /* neighboring enum value, if specified */
+ bool newValIsAfter; /* place new enum value after neighbor? */
+ bool skipIfNewValExists; /* no error if new already exists? */
+} AlterEnumStmt;
+
+/* ----------------------
+ * Create View Statement
+ * ----------------------
+ */
+typedef enum ViewCheckOption
+{
+ NO_CHECK_OPTION,
+ LOCAL_CHECK_OPTION,
+ CASCADED_CHECK_OPTION
+} ViewCheckOption;
+
+typedef struct ViewStmt
+{
+ NodeTag type;
+ RangeVar *view; /* the view to be created */
+ List *aliases; /* target column names */
+ Node *query; /* the SELECT query (as a raw parse tree) */
+ bool replace; /* replace an existing view? */
+ List *options; /* options from WITH clause */
+ ViewCheckOption withCheckOption; /* WITH CHECK OPTION */
+} ViewStmt;
+
+/* ----------------------
+ * Load Statement
+ * ----------------------
+ */
+typedef struct LoadStmt
+{
+ NodeTag type;
+ char *filename; /* file to load */
+} LoadStmt;
+
+/* ----------------------
+ * Createdb Statement
+ * ----------------------
+ */
+typedef struct CreatedbStmt
+{
+ NodeTag type;
+ char *dbname; /* name of database to create */
+ List *options; /* List of DefElem nodes */
+} CreatedbStmt;
+
+/* ----------------------
+ * Alter Database
+ * ----------------------
+ */
+typedef struct AlterDatabaseStmt
+{
+ NodeTag type;
+ char *dbname; /* name of database to alter */
+ List *options; /* List of DefElem nodes */
+} AlterDatabaseStmt;
+
+typedef struct AlterDatabaseRefreshCollStmt
+{
+ NodeTag type;
+ char *dbname;
+} AlterDatabaseRefreshCollStmt;
+
+typedef struct AlterDatabaseSetStmt
+{
+ NodeTag type;
+ char *dbname; /* database name */
+ VariableSetStmt *setstmt; /* SET or RESET subcommand */
+} AlterDatabaseSetStmt;
+
+/* ----------------------
+ * Dropdb Statement
+ * ----------------------
+ */
+typedef struct DropdbStmt
+{
+ NodeTag type;
+ char *dbname; /* database to drop */
+ bool missing_ok; /* skip error if db is missing? */
+ List *options; /* currently only FORCE is supported */
+} DropdbStmt;
+
+/* ----------------------
+ * Alter System Statement
+ * ----------------------
+ */
+typedef struct AlterSystemStmt
+{
+ NodeTag type;
+ VariableSetStmt *setstmt; /* SET subcommand */
+} AlterSystemStmt;
+
+/* ----------------------
+ * Cluster Statement (support pbrown's cluster index implementation)
+ * ----------------------
+ */
+typedef struct ClusterStmt
+{
+ NodeTag type;
+ RangeVar *relation; /* relation being indexed, or NULL if all */
+ char *indexname; /* original index defined */
+ List *params; /* list of DefElem nodes */
+} ClusterStmt;
+
+/* ----------------------
+ * Vacuum and Analyze Statements
+ *
+ * Even though these are nominally two statements, it's convenient to use
+ * just one node type for both.
+ * ----------------------
+ */
+typedef struct VacuumStmt
+{
+ NodeTag type;
+ List *options; /* list of DefElem nodes */
+ List *rels; /* list of VacuumRelation, or NIL for all */
+ bool is_vacuumcmd; /* true for VACUUM, false for ANALYZE */
+} VacuumStmt;
+
+/*
+ * Info about a single target table of VACUUM/ANALYZE.
+ *
+ * If the OID field is set, it always identifies the table to process.
+ * Then the relation field can be NULL; if it isn't, it's used only to report
+ * failure to open/lock the relation.
+ */
+typedef struct VacuumRelation
+{
+ NodeTag type;
+ RangeVar *relation; /* table name to process, or NULL */
+ Oid oid; /* table's OID; InvalidOid if not looked up */
+ List *va_cols; /* list of column names, or NIL for all */
+} VacuumRelation;
+
+/* ----------------------
+ * Explain Statement
+ *
+ * The "query" field is initially a raw parse tree, and is converted to a
+ * Query node during parse analysis. Note that rewriting and planning
+ * of the query are always postponed until execution.
+ * ----------------------
+ */
+typedef struct ExplainStmt
+{
+ NodeTag type;
+ Node *query; /* the query (see comments above) */
+ List *options; /* list of DefElem nodes */
+} ExplainStmt;
+
+/* ----------------------
+ * CREATE TABLE AS Statement (a/k/a SELECT INTO)
+ *
+ * A query written as CREATE TABLE AS will produce this node type natively.
+ * A query written as SELECT ... INTO will be transformed to this form during
+ * parse analysis.
+ * A query written as CREATE MATERIALIZED view will produce this node type,
+ * during parse analysis, since it needs all the same data.
+ *
+ * The "query" field is handled similarly to EXPLAIN, though note that it
+ * can be a SELECT or an EXECUTE, but not other DML statements.
+ * ----------------------
+ */
+typedef struct CreateTableAsStmt
+{
+ NodeTag type;
+ Node *query; /* the query (see comments above) */
+ IntoClause *into; /* destination table */
+ ObjectType objtype; /* OBJECT_TABLE or OBJECT_MATVIEW */
+ bool is_select_into; /* it was written as SELECT INTO */
+ bool if_not_exists; /* just do nothing if it already exists? */
+} CreateTableAsStmt;
+
+/* ----------------------
+ * REFRESH MATERIALIZED VIEW Statement
+ * ----------------------
+ */
+typedef struct RefreshMatViewStmt
+{
+ NodeTag type;
+ bool concurrent; /* allow concurrent access? */
+ bool skipData; /* true for WITH NO DATA */
+ RangeVar *relation; /* relation to insert into */
+} RefreshMatViewStmt;
+
+/* ----------------------
+ * Checkpoint Statement
+ * ----------------------
+ */
+typedef struct CheckPointStmt
+{
+ NodeTag type;
+} CheckPointStmt;
+
+/* ----------------------
+ * Discard Statement
+ * ----------------------
+ */
+
+typedef enum DiscardMode
+{
+ DISCARD_ALL,
+ DISCARD_PLANS,
+ DISCARD_SEQUENCES,
+ DISCARD_TEMP
+} DiscardMode;
+
+typedef struct DiscardStmt
+{
+ NodeTag type;
+ DiscardMode target;
+} DiscardStmt;
+
+/* ----------------------
+ * LOCK Statement
+ * ----------------------
+ */
+typedef struct LockStmt
+{
+ NodeTag type;
+ List *relations; /* relations to lock */
+ int mode; /* lock mode */
+ bool nowait; /* no wait mode */
+} LockStmt;
+
+/* ----------------------
+ * SET CONSTRAINTS Statement
+ * ----------------------
+ */
+typedef struct ConstraintsSetStmt
+{
+ NodeTag type;
+ List *constraints; /* List of names as RangeVars */
+ bool deferred;
+} ConstraintsSetStmt;
+
+/* ----------------------
+ * REINDEX Statement
+ * ----------------------
+ */
+typedef enum ReindexObjectType
+{
+ REINDEX_OBJECT_INDEX, /* index */
+ REINDEX_OBJECT_TABLE, /* table or materialized view */
+ REINDEX_OBJECT_SCHEMA, /* schema */
+ REINDEX_OBJECT_SYSTEM, /* system catalogs */
+ REINDEX_OBJECT_DATABASE /* database */
+} ReindexObjectType;
+
+typedef struct ReindexStmt
+{
+ NodeTag type;
+ ReindexObjectType kind; /* REINDEX_OBJECT_INDEX, REINDEX_OBJECT_TABLE,
+ * etc. */
+ RangeVar *relation; /* Table or index to reindex */
+ const char *name; /* name of database to reindex */
+ List *params; /* list of DefElem nodes */
+} ReindexStmt;
+
+/* ----------------------
+ * CREATE CONVERSION Statement
+ * ----------------------
+ */
+typedef struct CreateConversionStmt
+{
+ NodeTag type;
+ List *conversion_name; /* Name of the conversion */
+ char *for_encoding_name; /* source encoding name */
+ char *to_encoding_name; /* destination encoding name */
+ List *func_name; /* qualified conversion function name */
+ bool def; /* is this a default conversion? */
+} CreateConversionStmt;
+
+/* ----------------------
+ * CREATE CAST Statement
+ * ----------------------
+ */
+typedef struct CreateCastStmt
+{
+ NodeTag type;
+ TypeName *sourcetype;
+ TypeName *targettype;
+ ObjectWithArgs *func;
+ CoercionContext context;
+ bool inout;
+} CreateCastStmt;
+
+/* ----------------------
+ * CREATE TRANSFORM Statement
+ * ----------------------
+ */
+typedef struct CreateTransformStmt
+{
+ NodeTag type;
+ bool replace;
+ TypeName *type_name;
+ char *lang;
+ ObjectWithArgs *fromsql;
+ ObjectWithArgs *tosql;
+} CreateTransformStmt;
+
+/* ----------------------
+ * PREPARE Statement
+ * ----------------------
+ */
+typedef struct PrepareStmt
+{
+ NodeTag type;
+ char *name; /* Name of plan, arbitrary */
+ List *argtypes; /* Types of parameters (List of TypeName) */
+ Node *query; /* The query itself (as a raw parsetree) */
+} PrepareStmt;
+
+
+/* ----------------------
+ * EXECUTE Statement
+ * ----------------------
+ */
+
+typedef struct ExecuteStmt
+{
+ NodeTag type;
+ char *name; /* The name of the plan to execute */
+ List *params; /* Values to assign to parameters */
+} ExecuteStmt;
+
+
+/* ----------------------
+ * DEALLOCATE Statement
+ * ----------------------
+ */
+typedef struct DeallocateStmt
+{
+ NodeTag type;
+ char *name; /* The name of the plan to remove */
+ /* NULL means DEALLOCATE ALL */
+} DeallocateStmt;
+
+/*
+ * DROP OWNED statement
+ */
+typedef struct DropOwnedStmt
+{
+ NodeTag type;
+ List *roles;
+ DropBehavior behavior;
+} DropOwnedStmt;
+
+/*
+ * REASSIGN OWNED statement
+ */
+typedef struct ReassignOwnedStmt
+{
+ NodeTag type;
+ List *roles;
+ RoleSpec *newrole;
+} ReassignOwnedStmt;
+
+/*
+ * TS Dictionary stmts: DefineStmt, RenameStmt and DropStmt are default
+ */
+typedef struct AlterTSDictionaryStmt
+{
+ NodeTag type;
+ List *dictname; /* qualified name (list of String) */
+ List *options; /* List of DefElem nodes */
+} AlterTSDictionaryStmt;
+
+/*
+ * TS Configuration stmts: DefineStmt, RenameStmt and DropStmt are default
+ */
+typedef enum AlterTSConfigType
+{
+ ALTER_TSCONFIG_ADD_MAPPING,
+ ALTER_TSCONFIG_ALTER_MAPPING_FOR_TOKEN,
+ ALTER_TSCONFIG_REPLACE_DICT,
+ ALTER_TSCONFIG_REPLACE_DICT_FOR_TOKEN,
+ ALTER_TSCONFIG_DROP_MAPPING
+} AlterTSConfigType;
+
+typedef struct AlterTSConfigurationStmt
+{
+ NodeTag type;
+ AlterTSConfigType kind; /* ALTER_TSCONFIG_ADD_MAPPING, etc */
+ List *cfgname; /* qualified name (list of String) */
+
+ /*
+ * dicts will be non-NIL if ADD/ALTER MAPPING was specified. If dicts is
+ * NIL, but tokentype isn't, DROP MAPPING was specified.
+ */
+ List *tokentype; /* list of String */
+ List *dicts; /* list of list of String */
+ bool override; /* if true - remove old variant */
+ bool replace; /* if true - replace dictionary by another */
+ bool missing_ok; /* for DROP - skip error if missing? */
+} AlterTSConfigurationStmt;
+
+typedef struct PublicationTable
+{
+ NodeTag type;
+ RangeVar *relation; /* relation to be published */
+ Node *whereClause; /* qualifications */
+ List *columns; /* List of columns in a publication table */
+} PublicationTable;
+
+/*
+ * Publication object type
+ */
+typedef enum PublicationObjSpecType
+{
+ PUBLICATIONOBJ_TABLE, /* A table */
+ PUBLICATIONOBJ_TABLES_IN_SCHEMA, /* All tables in schema */
+ PUBLICATIONOBJ_TABLES_IN_CUR_SCHEMA, /* All tables in first element of
+ * search_path */
+ PUBLICATIONOBJ_CONTINUATION /* Continuation of previous type */
+} PublicationObjSpecType;
+
+typedef struct PublicationObjSpec
+{
+ NodeTag type;
+ PublicationObjSpecType pubobjtype; /* type of this publication object */
+ char *name;
+ PublicationTable *pubtable;
+ int location; /* token location, or -1 if unknown */
+} PublicationObjSpec;
+
+typedef struct CreatePublicationStmt
+{
+ NodeTag type;
+ char *pubname; /* Name of the publication */
+ List *options; /* List of DefElem nodes */
+ List *pubobjects; /* Optional list of publication objects */
+ bool for_all_tables; /* Special publication for all tables in db */
+} CreatePublicationStmt;
+
+typedef enum AlterPublicationAction
+{
+ AP_AddObjects, /* add objects to publication */
+ AP_DropObjects, /* remove objects from publication */
+ AP_SetObjects /* set list of objects */
+} AlterPublicationAction;
+
+typedef struct AlterPublicationStmt
+{
+ NodeTag type;
+ char *pubname; /* Name of the publication */
+
+ /* parameters used for ALTER PUBLICATION ... WITH */
+ List *options; /* List of DefElem nodes */
+
+ /*
+ * Parameters used for ALTER PUBLICATION ... ADD/DROP/SET publication
+ * objects.
+ */
+ List *pubobjects; /* Optional list of publication objects */
+ bool for_all_tables; /* Special publication for all tables in db */
+ AlterPublicationAction action; /* What action to perform with the given
+ * objects */
+} AlterPublicationStmt;
+
+typedef struct CreateSubscriptionStmt
+{
+ NodeTag type;
+ char *subname; /* Name of the subscription */
+ char *conninfo; /* Connection string to publisher */
+ List *publication; /* One or more publication to subscribe to */
+ List *options; /* List of DefElem nodes */
+} CreateSubscriptionStmt;
+
+typedef enum AlterSubscriptionType
+{
+ ALTER_SUBSCRIPTION_OPTIONS,
+ ALTER_SUBSCRIPTION_CONNECTION,
+ ALTER_SUBSCRIPTION_SET_PUBLICATION,
+ ALTER_SUBSCRIPTION_ADD_PUBLICATION,
+ ALTER_SUBSCRIPTION_DROP_PUBLICATION,
+ ALTER_SUBSCRIPTION_REFRESH,
+ ALTER_SUBSCRIPTION_ENABLED,
+ ALTER_SUBSCRIPTION_SKIP
+} AlterSubscriptionType;
+
+typedef struct AlterSubscriptionStmt
+{
+ NodeTag type;
+ AlterSubscriptionType kind; /* ALTER_SUBSCRIPTION_OPTIONS, etc */
+ char *subname; /* Name of the subscription */
+ char *conninfo; /* Connection string to publisher */
+ List *publication; /* One or more publication to subscribe to */
+ List *options; /* List of DefElem nodes */
+} AlterSubscriptionStmt;
+
+typedef struct DropSubscriptionStmt
+{
+ NodeTag type;
+ char *subname; /* Name of the subscription */
+ bool missing_ok; /* Skip error if missing? */
+ DropBehavior behavior; /* RESTRICT or CASCADE behavior */
+} DropSubscriptionStmt;
+
+#endif /* PARSENODES_H */
diff --git a/pgsql/include/server/nodes/pathnodes.h b/pgsql/include/server/nodes/pathnodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..94aebadd9f9e9a85189a99a7dfda4867c139a87d
--- /dev/null
+++ b/pgsql/include/server/nodes/pathnodes.h
@@ -0,0 +1,3384 @@
+/*-------------------------------------------------------------------------
+ *
+ * pathnodes.h
+ * Definitions for planner's internal data structures, especially Paths.
+ *
+ * We don't support copying RelOptInfo, IndexOptInfo, or Path nodes.
+ * There are some subsidiary structs that are useful to copy, though.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/pathnodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PATHNODES_H
+#define PATHNODES_H
+
+#include "access/sdir.h"
+#include "lib/stringinfo.h"
+#include "nodes/params.h"
+#include "nodes/parsenodes.h"
+#include "storage/block.h"
+
+
+/*
+ * Relids
+ * Set of relation identifiers (indexes into the rangetable).
+ */
+typedef Bitmapset *Relids;
+
+/*
+ * When looking for a "cheapest path", this enum specifies whether we want
+ * cheapest startup cost or cheapest total cost.
+ */
+typedef enum CostSelector
+{
+ STARTUP_COST, TOTAL_COST
+} CostSelector;
+
+/*
+ * The cost estimate produced by cost_qual_eval() includes both a one-time
+ * (startup) cost, and a per-tuple cost.
+ */
+typedef struct QualCost
+{
+ Cost startup; /* one-time cost */
+ Cost per_tuple; /* per-evaluation cost */
+} QualCost;
+
+/*
+ * Costing aggregate function execution requires these statistics about
+ * the aggregates to be executed by a given Agg node. Note that the costs
+ * include the execution costs of the aggregates' argument expressions as
+ * well as the aggregate functions themselves. Also, the fields must be
+ * defined so that initializing the struct to zeroes with memset is correct.
+ */
+typedef struct AggClauseCosts
+{
+ QualCost transCost; /* total per-input-row execution costs */
+ QualCost finalCost; /* total per-aggregated-row costs */
+ Size transitionSpace; /* space for pass-by-ref transition data */
+} AggClauseCosts;
+
+/*
+ * This enum identifies the different types of "upper" (post-scan/join)
+ * relations that we might deal with during planning.
+ */
+typedef enum UpperRelationKind
+{
+ UPPERREL_SETOP, /* result of UNION/INTERSECT/EXCEPT, if any */
+ UPPERREL_PARTIAL_GROUP_AGG, /* result of partial grouping/aggregation, if
+ * any */
+ UPPERREL_GROUP_AGG, /* result of grouping/aggregation, if any */
+ UPPERREL_WINDOW, /* result of window functions, if any */
+ UPPERREL_PARTIAL_DISTINCT, /* result of partial "SELECT DISTINCT", if any */
+ UPPERREL_DISTINCT, /* result of "SELECT DISTINCT", if any */
+ UPPERREL_ORDERED, /* result of ORDER BY, if any */
+ UPPERREL_FINAL /* result of any remaining top-level actions */
+ /* NB: UPPERREL_FINAL must be last enum entry; it's used to size arrays */
+} UpperRelationKind;
+
+/*----------
+ * PlannerGlobal
+ * Global information for planning/optimization
+ *
+ * PlannerGlobal holds state for an entire planner invocation; this state
+ * is shared across all levels of sub-Queries that exist in the command being
+ * planned.
+ *
+ * Not all fields are printed. (In some cases, there is no print support for
+ * the field type; in others, doing so would lead to infinite recursion.)
+ *----------
+ */
+typedef struct PlannerGlobal
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* Param values provided to planner() */
+ ParamListInfo boundParams pg_node_attr(read_write_ignore);
+
+ /* Plans for SubPlan nodes */
+ List *subplans;
+
+ /* PlannerInfos for SubPlan nodes */
+ List *subroots pg_node_attr(read_write_ignore);
+
+ /* indices of subplans that require REWIND */
+ Bitmapset *rewindPlanIDs;
+
+ /* "flat" rangetable for executor */
+ List *finalrtable;
+
+ /* "flat" list of RTEPermissionInfos */
+ List *finalrteperminfos;
+
+ /* "flat" list of PlanRowMarks */
+ List *finalrowmarks;
+
+ /* "flat" list of integer RT indexes */
+ List *resultRelations;
+
+ /* "flat" list of AppendRelInfos */
+ List *appendRelations;
+
+ /* OIDs of relations the plan depends on */
+ List *relationOids;
+
+ /* other dependencies, as PlanInvalItems */
+ List *invalItems;
+
+ /* type OIDs for PARAM_EXEC Params */
+ List *paramExecTypes;
+
+ /* highest PlaceHolderVar ID assigned */
+ Index lastPHId;
+
+ /* highest PlanRowMark ID assigned */
+ Index lastRowMarkId;
+
+ /* highest plan node ID assigned */
+ int lastPlanNodeId;
+
+ /* redo plan when TransactionXmin changes? */
+ bool transientPlan;
+
+ /* is plan specific to current role? */
+ bool dependsOnRole;
+
+ /* parallel mode potentially OK? */
+ bool parallelModeOK;
+
+ /* parallel mode actually required? */
+ bool parallelModeNeeded;
+
+ /* worst PROPARALLEL hazard level */
+ char maxParallelHazard;
+
+ /* partition descriptors */
+ PartitionDirectory partition_directory pg_node_attr(read_write_ignore);
+} PlannerGlobal;
+
+/* macro for fetching the Plan associated with a SubPlan node */
+#define planner_subplan_get_plan(root, subplan) \
+ ((Plan *) list_nth((root)->glob->subplans, (subplan)->plan_id - 1))
+
+
+/*----------
+ * PlannerInfo
+ * Per-query information for planning/optimization
+ *
+ * This struct is conventionally called "root" in all the planner routines.
+ * It holds links to all of the planner's working state, in addition to the
+ * original Query. Note that at present the planner extensively modifies
+ * the passed-in Query data structure; someday that should stop.
+ *
+ * For reasons explained in optimizer/optimizer.h, we define the typedef
+ * either here or in that header, whichever is read first.
+ *
+ * Not all fields are printed. (In some cases, there is no print support for
+ * the field type; in others, doing so would lead to infinite recursion or
+ * bloat dump output more than seems useful.)
+ *----------
+ */
+#ifndef HAVE_PLANNERINFO_TYPEDEF
+typedef struct PlannerInfo PlannerInfo;
+#define HAVE_PLANNERINFO_TYPEDEF 1
+#endif
+
+struct PlannerInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* the Query being planned */
+ Query *parse;
+
+ /* global info for current planner run */
+ PlannerGlobal *glob;
+
+ /* 1 at the outermost Query */
+ Index query_level;
+
+ /* NULL at outermost Query */
+ PlannerInfo *parent_root pg_node_attr(read_write_ignore);
+
+ /*
+ * plan_params contains the expressions that this query level needs to
+ * make available to a lower query level that is currently being planned.
+ * outer_params contains the paramIds of PARAM_EXEC Params that outer
+ * query levels will make available to this query level.
+ */
+ /* list of PlannerParamItems, see below */
+ List *plan_params;
+ Bitmapset *outer_params;
+
+ /*
+ * simple_rel_array holds pointers to "base rels" and "other rels" (see
+ * comments for RelOptInfo for more info). It is indexed by rangetable
+ * index (so entry 0 is always wasted). Entries can be NULL when an RTE
+ * does not correspond to a base relation, such as a join RTE or an
+ * unreferenced view RTE; or if the RelOptInfo hasn't been made yet.
+ */
+ struct RelOptInfo **simple_rel_array pg_node_attr(array_size(simple_rel_array_size));
+ /* allocated size of array */
+ int simple_rel_array_size;
+
+ /*
+ * simple_rte_array is the same length as simple_rel_array and holds
+ * pointers to the associated rangetable entries. Using this is a shade
+ * faster than using rt_fetch(), mostly due to fewer indirections. (Not
+ * printed because it'd be redundant with parse->rtable.)
+ */
+ RangeTblEntry **simple_rte_array pg_node_attr(read_write_ignore);
+
+ /*
+ * append_rel_array is the same length as the above arrays, and holds
+ * pointers to the corresponding AppendRelInfo entry indexed by
+ * child_relid, or NULL if the rel is not an appendrel child. The array
+ * itself is not allocated if append_rel_list is empty. (Not printed
+ * because it'd be redundant with append_rel_list.)
+ */
+ struct AppendRelInfo **append_rel_array pg_node_attr(read_write_ignore);
+
+ /*
+ * all_baserels is a Relids set of all base relids (but not joins or
+ * "other" rels) in the query. This is computed in deconstruct_jointree.
+ */
+ Relids all_baserels;
+
+ /*
+ * outer_join_rels is a Relids set of all outer-join relids in the query.
+ * This is computed in deconstruct_jointree.
+ */
+ Relids outer_join_rels;
+
+ /*
+ * all_query_rels is a Relids set of all base relids and outer join relids
+ * (but not "other" relids) in the query. This is the Relids identifier
+ * of the final join we need to form. This is computed in
+ * deconstruct_jointree.
+ */
+ Relids all_query_rels;
+
+ /*
+ * join_rel_list is a list of all join-relation RelOptInfos we have
+ * considered in this planning run. For small problems we just scan the
+ * list to do lookups, but when there are many join relations we build a
+ * hash table for faster lookups. The hash table is present and valid
+ * when join_rel_hash is not NULL. Note that we still maintain the list
+ * even when using the hash table for lookups; this simplifies life for
+ * GEQO.
+ */
+ List *join_rel_list;
+ struct HTAB *join_rel_hash pg_node_attr(read_write_ignore);
+
+ /*
+ * When doing a dynamic-programming-style join search, join_rel_level[k]
+ * is a list of all join-relation RelOptInfos of level k, and
+ * join_cur_level is the current level. New join-relation RelOptInfos are
+ * automatically added to the join_rel_level[join_cur_level] list.
+ * join_rel_level is NULL if not in use.
+ *
+ * Note: we've already printed all baserel and joinrel RelOptInfos above,
+ * so we don't dump join_rel_level or other lists of RelOptInfos.
+ */
+ /* lists of join-relation RelOptInfos */
+ List **join_rel_level pg_node_attr(read_write_ignore);
+ /* index of list being extended */
+ int join_cur_level;
+
+ /* init SubPlans for query */
+ List *init_plans;
+
+ /*
+ * per-CTE-item list of subplan IDs (or -1 if no subplan was made for that
+ * CTE)
+ */
+ List *cte_plan_ids;
+
+ /* List of Lists of Params for MULTIEXPR subquery outputs */
+ List *multiexpr_params;
+
+ /* list of JoinDomains used in the query (higher ones first) */
+ List *join_domains;
+
+ /* list of active EquivalenceClasses */
+ List *eq_classes;
+
+ /* set true once ECs are canonical */
+ bool ec_merging_done;
+
+ /* list of "canonical" PathKeys */
+ List *canon_pathkeys;
+
+ /*
+ * list of OuterJoinClauseInfos for mergejoinable outer join clauses
+ * w/nonnullable var on left
+ */
+ List *left_join_clauses;
+
+ /*
+ * list of OuterJoinClauseInfos for mergejoinable outer join clauses
+ * w/nonnullable var on right
+ */
+ List *right_join_clauses;
+
+ /*
+ * list of OuterJoinClauseInfos for mergejoinable full join clauses
+ */
+ List *full_join_clauses;
+
+ /* list of SpecialJoinInfos */
+ List *join_info_list;
+
+ /* counter for assigning RestrictInfo serial numbers */
+ int last_rinfo_serial;
+
+ /*
+ * all_result_relids is empty for SELECT, otherwise it contains at least
+ * parse->resultRelation. For UPDATE/DELETE/MERGE across an inheritance
+ * or partitioning tree, the result rel's child relids are added. When
+ * using multi-level partitioning, intermediate partitioned rels are
+ * included. leaf_result_relids is similar except that only actual result
+ * tables, not partitioned tables, are included in it.
+ */
+ /* set of all result relids */
+ Relids all_result_relids;
+ /* set of all leaf relids */
+ Relids leaf_result_relids;
+
+ /*
+ * list of AppendRelInfos
+ *
+ * Note: for AppendRelInfos describing partitions of a partitioned table,
+ * we guarantee that partitions that come earlier in the partitioned
+ * table's PartitionDesc will appear earlier in append_rel_list.
+ */
+ List *append_rel_list;
+
+ /* list of RowIdentityVarInfos */
+ List *row_identity_vars;
+
+ /* list of PlanRowMarks */
+ List *rowMarks;
+
+ /* list of PlaceHolderInfos */
+ List *placeholder_list;
+
+ /* array of PlaceHolderInfos indexed by phid */
+ struct PlaceHolderInfo **placeholder_array pg_node_attr(read_write_ignore, array_size(placeholder_array_size));
+ /* allocated size of array */
+ int placeholder_array_size pg_node_attr(read_write_ignore);
+
+ /* list of ForeignKeyOptInfos */
+ List *fkey_list;
+
+ /* desired pathkeys for query_planner() */
+ List *query_pathkeys;
+
+ /* groupClause pathkeys, if any */
+ List *group_pathkeys;
+
+ /*
+ * The number of elements in the group_pathkeys list which belong to the
+ * GROUP BY clause. Additional ones belong to ORDER BY / DISTINCT
+ * aggregates.
+ */
+ int num_groupby_pathkeys;
+
+ /* pathkeys of bottom window, if any */
+ List *window_pathkeys;
+ /* distinctClause pathkeys, if any */
+ List *distinct_pathkeys;
+ /* sortClause pathkeys, if any */
+ List *sort_pathkeys;
+
+ /* Canonicalised partition schemes used in the query. */
+ List *part_schemes pg_node_attr(read_write_ignore);
+
+ /* RelOptInfos we are now trying to join */
+ List *initial_rels pg_node_attr(read_write_ignore);
+
+ /*
+ * Upper-rel RelOptInfos. Use fetch_upper_rel() to get any particular
+ * upper rel.
+ */
+ List *upper_rels[UPPERREL_FINAL + 1] pg_node_attr(read_write_ignore);
+
+ /* Result tlists chosen by grouping_planner for upper-stage processing */
+ struct PathTarget *upper_targets[UPPERREL_FINAL + 1] pg_node_attr(read_write_ignore);
+
+ /*
+ * The fully-processed groupClause is kept here. It differs from
+ * parse->groupClause in that we remove any items that we can prove
+ * redundant, so that only the columns named here actually need to be
+ * compared to determine grouping. Note that it's possible for *all* the
+ * items to be proven redundant, implying that there is only one group
+ * containing all the query's rows. Hence, if you want to check whether
+ * GROUP BY was specified, test for nonempty parse->groupClause, not for
+ * nonempty processed_groupClause.
+ *
+ * Currently, when grouping sets are specified we do not attempt to
+ * optimize the groupClause, so that processed_groupClause will be
+ * identical to parse->groupClause.
+ */
+ List *processed_groupClause;
+
+ /*
+ * The fully-processed distinctClause is kept here. It differs from
+ * parse->distinctClause in that we remove any items that we can prove
+ * redundant, so that only the columns named here actually need to be
+ * compared to determine uniqueness. Note that it's possible for *all*
+ * the items to be proven redundant, implying that there should be only
+ * one output row. Hence, if you want to check whether DISTINCT was
+ * specified, test for nonempty parse->distinctClause, not for nonempty
+ * processed_distinctClause.
+ */
+ List *processed_distinctClause;
+
+ /*
+ * The fully-processed targetlist is kept here. It differs from
+ * parse->targetList in that (for INSERT) it's been reordered to match the
+ * target table, and defaults have been filled in. Also, additional
+ * resjunk targets may be present. preprocess_targetlist() does most of
+ * that work, but note that more resjunk targets can get added during
+ * appendrel expansion. (Hence, upper_targets mustn't get set up till
+ * after that.)
+ */
+ List *processed_tlist;
+
+ /*
+ * For UPDATE, this list contains the target table's attribute numbers to
+ * which the first N entries of processed_tlist are to be assigned. (Any
+ * additional entries in processed_tlist must be resjunk.) DO NOT use the
+ * resnos in processed_tlist to identify the UPDATE target columns.
+ */
+ List *update_colnos;
+
+ /*
+ * Fields filled during create_plan() for use in setrefs.c
+ */
+ /* for GroupingFunc fixup (can't print: array length not known here) */
+ AttrNumber *grouping_map pg_node_attr(read_write_ignore);
+ /* List of MinMaxAggInfos */
+ List *minmax_aggs;
+
+ /* context holding PlannerInfo */
+ MemoryContext planner_cxt pg_node_attr(read_write_ignore);
+
+ /* # of pages in all non-dummy tables of query */
+ Cardinality total_table_pages;
+
+ /* tuple_fraction passed to query_planner */
+ Selectivity tuple_fraction;
+ /* limit_tuples passed to query_planner */
+ Cardinality limit_tuples;
+
+ /*
+ * Minimum security_level for quals. Note: qual_security_level is zero if
+ * there are no securityQuals.
+ */
+ Index qual_security_level;
+
+ /* true if any RTEs are RTE_JOIN kind */
+ bool hasJoinRTEs;
+ /* true if any RTEs are marked LATERAL */
+ bool hasLateralRTEs;
+ /* true if havingQual was non-null */
+ bool hasHavingQual;
+ /* true if any RestrictInfo has pseudoconstant = true */
+ bool hasPseudoConstantQuals;
+ /* true if we've made any of those */
+ bool hasAlternativeSubPlans;
+ /* true once we're no longer allowed to add PlaceHolderInfos */
+ bool placeholdersFrozen;
+ /* true if planning a recursive WITH item */
+ bool hasRecursion;
+
+ /*
+ * Information about aggregates. Filled by preprocess_aggrefs().
+ */
+ /* AggInfo structs */
+ List *agginfos;
+ /* AggTransInfo structs */
+ List *aggtransinfos;
+ /* number of aggs with DISTINCT/ORDER BY/WITHIN GROUP */
+ int numOrderedAggs;
+ /* does any agg not support partial mode? */
+ bool hasNonPartialAggs;
+ /* is any partial agg non-serializable? */
+ bool hasNonSerialAggs;
+
+ /*
+ * These fields are used only when hasRecursion is true:
+ */
+ /* PARAM_EXEC ID for the work table */
+ int wt_param_id;
+ /* a path for non-recursive term */
+ struct Path *non_recursive_path;
+
+ /*
+ * These fields are workspace for createplan.c
+ */
+ /* outer rels above current node */
+ Relids curOuterRels;
+ /* not-yet-assigned NestLoopParams */
+ List *curOuterParams;
+
+ /*
+ * These fields are workspace for setrefs.c. Each is an array
+ * corresponding to glob->subplans. (We could probably teach
+ * gen_node_support.pl how to determine the array length, but it doesn't
+ * seem worth the trouble, so just mark them read_write_ignore.)
+ */
+ bool *isAltSubplan pg_node_attr(read_write_ignore);
+ bool *isUsedSubplan pg_node_attr(read_write_ignore);
+
+ /* optional private data for join_search_hook, e.g., GEQO */
+ void *join_search_private pg_node_attr(read_write_ignore);
+
+ /* Does this query modify any partition key columns? */
+ bool partColsUpdated;
+};
+
+
+/*
+ * In places where it's known that simple_rte_array[] must have been prepared
+ * already, we just index into it to fetch RTEs. In code that might be
+ * executed before or after entering query_planner(), use this macro.
+ */
+#define planner_rt_fetch(rti, root) \
+ ((root)->simple_rte_array ? (root)->simple_rte_array[rti] : \
+ rt_fetch(rti, (root)->parse->rtable))
+
+/*
+ * If multiple relations are partitioned the same way, all such partitions
+ * will have a pointer to the same PartitionScheme. A list of PartitionScheme
+ * objects is attached to the PlannerInfo. By design, the partition scheme
+ * incorporates only the general properties of the partition method (LIST vs.
+ * RANGE, number of partitioning columns and the type information for each)
+ * and not the specific bounds.
+ *
+ * We store the opclass-declared input data types instead of the partition key
+ * datatypes since the former rather than the latter are used to compare
+ * partition bounds. Since partition key data types and the opclass declared
+ * input data types are expected to be binary compatible (per ResolveOpClass),
+ * both of those should have same byval and length properties.
+ */
+typedef struct PartitionSchemeData
+{
+ char strategy; /* partition strategy */
+ int16 partnatts; /* number of partition attributes */
+ Oid *partopfamily; /* OIDs of operator families */
+ Oid *partopcintype; /* OIDs of opclass declared input data types */
+ Oid *partcollation; /* OIDs of partitioning collations */
+
+ /* Cached information about partition key data types. */
+ int16 *parttyplen;
+ bool *parttypbyval;
+
+ /* Cached information about partition comparison functions. */
+ struct FmgrInfo *partsupfunc;
+} PartitionSchemeData;
+
+typedef struct PartitionSchemeData *PartitionScheme;
+
+/*----------
+ * RelOptInfo
+ * Per-relation information for planning/optimization
+ *
+ * For planning purposes, a "base rel" is either a plain relation (a table)
+ * or the output of a sub-SELECT or function that appears in the range table.
+ * In either case it is uniquely identified by an RT index. A "joinrel"
+ * is the joining of two or more base rels. A joinrel is identified by
+ * the set of RT indexes for its component baserels, along with RT indexes
+ * for any outer joins it has computed. We create RelOptInfo nodes for each
+ * baserel and joinrel, and store them in the PlannerInfo's simple_rel_array
+ * and join_rel_list respectively.
+ *
+ * Note that there is only one joinrel for any given set of component
+ * baserels, no matter what order we assemble them in; so an unordered
+ * set is the right datatype to identify it with.
+ *
+ * We also have "other rels", which are like base rels in that they refer to
+ * single RT indexes; but they are not part of the join tree, and are given
+ * a different RelOptKind to identify them.
+ * Currently the only kind of otherrels are those made for member relations
+ * of an "append relation", that is an inheritance set or UNION ALL subquery.
+ * An append relation has a parent RTE that is a base rel, which represents
+ * the entire append relation. The member RTEs are otherrels. The parent
+ * is present in the query join tree but the members are not. The member
+ * RTEs and otherrels are used to plan the scans of the individual tables or
+ * subqueries of the append set; then the parent baserel is given Append
+ * and/or MergeAppend paths comprising the best paths for the individual
+ * member rels. (See comments for AppendRelInfo for more information.)
+ *
+ * At one time we also made otherrels to represent join RTEs, for use in
+ * handling join alias Vars. Currently this is not needed because all join
+ * alias Vars are expanded to non-aliased form during preprocess_expression.
+ *
+ * We also have relations representing joins between child relations of
+ * different partitioned tables. These relations are not added to
+ * join_rel_level lists as they are not joined directly by the dynamic
+ * programming algorithm.
+ *
+ * There is also a RelOptKind for "upper" relations, which are RelOptInfos
+ * that describe post-scan/join processing steps, such as aggregation.
+ * Many of the fields in these RelOptInfos are meaningless, but their Path
+ * fields always hold Paths showing ways to do that processing step.
+ *
+ * Parts of this data structure are specific to various scan and join
+ * mechanisms. It didn't seem worth creating new node types for them.
+ *
+ * relids - Set of relation identifiers (RT indexes). This is a base
+ * relation if there is just one, a join relation if more;
+ * in the join case, RT indexes of any outer joins formed
+ * at or below this join are included along with baserels
+ * rows - estimated number of tuples in the relation after restriction
+ * clauses have been applied (ie, output rows of a plan for it)
+ * consider_startup - true if there is any value in keeping plain paths for
+ * this rel on the basis of having cheap startup cost
+ * consider_param_startup - the same for parameterized paths
+ * reltarget - Default Path output tlist for this rel; normally contains
+ * Var and PlaceHolderVar nodes for the values we need to
+ * output from this relation.
+ * List is in no particular order, but all rels of an
+ * appendrel set must use corresponding orders.
+ * NOTE: in an appendrel child relation, may contain
+ * arbitrary expressions pulled up from a subquery!
+ * pathlist - List of Path nodes, one for each potentially useful
+ * method of generating the relation
+ * ppilist - ParamPathInfo nodes for parameterized Paths, if any
+ * cheapest_startup_path - the pathlist member with lowest startup cost
+ * (regardless of ordering) among the unparameterized paths;
+ * or NULL if there is no unparameterized path
+ * cheapest_total_path - the pathlist member with lowest total cost
+ * (regardless of ordering) among the unparameterized paths;
+ * or if there is no unparameterized path, the path with lowest
+ * total cost among the paths with minimum parameterization
+ * cheapest_unique_path - for caching cheapest path to produce unique
+ * (no duplicates) output from relation; NULL if not yet requested
+ * cheapest_parameterized_paths - best paths for their parameterizations;
+ * always includes cheapest_total_path, even if that's unparameterized
+ * direct_lateral_relids - rels this rel has direct LATERAL references to
+ * lateral_relids - required outer rels for LATERAL, as a Relids set
+ * (includes both direct and indirect lateral references)
+ *
+ * If the relation is a base relation it will have these fields set:
+ *
+ * relid - RTE index (this is redundant with the relids field, but
+ * is provided for convenience of access)
+ * rtekind - copy of RTE's rtekind field
+ * min_attr, max_attr - range of valid AttrNumbers for rel
+ * attr_needed - array of bitmapsets indicating the highest joinrel
+ * in which each attribute is needed; if bit 0 is set then
+ * the attribute is needed as part of final targetlist
+ * attr_widths - cache space for per-attribute width estimates;
+ * zero means not computed yet
+ * nulling_relids - relids of outer joins that can null this rel
+ * lateral_vars - lateral cross-references of rel, if any (list of
+ * Vars and PlaceHolderVars)
+ * lateral_referencers - relids of rels that reference this one laterally
+ * (includes both direct and indirect lateral references)
+ * indexlist - list of IndexOptInfo nodes for relation's indexes
+ * (always NIL if it's not a table or partitioned table)
+ * pages - number of disk pages in relation (zero if not a table)
+ * tuples - number of tuples in relation (not considering restrictions)
+ * allvisfrac - fraction of disk pages that are marked all-visible
+ * eclass_indexes - EquivalenceClasses that mention this rel (filled
+ * only after EC merging is complete)
+ * subroot - PlannerInfo for subquery (NULL if it's not a subquery)
+ * subplan_params - list of PlannerParamItems to be passed to subquery
+ *
+ * Note: for a subquery, tuples and subroot are not set immediately
+ * upon creation of the RelOptInfo object; they are filled in when
+ * set_subquery_pathlist processes the object.
+ *
+ * For otherrels that are appendrel members, these fields are filled
+ * in just as for a baserel, except we don't bother with lateral_vars.
+ *
+ * If the relation is either a foreign table or a join of foreign tables that
+ * all belong to the same foreign server and are assigned to the same user to
+ * check access permissions as (cf checkAsUser), these fields will be set:
+ *
+ * serverid - OID of foreign server, if foreign table (else InvalidOid)
+ * userid - OID of user to check access as (InvalidOid means current user)
+ * useridiscurrent - we've assumed that userid equals current user
+ * fdwroutine - function hooks for FDW, if foreign table (else NULL)
+ * fdw_private - private state for FDW, if foreign table (else NULL)
+ *
+ * Two fields are used to cache knowledge acquired during the join search
+ * about whether this rel is provably unique when being joined to given other
+ * relation(s), ie, it can have at most one row matching any given row from
+ * that join relation. Currently we only attempt such proofs, and thus only
+ * populate these fields, for base rels; but someday they might be used for
+ * join rels too:
+ *
+ * unique_for_rels - list of Relid sets, each one being a set of other
+ * rels for which this one has been proven unique
+ * non_unique_for_rels - list of Relid sets, each one being a set of
+ * other rels for which we have tried and failed to prove
+ * this one unique
+ *
+ * The presence of the following fields depends on the restrictions
+ * and joins that the relation participates in:
+ *
+ * baserestrictinfo - List of RestrictInfo nodes, containing info about
+ * each non-join qualification clause in which this relation
+ * participates (only used for base rels)
+ * baserestrictcost - Estimated cost of evaluating the baserestrictinfo
+ * clauses at a single tuple (only used for base rels)
+ * baserestrict_min_security - Smallest security_level found among
+ * clauses in baserestrictinfo
+ * joininfo - List of RestrictInfo nodes, containing info about each
+ * join clause in which this relation participates (but
+ * note this excludes clauses that might be derivable from
+ * EquivalenceClasses)
+ * has_eclass_joins - flag that EquivalenceClass joins are possible
+ *
+ * Note: Keeping a restrictinfo list in the RelOptInfo is useful only for
+ * base rels, because for a join rel the set of clauses that are treated as
+ * restrict clauses varies depending on which sub-relations we choose to join.
+ * (For example, in a 3-base-rel join, a clause relating rels 1 and 2 must be
+ * treated as a restrictclause if we join {1} and {2 3} to make {1 2 3}; but
+ * if we join {1 2} and {3} then that clause will be a restrictclause in {1 2}
+ * and should not be processed again at the level of {1 2 3}.) Therefore,
+ * the restrictinfo list in the join case appears in individual JoinPaths
+ * (field joinrestrictinfo), not in the parent relation. But it's OK for
+ * the RelOptInfo to store the joininfo list, because that is the same
+ * for a given rel no matter how we form it.
+ *
+ * We store baserestrictcost in the RelOptInfo (for base relations) because
+ * we know we will need it at least once (to price the sequential scan)
+ * and may need it multiple times to price index scans.
+ *
+ * A join relation is considered to be partitioned if it is formed from a
+ * join of two relations that are partitioned, have matching partitioning
+ * schemes, and are joined on an equijoin of the partitioning columns.
+ * Under those conditions we can consider the join relation to be partitioned
+ * by either relation's partitioning keys, though some care is needed if
+ * either relation can be forced to null by outer-joining. For example, an
+ * outer join like (A LEFT JOIN B ON A.a = B.b) may produce rows with B.b
+ * NULL. These rows may not fit the partitioning conditions imposed on B.
+ * Hence, strictly speaking, the join is not partitioned by B.b and thus
+ * partition keys of an outer join should include partition key expressions
+ * from the non-nullable side only. However, if a subsequent join uses
+ * strict comparison operators (and all commonly-used equijoin operators are
+ * strict), the presence of nulls doesn't cause a problem: such rows couldn't
+ * match anything on the other side and thus they don't create a need to do
+ * any cross-partition sub-joins. Hence we can treat such values as still
+ * partitioning the join output for the purpose of additional partitionwise
+ * joining, so long as a strict join operator is used by the next join.
+ *
+ * If the relation is partitioned, these fields will be set:
+ *
+ * part_scheme - Partitioning scheme of the relation
+ * nparts - Number of partitions
+ * boundinfo - Partition bounds
+ * partbounds_merged - true if partition bounds are merged ones
+ * partition_qual - Partition constraint if not the root
+ * part_rels - RelOptInfos for each partition
+ * all_partrels - Relids set of all partition relids
+ * partexprs, nullable_partexprs - Partition key expressions
+ *
+ * The partexprs and nullable_partexprs arrays each contain
+ * part_scheme->partnatts elements. Each of the elements is a list of
+ * partition key expressions. For partitioned base relations, there is one
+ * expression in each partexprs element, and nullable_partexprs is empty.
+ * For partitioned join relations, each base relation within the join
+ * contributes one partition key expression per partitioning column;
+ * that expression goes in the partexprs[i] list if the base relation
+ * is not nullable by this join or any lower outer join, or in the
+ * nullable_partexprs[i] list if the base relation is nullable.
+ * Furthermore, FULL JOINs add extra nullable_partexprs expressions
+ * corresponding to COALESCE expressions of the left and right join columns,
+ * to simplify matching join clauses to those lists.
+ *
+ * Not all fields are printed. (In some cases, there is no print support for
+ * the field type.)
+ *----------
+ */
+
+/* Bitmask of flags supported by table AMs */
+#define AMFLAG_HAS_TID_RANGE (1 << 0)
+
+typedef enum RelOptKind
+{
+ RELOPT_BASEREL,
+ RELOPT_JOINREL,
+ RELOPT_OTHER_MEMBER_REL,
+ RELOPT_OTHER_JOINREL,
+ RELOPT_UPPER_REL,
+ RELOPT_OTHER_UPPER_REL
+} RelOptKind;
+
+/*
+ * Is the given relation a simple relation i.e a base or "other" member
+ * relation?
+ */
+#define IS_SIMPLE_REL(rel) \
+ ((rel)->reloptkind == RELOPT_BASEREL || \
+ (rel)->reloptkind == RELOPT_OTHER_MEMBER_REL)
+
+/* Is the given relation a join relation? */
+#define IS_JOIN_REL(rel) \
+ ((rel)->reloptkind == RELOPT_JOINREL || \
+ (rel)->reloptkind == RELOPT_OTHER_JOINREL)
+
+/* Is the given relation an upper relation? */
+#define IS_UPPER_REL(rel) \
+ ((rel)->reloptkind == RELOPT_UPPER_REL || \
+ (rel)->reloptkind == RELOPT_OTHER_UPPER_REL)
+
+/* Is the given relation an "other" relation? */
+#define IS_OTHER_REL(rel) \
+ ((rel)->reloptkind == RELOPT_OTHER_MEMBER_REL || \
+ (rel)->reloptkind == RELOPT_OTHER_JOINREL || \
+ (rel)->reloptkind == RELOPT_OTHER_UPPER_REL)
+
+typedef struct RelOptInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ RelOptKind reloptkind;
+
+ /*
+ * all relations included in this RelOptInfo; set of base + OJ relids
+ * (rangetable indexes)
+ */
+ Relids relids;
+
+ /*
+ * size estimates generated by planner
+ */
+ /* estimated number of result tuples */
+ Cardinality rows;
+
+ /*
+ * per-relation planner control flags
+ */
+ /* keep cheap-startup-cost paths? */
+ bool consider_startup;
+ /* ditto, for parameterized paths? */
+ bool consider_param_startup;
+ /* consider parallel paths? */
+ bool consider_parallel;
+
+ /*
+ * default result targetlist for Paths scanning this relation; list of
+ * Vars/Exprs, cost, width
+ */
+ struct PathTarget *reltarget;
+
+ /*
+ * materialization information
+ */
+ List *pathlist; /* Path structures */
+ List *ppilist; /* ParamPathInfos used in pathlist */
+ List *partial_pathlist; /* partial Paths */
+ struct Path *cheapest_startup_path;
+ struct Path *cheapest_total_path;
+ struct Path *cheapest_unique_path;
+ List *cheapest_parameterized_paths;
+
+ /*
+ * parameterization information needed for both base rels and join rels
+ * (see also lateral_vars and lateral_referencers)
+ */
+ /* rels directly laterally referenced */
+ Relids direct_lateral_relids;
+ /* minimum parameterization of rel */
+ Relids lateral_relids;
+
+ /*
+ * information about a base rel (not set for join rels!)
+ */
+ Index relid;
+ /* containing tablespace */
+ Oid reltablespace;
+ /* RELATION, SUBQUERY, FUNCTION, etc */
+ RTEKind rtekind;
+ /* smallest attrno of rel (often <0) */
+ AttrNumber min_attr;
+ /* largest attrno of rel */
+ AttrNumber max_attr;
+ /* array indexed [min_attr .. max_attr] */
+ Relids *attr_needed pg_node_attr(read_write_ignore);
+ /* array indexed [min_attr .. max_attr] */
+ int32 *attr_widths pg_node_attr(read_write_ignore);
+ /* relids of outer joins that can null this baserel */
+ Relids nulling_relids;
+ /* LATERAL Vars and PHVs referenced by rel */
+ List *lateral_vars;
+ /* rels that reference this baserel laterally */
+ Relids lateral_referencers;
+ /* list of IndexOptInfo */
+ List *indexlist;
+ /* list of StatisticExtInfo */
+ List *statlist;
+ /* size estimates derived from pg_class */
+ BlockNumber pages;
+ Cardinality tuples;
+ double allvisfrac;
+ /* indexes in PlannerInfo's eq_classes list of ECs that mention this rel */
+ Bitmapset *eclass_indexes;
+ PlannerInfo *subroot; /* if subquery */
+ List *subplan_params; /* if subquery */
+ /* wanted number of parallel workers */
+ int rel_parallel_workers;
+ /* Bitmask of optional features supported by the table AM */
+ uint32 amflags;
+
+ /*
+ * Information about foreign tables and foreign joins
+ */
+ /* identifies server for the table or join */
+ Oid serverid;
+ /* identifies user to check access as; 0 means to check as current user */
+ Oid userid;
+ /* join is only valid for current user */
+ bool useridiscurrent;
+ /* use "struct FdwRoutine" to avoid including fdwapi.h here */
+ struct FdwRoutine *fdwroutine pg_node_attr(read_write_ignore);
+ void *fdw_private pg_node_attr(read_write_ignore);
+
+ /*
+ * cache space for remembering if we have proven this relation unique
+ */
+ /* known unique for these other relid set(s) */
+ List *unique_for_rels;
+ /* known not unique for these set(s) */
+ List *non_unique_for_rels;
+
+ /*
+ * used by various scans and joins:
+ */
+ /* RestrictInfo structures (if base rel) */
+ List *baserestrictinfo;
+ /* cost of evaluating the above */
+ QualCost baserestrictcost;
+ /* min security_level found in baserestrictinfo */
+ Index baserestrict_min_security;
+ /* RestrictInfo structures for join clauses involving this rel */
+ List *joininfo;
+ /* T means joininfo is incomplete */
+ bool has_eclass_joins;
+
+ /*
+ * used by partitionwise joins:
+ */
+ /* consider partitionwise join paths? (if partitioned rel) */
+ bool consider_partitionwise_join;
+
+ /*
+ * inheritance links, if this is an otherrel (otherwise NULL):
+ */
+ /* Immediate parent relation (dumping it would be too verbose) */
+ struct RelOptInfo *parent pg_node_attr(read_write_ignore);
+ /* Topmost parent relation (dumping it would be too verbose) */
+ struct RelOptInfo *top_parent pg_node_attr(read_write_ignore);
+ /* Relids of topmost parent (redundant, but handy) */
+ Relids top_parent_relids;
+
+ /*
+ * used for partitioned relations:
+ */
+ /* Partitioning scheme */
+ PartitionScheme part_scheme pg_node_attr(read_write_ignore);
+
+ /*
+ * Number of partitions; -1 if not yet set; in case of a join relation 0
+ * means it's considered unpartitioned
+ */
+ int nparts;
+ /* Partition bounds */
+ struct PartitionBoundInfoData *boundinfo pg_node_attr(read_write_ignore);
+ /* True if partition bounds were created by partition_bounds_merge() */
+ bool partbounds_merged;
+ /* Partition constraint, if not the root */
+ List *partition_qual;
+
+ /*
+ * Array of RelOptInfos of partitions, stored in the same order as bounds
+ * (don't print, too bulky and duplicative)
+ */
+ struct RelOptInfo **part_rels pg_node_attr(read_write_ignore);
+
+ /*
+ * Bitmap with members acting as indexes into the part_rels[] array to
+ * indicate which partitions survived partition pruning.
+ */
+ Bitmapset *live_parts;
+ /* Relids set of all partition relids */
+ Relids all_partrels;
+
+ /*
+ * These arrays are of length partkey->partnatts, which we don't have at
+ * hand, so don't try to print
+ */
+
+ /* Non-nullable partition key expressions */
+ List **partexprs pg_node_attr(read_write_ignore);
+ /* Nullable partition key expressions */
+ List **nullable_partexprs pg_node_attr(read_write_ignore);
+} RelOptInfo;
+
+/*
+ * Is given relation partitioned?
+ *
+ * It's not enough to test whether rel->part_scheme is set, because it might
+ * be that the basic partitioning properties of the input relations matched
+ * but the partition bounds did not. Also, if we are able to prove a rel
+ * dummy (empty), we should henceforth treat it as unpartitioned.
+ */
+#define IS_PARTITIONED_REL(rel) \
+ ((rel)->part_scheme && (rel)->boundinfo && (rel)->nparts > 0 && \
+ (rel)->part_rels && !IS_DUMMY_REL(rel))
+
+/*
+ * Convenience macro to make sure that a partitioned relation has all the
+ * required members set.
+ */
+#define REL_HAS_ALL_PART_PROPS(rel) \
+ ((rel)->part_scheme && (rel)->boundinfo && (rel)->nparts > 0 && \
+ (rel)->part_rels && (rel)->partexprs && (rel)->nullable_partexprs)
+
+/*
+ * IndexOptInfo
+ * Per-index information for planning/optimization
+ *
+ * indexkeys[], indexcollations[] each have ncolumns entries.
+ * opfamily[], and opcintype[] each have nkeycolumns entries. They do
+ * not contain any information about included attributes.
+ *
+ * sortopfamily[], reverse_sort[], and nulls_first[] have
+ * nkeycolumns entries, if the index is ordered; but if it is unordered,
+ * those pointers are NULL.
+ *
+ * Zeroes in the indexkeys[] array indicate index columns that are
+ * expressions; there is one element in indexprs for each such column.
+ *
+ * For an ordered index, reverse_sort[] and nulls_first[] describe the
+ * sort ordering of a forward indexscan; we can also consider a backward
+ * indexscan, which will generate the reverse ordering.
+ *
+ * The indexprs and indpred expressions have been run through
+ * prepqual.c and eval_const_expressions() for ease of matching to
+ * WHERE clauses. indpred is in implicit-AND form.
+ *
+ * indextlist is a TargetEntry list representing the index columns.
+ * It provides an equivalent base-relation Var for each simple column,
+ * and links to the matching indexprs element for each expression column.
+ *
+ * While most of these fields are filled when the IndexOptInfo is created
+ * (by plancat.c), indrestrictinfo and predOK are set later, in
+ * check_index_predicates().
+ */
+#ifndef HAVE_INDEXOPTINFO_TYPEDEF
+typedef struct IndexOptInfo IndexOptInfo;
+#define HAVE_INDEXOPTINFO_TYPEDEF 1
+#endif
+
+struct IndexOptInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* OID of the index relation */
+ Oid indexoid;
+ /* tablespace of index (not table) */
+ Oid reltablespace;
+ /* back-link to index's table; don't print, else infinite recursion */
+ RelOptInfo *rel pg_node_attr(read_write_ignore);
+
+ /*
+ * index-size statistics (from pg_class and elsewhere)
+ */
+ /* number of disk pages in index */
+ BlockNumber pages;
+ /* number of index tuples in index */
+ Cardinality tuples;
+ /* index tree height, or -1 if unknown */
+ int tree_height;
+
+ /*
+ * index descriptor information
+ */
+ /* number of columns in index */
+ int ncolumns;
+ /* number of key columns in index */
+ int nkeycolumns;
+
+ /*
+ * table column numbers of index's columns (both key and included
+ * columns), or 0 for expression columns
+ */
+ int *indexkeys pg_node_attr(array_size(ncolumns));
+ /* OIDs of collations of index columns */
+ Oid *indexcollations pg_node_attr(array_size(nkeycolumns));
+ /* OIDs of operator families for columns */
+ Oid *opfamily pg_node_attr(array_size(nkeycolumns));
+ /* OIDs of opclass declared input data types */
+ Oid *opcintype pg_node_attr(array_size(nkeycolumns));
+ /* OIDs of btree opfamilies, if orderable. NULL if partitioned index */
+ Oid *sortopfamily pg_node_attr(array_size(nkeycolumns));
+ /* is sort order descending? or NULL if partitioned index */
+ bool *reverse_sort pg_node_attr(array_size(nkeycolumns));
+ /* do NULLs come first in the sort order? or NULL if partitioned index */
+ bool *nulls_first pg_node_attr(array_size(nkeycolumns));
+ /* opclass-specific options for columns */
+ bytea **opclassoptions pg_node_attr(read_write_ignore);
+ /* which index cols can be returned in an index-only scan? */
+ bool *canreturn pg_node_attr(array_size(ncolumns));
+ /* OID of the access method (in pg_am) */
+ Oid relam;
+
+ /*
+ * expressions for non-simple index columns; redundant to print since we
+ * print indextlist
+ */
+ List *indexprs pg_node_attr(read_write_ignore);
+ /* predicate if a partial index, else NIL */
+ List *indpred;
+
+ /* targetlist representing index columns */
+ List *indextlist;
+
+ /*
+ * parent relation's baserestrictinfo list, less any conditions implied by
+ * the index's predicate (unless it's a target rel, see comments in
+ * check_index_predicates())
+ */
+ List *indrestrictinfo;
+
+ /* true if index predicate matches query */
+ bool predOK;
+ /* true if a unique index */
+ bool unique;
+ /* is uniqueness enforced immediately? */
+ bool immediate;
+ /* true if index doesn't really exist */
+ bool hypothetical;
+
+ /*
+ * Remaining fields are copied from the index AM's API struct
+ * (IndexAmRoutine). These fields are not set for partitioned indexes.
+ */
+ bool amcanorderbyop;
+ bool amoptionalkey;
+ bool amsearcharray;
+ bool amsearchnulls;
+ /* does AM have amgettuple interface? */
+ bool amhasgettuple;
+ /* does AM have amgetbitmap interface? */
+ bool amhasgetbitmap;
+ bool amcanparallel;
+ /* does AM have ammarkpos interface? */
+ bool amcanmarkpos;
+ /* AM's cost estimator */
+ /* Rather than include amapi.h here, we declare amcostestimate like this */
+ void (*amcostestimate) () pg_node_attr(read_write_ignore);
+};
+
+/*
+ * ForeignKeyOptInfo
+ * Per-foreign-key information for planning/optimization
+ *
+ * The per-FK-column arrays can be fixed-size because we allow at most
+ * INDEX_MAX_KEYS columns in a foreign key constraint. Each array has
+ * nkeys valid entries.
+ */
+typedef struct ForeignKeyOptInfo
+{
+ pg_node_attr(custom_read_write, no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /*
+ * Basic data about the foreign key (fetched from catalogs):
+ */
+
+ /* RT index of the referencing table */
+ Index con_relid;
+ /* RT index of the referenced table */
+ Index ref_relid;
+ /* number of columns in the foreign key */
+ int nkeys;
+ /* cols in referencing table */
+ AttrNumber conkey[INDEX_MAX_KEYS] pg_node_attr(array_size(nkeys));
+ /* cols in referenced table */
+ AttrNumber confkey[INDEX_MAX_KEYS] pg_node_attr(array_size(nkeys));
+ /* PK = FK operator OIDs */
+ Oid conpfeqop[INDEX_MAX_KEYS] pg_node_attr(array_size(nkeys));
+
+ /*
+ * Derived info about whether FK's equality conditions match the query:
+ */
+
+ /* # of FK cols matched by ECs */
+ int nmatched_ec;
+ /* # of these ECs that are ec_has_const */
+ int nconst_ec;
+ /* # of FK cols matched by non-EC rinfos */
+ int nmatched_rcols;
+ /* total # of non-EC rinfos matched to FK */
+ int nmatched_ri;
+ /* Pointer to eclass matching each column's condition, if there is one */
+ struct EquivalenceClass *eclass[INDEX_MAX_KEYS];
+ /* Pointer to eclass member for the referencing Var, if there is one */
+ struct EquivalenceMember *fk_eclass_member[INDEX_MAX_KEYS];
+ /* List of non-EC RestrictInfos matching each column's condition */
+ List *rinfos[INDEX_MAX_KEYS];
+} ForeignKeyOptInfo;
+
+/*
+ * StatisticExtInfo
+ * Information about extended statistics for planning/optimization
+ *
+ * Each pg_statistic_ext row is represented by one or more nodes of this
+ * type, or even zero if ANALYZE has not computed them.
+ */
+typedef struct StatisticExtInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* OID of the statistics row */
+ Oid statOid;
+
+ /* includes child relations */
+ bool inherit;
+
+ /* back-link to statistic's table; don't print, else infinite recursion */
+ RelOptInfo *rel pg_node_attr(read_write_ignore);
+
+ /* statistics kind of this entry */
+ char kind;
+
+ /* attnums of the columns covered */
+ Bitmapset *keys;
+
+ /* expressions */
+ List *exprs;
+} StatisticExtInfo;
+
+/*
+ * JoinDomains
+ *
+ * A "join domain" defines the scope of applicability of deductions made via
+ * the EquivalenceClass mechanism. Roughly speaking, a join domain is a set
+ * of base+OJ relations that are inner-joined together. More precisely, it is
+ * the set of relations at which equalities deduced from an EquivalenceClass
+ * can be enforced or should be expected to hold. The topmost JoinDomain
+ * covers the whole query (so its jd_relids should equal all_query_rels).
+ * An outer join creates a new JoinDomain that includes all base+OJ relids
+ * within its nullable side, but (by convention) not the OJ's own relid.
+ * A FULL join creates two new JoinDomains, one for each side.
+ *
+ * Notice that a rel that is below outer join(s) will thus appear to belong
+ * to multiple join domains. However, any of its Vars that appear in
+ * EquivalenceClasses belonging to higher join domains will have nullingrel
+ * bits preventing them from being evaluated at the rel's scan level, so that
+ * we will not be able to derive enforceable-at-the-rel-scan-level clauses
+ * from such ECs. We define the join domain relid sets this way so that
+ * domains can be said to be "higher" or "lower" when one domain relid set
+ * includes another.
+ *
+ * The JoinDomains for a query are computed in deconstruct_jointree.
+ * We do not copy JoinDomain structs once made, so they can be compared
+ * for equality by simple pointer equality.
+ */
+typedef struct JoinDomain
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ Relids jd_relids; /* all relids contained within the domain */
+} JoinDomain;
+
+/*
+ * EquivalenceClasses
+ *
+ * Whenever we identify a mergejoinable equality clause A = B that is
+ * not an outer-join clause, we create an EquivalenceClass containing
+ * the expressions A and B to record this knowledge. If we later find another
+ * equivalence B = C, we add C to the existing EquivalenceClass; this may
+ * require merging two existing EquivalenceClasses. At the end of the qual
+ * distribution process, we have sets of values that are known all transitively
+ * equal to each other, where "equal" is according to the rules of the btree
+ * operator family(s) shown in ec_opfamilies, as well as the collation shown
+ * by ec_collation. (We restrict an EC to contain only equalities whose
+ * operators belong to the same set of opfamilies. This could probably be
+ * relaxed, but for now it's not worth the trouble, since nearly all equality
+ * operators belong to only one btree opclass anyway. Similarly, we suppose
+ * that all or none of the input datatypes are collatable, so that a single
+ * collation value is sufficient.)
+ *
+ * Strictly speaking, deductions from an EquivalenceClass hold only within
+ * a "join domain", that is a set of relations that are innerjoined together
+ * (see JoinDomain above). For the most part we don't need to account for
+ * this explicitly, because equality clauses from different join domains
+ * will contain Vars that are not equal() because they have different
+ * nullingrel sets, and thus we will never falsely merge ECs from different
+ * join domains. But Var-free (pseudoconstant) expressions lack that safety
+ * feature. We handle that by marking "const" EC members with the JoinDomain
+ * of the clause they came from; two nominally-equal const members will be
+ * considered different if they came from different JoinDomains. This ensures
+ * no false EquivalenceClass merges will occur.
+ *
+ * We also use EquivalenceClasses as the base structure for PathKeys, letting
+ * us represent knowledge about different sort orderings being equivalent.
+ * Since every PathKey must reference an EquivalenceClass, we will end up
+ * with single-member EquivalenceClasses whenever a sort key expression has
+ * not been equivalenced to anything else. It is also possible that such an
+ * EquivalenceClass will contain a volatile expression ("ORDER BY random()"),
+ * which is a case that can't arise otherwise since clauses containing
+ * volatile functions are never considered mergejoinable. We mark such
+ * EquivalenceClasses specially to prevent them from being merged with
+ * ordinary EquivalenceClasses. Also, for volatile expressions we have
+ * to be careful to match the EquivalenceClass to the correct targetlist
+ * entry: consider SELECT random() AS a, random() AS b ... ORDER BY b,a.
+ * So we record the SortGroupRef of the originating sort clause.
+ *
+ * NB: if ec_merged isn't NULL, this class has been merged into another, and
+ * should be ignored in favor of using the pointed-to class.
+ *
+ * NB: EquivalenceClasses are never copied after creation. Therefore,
+ * copyObject() copies pointers to them as pointers, and equal() compares
+ * pointers to EquivalenceClasses via pointer equality. This is implemented
+ * by putting copy_as_scalar and equal_as_scalar attributes on fields that
+ * are pointers to EquivalenceClasses. The same goes for EquivalenceMembers.
+ */
+typedef struct EquivalenceClass
+{
+ pg_node_attr(custom_read_write, no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ List *ec_opfamilies; /* btree operator family OIDs */
+ Oid ec_collation; /* collation, if datatypes are collatable */
+ List *ec_members; /* list of EquivalenceMembers */
+ List *ec_sources; /* list of generating RestrictInfos */
+ List *ec_derives; /* list of derived RestrictInfos */
+ Relids ec_relids; /* all relids appearing in ec_members, except
+ * for child members (see below) */
+ bool ec_has_const; /* any pseudoconstants in ec_members? */
+ bool ec_has_volatile; /* the (sole) member is a volatile expr */
+ bool ec_broken; /* failed to generate needed clauses? */
+ Index ec_sortref; /* originating sortclause label, or 0 */
+ Index ec_min_security; /* minimum security_level in ec_sources */
+ Index ec_max_security; /* maximum security_level in ec_sources */
+ struct EquivalenceClass *ec_merged; /* set if merged into another EC */
+} EquivalenceClass;
+
+/*
+ * If an EC contains a constant, any PathKey depending on it must be
+ * redundant, since there's only one possible value of the key.
+ */
+#define EC_MUST_BE_REDUNDANT(eclass) \
+ ((eclass)->ec_has_const)
+
+/*
+ * EquivalenceMember - one member expression of an EquivalenceClass
+ *
+ * em_is_child signifies that this element was built by transposing a member
+ * for an appendrel parent relation to represent the corresponding expression
+ * for an appendrel child. These members are used for determining the
+ * pathkeys of scans on the child relation and for explicitly sorting the
+ * child when necessary to build a MergeAppend path for the whole appendrel
+ * tree. An em_is_child member has no impact on the properties of the EC as a
+ * whole; in particular the EC's ec_relids field does NOT include the child
+ * relation. An em_is_child member should never be marked em_is_const nor
+ * cause ec_has_const or ec_has_volatile to be set, either. Thus, em_is_child
+ * members are not really full-fledged members of the EC, but just reflections
+ * or doppelgangers of real members. Most operations on EquivalenceClasses
+ * should ignore em_is_child members, and those that don't should test
+ * em_relids to make sure they only consider relevant members.
+ *
+ * em_datatype is usually the same as exprType(em_expr), but can be
+ * different when dealing with a binary-compatible opfamily; in particular
+ * anyarray_ops would never work without this. Use em_datatype when
+ * looking up a specific btree operator to work with this expression.
+ */
+typedef struct EquivalenceMember
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ Expr *em_expr; /* the expression represented */
+ Relids em_relids; /* all relids appearing in em_expr */
+ bool em_is_const; /* expression is pseudoconstant? */
+ bool em_is_child; /* derived version for a child relation? */
+ Oid em_datatype; /* the "nominal type" used by the opfamily */
+ JoinDomain *em_jdomain; /* join domain containing the source clause */
+ /* if em_is_child is true, this links to corresponding EM for top parent */
+ struct EquivalenceMember *em_parent pg_node_attr(read_write_ignore);
+} EquivalenceMember;
+
+/*
+ * PathKeys
+ *
+ * The sort ordering of a path is represented by a list of PathKey nodes.
+ * An empty list implies no known ordering. Otherwise the first item
+ * represents the primary sort key, the second the first secondary sort key,
+ * etc. The value being sorted is represented by linking to an
+ * EquivalenceClass containing that value and including pk_opfamily among its
+ * ec_opfamilies. The EquivalenceClass tells which collation to use, too.
+ * This is a convenient method because it makes it trivial to detect
+ * equivalent and closely-related orderings. (See optimizer/README for more
+ * information.)
+ *
+ * Note: pk_strategy is either BTLessStrategyNumber (for ASC) or
+ * BTGreaterStrategyNumber (for DESC). We assume that all ordering-capable
+ * index types will use btree-compatible strategy numbers.
+ */
+typedef struct PathKey
+{
+ pg_node_attr(no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* the value that is ordered */
+ EquivalenceClass *pk_eclass pg_node_attr(copy_as_scalar, equal_as_scalar);
+ Oid pk_opfamily; /* btree opfamily defining the ordering */
+ int pk_strategy; /* sort direction (ASC or DESC) */
+ bool pk_nulls_first; /* do NULLs come before normal values? */
+} PathKey;
+
+/*
+ * VolatileFunctionStatus -- allows nodes to cache their
+ * contain_volatile_functions properties. VOLATILITY_UNKNOWN means not yet
+ * determined.
+ */
+typedef enum VolatileFunctionStatus
+{
+ VOLATILITY_UNKNOWN = 0,
+ VOLATILITY_VOLATILE,
+ VOLATILITY_NOVOLATILE
+} VolatileFunctionStatus;
+
+/*
+ * PathTarget
+ *
+ * This struct contains what we need to know during planning about the
+ * targetlist (output columns) that a Path will compute. Each RelOptInfo
+ * includes a default PathTarget, which its individual Paths may simply
+ * reference. However, in some cases a Path may compute outputs different
+ * from other Paths, and in that case we make a custom PathTarget for it.
+ * For example, an indexscan might return index expressions that would
+ * otherwise need to be explicitly calculated. (Note also that "upper"
+ * relations generally don't have useful default PathTargets.)
+ *
+ * exprs contains bare expressions; they do not have TargetEntry nodes on top,
+ * though those will appear in finished Plans.
+ *
+ * sortgrouprefs[] is an array of the same length as exprs, containing the
+ * corresponding sort/group refnos, or zeroes for expressions not referenced
+ * by sort/group clauses. If sortgrouprefs is NULL (which it generally is in
+ * RelOptInfo.reltarget targets; only upper-level Paths contain this info),
+ * we have not identified sort/group columns in this tlist. This allows us to
+ * deal with sort/group refnos when needed with less expense than including
+ * TargetEntry nodes in the exprs list.
+ */
+typedef struct PathTarget
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* list of expressions to be computed */
+ List *exprs;
+
+ /* corresponding sort/group refnos, or 0 */
+ Index *sortgrouprefs pg_node_attr(array_size(exprs));
+
+ /* cost of evaluating the expressions */
+ QualCost cost;
+
+ /* estimated avg width of result tuples */
+ int width;
+
+ /* indicates if exprs contain any volatile functions */
+ VolatileFunctionStatus has_volatile_expr;
+} PathTarget;
+
+/* Convenience macro to get a sort/group refno from a PathTarget */
+#define get_pathtarget_sortgroupref(target, colno) \
+ ((target)->sortgrouprefs ? (target)->sortgrouprefs[colno] : (Index) 0)
+
+
+/*
+ * ParamPathInfo
+ *
+ * All parameterized paths for a given relation with given required outer rels
+ * link to a single ParamPathInfo, which stores common information such as
+ * the estimated rowcount for this parameterization. We do this partly to
+ * avoid recalculations, but mostly to ensure that the estimated rowcount
+ * is in fact the same for every such path.
+ *
+ * Note: ppi_clauses is only used in ParamPathInfos for base relation paths;
+ * in join cases it's NIL because the set of relevant clauses varies depending
+ * on how the join is formed. The relevant clauses will appear in each
+ * parameterized join path's joinrestrictinfo list, instead. ParamPathInfos
+ * for append relations don't bother with this, either.
+ *
+ * ppi_serials is the set of rinfo_serial numbers for quals that are enforced
+ * by this path. As with ppi_clauses, it's only maintained for baserels.
+ * (We could construct it on-the-fly from ppi_clauses, but it seems better
+ * to materialize a copy.)
+ */
+typedef struct ParamPathInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ Relids ppi_req_outer; /* rels supplying parameters used by path */
+ Cardinality ppi_rows; /* estimated number of result tuples */
+ List *ppi_clauses; /* join clauses available from outer rels */
+ Bitmapset *ppi_serials; /* set of rinfo_serial for enforced quals */
+} ParamPathInfo;
+
+
+/*
+ * Type "Path" is used as-is for sequential-scan paths, as well as some other
+ * simple plan types that we don't need any extra information in the path for.
+ * For other path types it is the first component of a larger struct.
+ *
+ * "pathtype" is the NodeTag of the Plan node we could build from this Path.
+ * It is partially redundant with the Path's NodeTag, but allows us to use
+ * the same Path type for multiple Plan types when there is no need to
+ * distinguish the Plan type during path processing.
+ *
+ * "parent" identifies the relation this Path scans, and "pathtarget"
+ * describes the precise set of output columns the Path would compute.
+ * In simple cases all Paths for a given rel share the same targetlist,
+ * which we represent by having path->pathtarget equal to parent->reltarget.
+ *
+ * "param_info", if not NULL, links to a ParamPathInfo that identifies outer
+ * relation(s) that provide parameter values to each scan of this path.
+ * That means this path can only be joined to those rels by means of nestloop
+ * joins with this path on the inside. Also note that a parameterized path
+ * is responsible for testing all "movable" joinclauses involving this rel
+ * and the specified outer rel(s).
+ *
+ * "rows" is the same as parent->rows in simple paths, but in parameterized
+ * paths and UniquePaths it can be less than parent->rows, reflecting the
+ * fact that we've filtered by extra join conditions or removed duplicates.
+ *
+ * "pathkeys" is a List of PathKey nodes (see above), describing the sort
+ * ordering of the path's output rows.
+ *
+ * We do not support copying Path trees, mainly because the circular linkages
+ * between RelOptInfo and Path nodes can't be handled easily in a simple
+ * depth-first traversal. We also don't have read support at the moment.
+ */
+typedef struct Path
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* tag identifying scan/join method */
+ NodeTag pathtype;
+
+ /*
+ * the relation this path can build
+ *
+ * We do NOT print the parent, else we'd be in infinite recursion. We can
+ * print the parent's relids for identification purposes, though.
+ */
+ RelOptInfo *parent pg_node_attr(write_only_relids);
+
+ /*
+ * list of Vars/Exprs, cost, width
+ *
+ * We print the pathtarget only if it's not the default one for the rel.
+ */
+ PathTarget *pathtarget pg_node_attr(write_only_nondefault_pathtarget);
+
+ /*
+ * parameterization info, or NULL if none
+ *
+ * We do not print the whole of param_info, since it's printed via
+ * RelOptInfo; it's sufficient and less cluttering to print just the
+ * required outer relids.
+ */
+ ParamPathInfo *param_info pg_node_attr(write_only_req_outer);
+
+ /* engage parallel-aware logic? */
+ bool parallel_aware;
+ /* OK to use as part of parallel plan? */
+ bool parallel_safe;
+ /* desired # of workers; 0 = not parallel */
+ int parallel_workers;
+
+ /* estimated size/costs for path (see costsize.c for more info) */
+ Cardinality rows; /* estimated number of result tuples */
+ Cost startup_cost; /* cost expended before fetching any tuples */
+ Cost total_cost; /* total cost (assuming all tuples fetched) */
+
+ /* sort ordering of path's output; a List of PathKey nodes; see above */
+ List *pathkeys;
+} Path;
+
+/* Macro for extracting a path's parameterization relids; beware double eval */
+#define PATH_REQ_OUTER(path) \
+ ((path)->param_info ? (path)->param_info->ppi_req_outer : (Relids) NULL)
+
+/*----------
+ * IndexPath represents an index scan over a single index.
+ *
+ * This struct is used for both regular indexscans and index-only scans;
+ * path.pathtype is T_IndexScan or T_IndexOnlyScan to show which is meant.
+ *
+ * 'indexinfo' is the index to be scanned.
+ *
+ * 'indexclauses' is a list of IndexClause nodes, each representing one
+ * index-checkable restriction, with implicit AND semantics across the list.
+ * An empty list implies a full index scan.
+ *
+ * 'indexorderbys', if not NIL, is a list of ORDER BY expressions that have
+ * been found to be usable as ordering operators for an amcanorderbyop index.
+ * The list must match the path's pathkeys, ie, one expression per pathkey
+ * in the same order. These are not RestrictInfos, just bare expressions,
+ * since they generally won't yield booleans. It's guaranteed that each
+ * expression has the index key on the left side of the operator.
+ *
+ * 'indexorderbycols' is an integer list of index column numbers (zero-based)
+ * of the same length as 'indexorderbys', showing which index column each
+ * ORDER BY expression is meant to be used with. (There is no restriction
+ * on which index column each ORDER BY can be used with.)
+ *
+ * 'indexscandir' is one of:
+ * ForwardScanDirection: forward scan of an index
+ * BackwardScanDirection: backward scan of an ordered index
+ * Unordered indexes will always have an indexscandir of ForwardScanDirection.
+ *
+ * 'indextotalcost' and 'indexselectivity' are saved in the IndexPath so that
+ * we need not recompute them when considering using the same index in a
+ * bitmap index/heap scan (see BitmapHeapPath). The costs of the IndexPath
+ * itself represent the costs of an IndexScan or IndexOnlyScan plan type.
+ *----------
+ */
+typedef struct IndexPath
+{
+ Path path;
+ IndexOptInfo *indexinfo;
+ List *indexclauses;
+ List *indexorderbys;
+ List *indexorderbycols;
+ ScanDirection indexscandir;
+ Cost indextotalcost;
+ Selectivity indexselectivity;
+} IndexPath;
+
+/*
+ * Each IndexClause references a RestrictInfo node from the query's WHERE
+ * or JOIN conditions, and shows how that restriction can be applied to
+ * the particular index. We support both indexclauses that are directly
+ * usable by the index machinery, which are typically of the form
+ * "indexcol OP pseudoconstant", and those from which an indexable qual
+ * can be derived. The simplest such transformation is that a clause
+ * of the form "pseudoconstant OP indexcol" can be commuted to produce an
+ * indexable qual (the index machinery expects the indexcol to be on the
+ * left always). Another example is that we might be able to extract an
+ * indexable range condition from a LIKE condition, as in "x LIKE 'foo%bar'"
+ * giving rise to "x >= 'foo' AND x < 'fop'". Derivation of such lossy
+ * conditions is done by a planner support function attached to the
+ * indexclause's top-level function or operator.
+ *
+ * indexquals is a list of RestrictInfos for the directly-usable index
+ * conditions associated with this IndexClause. In the simplest case
+ * it's a one-element list whose member is iclause->rinfo. Otherwise,
+ * it contains one or more directly-usable indexqual conditions extracted
+ * from the given clause. The 'lossy' flag indicates whether the
+ * indexquals are semantically equivalent to the original clause, or
+ * represent a weaker condition.
+ *
+ * Normally, indexcol is the index of the single index column the clause
+ * works on, and indexcols is NIL. But if the clause is a RowCompareExpr,
+ * indexcol is the index of the leading column, and indexcols is a list of
+ * all the affected columns. (Note that indexcols matches up with the
+ * columns of the actual indexable RowCompareExpr in indexquals, which
+ * might be different from the original in rinfo.)
+ *
+ * An IndexPath's IndexClause list is required to be ordered by index
+ * column, i.e. the indexcol values must form a nondecreasing sequence.
+ * (The order of multiple clauses for the same index column is unspecified.)
+ */
+typedef struct IndexClause
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+ struct RestrictInfo *rinfo; /* original restriction or join clause */
+ List *indexquals; /* indexqual(s) derived from it */
+ bool lossy; /* are indexquals a lossy version of clause? */
+ AttrNumber indexcol; /* index column the clause uses (zero-based) */
+ List *indexcols; /* multiple index columns, if RowCompare */
+} IndexClause;
+
+/*
+ * BitmapHeapPath represents one or more indexscans that generate TID bitmaps
+ * instead of directly accessing the heap, followed by AND/OR combinations
+ * to produce a single bitmap, followed by a heap scan that uses the bitmap.
+ * Note that the output is always considered unordered, since it will come
+ * out in physical heap order no matter what the underlying indexes did.
+ *
+ * The individual indexscans are represented by IndexPath nodes, and any
+ * logic on top of them is represented by a tree of BitmapAndPath and
+ * BitmapOrPath nodes. Notice that we can use the same IndexPath node both
+ * to represent a regular (or index-only) index scan plan, and as the child
+ * of a BitmapHeapPath that represents scanning the same index using a
+ * BitmapIndexScan. The startup_cost and total_cost figures of an IndexPath
+ * always represent the costs to use it as a regular (or index-only)
+ * IndexScan. The costs of a BitmapIndexScan can be computed using the
+ * IndexPath's indextotalcost and indexselectivity.
+ */
+typedef struct BitmapHeapPath
+{
+ Path path;
+ Path *bitmapqual; /* IndexPath, BitmapAndPath, BitmapOrPath */
+} BitmapHeapPath;
+
+/*
+ * BitmapAndPath represents a BitmapAnd plan node; it can only appear as
+ * part of the substructure of a BitmapHeapPath. The Path structure is
+ * a bit more heavyweight than we really need for this, but for simplicity
+ * we make it a derivative of Path anyway.
+ */
+typedef struct BitmapAndPath
+{
+ Path path;
+ List *bitmapquals; /* IndexPaths and BitmapOrPaths */
+ Selectivity bitmapselectivity;
+} BitmapAndPath;
+
+/*
+ * BitmapOrPath represents a BitmapOr plan node; it can only appear as
+ * part of the substructure of a BitmapHeapPath. The Path structure is
+ * a bit more heavyweight than we really need for this, but for simplicity
+ * we make it a derivative of Path anyway.
+ */
+typedef struct BitmapOrPath
+{
+ Path path;
+ List *bitmapquals; /* IndexPaths and BitmapAndPaths */
+ Selectivity bitmapselectivity;
+} BitmapOrPath;
+
+/*
+ * TidPath represents a scan by TID
+ *
+ * tidquals is an implicitly OR'ed list of qual expressions of the form
+ * "CTID = pseudoconstant", or "CTID = ANY(pseudoconstant_array)",
+ * or a CurrentOfExpr for the relation.
+ */
+typedef struct TidPath
+{
+ Path path;
+ List *tidquals; /* qual(s) involving CTID = something */
+} TidPath;
+
+/*
+ * TidRangePath represents a scan by a contiguous range of TIDs
+ *
+ * tidrangequals is an implicitly AND'ed list of qual expressions of the form
+ * "CTID relop pseudoconstant", where relop is one of >,>=,<,<=.
+ */
+typedef struct TidRangePath
+{
+ Path path;
+ List *tidrangequals;
+} TidRangePath;
+
+/*
+ * SubqueryScanPath represents a scan of an unflattened subquery-in-FROM
+ *
+ * Note that the subpath comes from a different planning domain; for example
+ * RTE indexes within it mean something different from those known to the
+ * SubqueryScanPath. path.parent->subroot is the planning context needed to
+ * interpret the subpath.
+ */
+typedef struct SubqueryScanPath
+{
+ Path path;
+ Path *subpath; /* path representing subquery execution */
+} SubqueryScanPath;
+
+/*
+ * ForeignPath represents a potential scan of a foreign table, foreign join
+ * or foreign upper-relation.
+ *
+ * fdw_private stores FDW private data about the scan. While fdw_private is
+ * not actually touched by the core code during normal operations, it's
+ * generally a good idea to use a representation that can be dumped by
+ * nodeToString(), so that you can examine the structure during debugging
+ * with tools like pprint().
+ */
+typedef struct ForeignPath
+{
+ Path path;
+ Path *fdw_outerpath;
+ List *fdw_private;
+} ForeignPath;
+
+/*
+ * CustomPath represents a table scan or a table join done by some out-of-core
+ * extension.
+ *
+ * We provide a set of hooks here - which the provider must take care to set
+ * up correctly - to allow extensions to supply their own methods of scanning
+ * a relation or joing relations. For example, a provider might provide GPU
+ * acceleration, a cache-based scan, or some other kind of logic we haven't
+ * dreamed up yet.
+ *
+ * CustomPaths can be injected into the planning process for a base or join
+ * relation by set_rel_pathlist_hook or set_join_pathlist_hook functions,
+ * respectively.
+ *
+ * Core code must avoid assuming that the CustomPath is only as large as
+ * the structure declared here; providers are allowed to make it the first
+ * element in a larger structure. (Since the planner never copies Paths,
+ * this doesn't add any complication.) However, for consistency with the
+ * FDW case, we provide a "custom_private" field in CustomPath; providers
+ * may prefer to use that rather than define another struct type.
+ */
+
+struct CustomPathMethods;
+
+typedef struct CustomPath
+{
+ Path path;
+ uint32 flags; /* mask of CUSTOMPATH_* flags, see
+ * nodes/extensible.h */
+ List *custom_paths; /* list of child Path nodes, if any */
+ List *custom_private;
+ const struct CustomPathMethods *methods;
+} CustomPath;
+
+/*
+ * AppendPath represents an Append plan, ie, successive execution of
+ * several member plans.
+ *
+ * For partial Append, 'subpaths' contains non-partial subpaths followed by
+ * partial subpaths.
+ *
+ * Note: it is possible for "subpaths" to contain only one, or even no,
+ * elements. These cases are optimized during create_append_plan.
+ * In particular, an AppendPath with no subpaths is a "dummy" path that
+ * is created to represent the case that a relation is provably empty.
+ * (This is a convenient representation because it means that when we build
+ * an appendrel and find that all its children have been excluded, no extra
+ * action is needed to recognize the relation as dummy.)
+ */
+typedef struct AppendPath
+{
+ Path path;
+ List *subpaths; /* list of component Paths */
+ /* Index of first partial path in subpaths; list_length(subpaths) if none */
+ int first_partial_path;
+ Cardinality limit_tuples; /* hard limit on output tuples, or -1 */
+} AppendPath;
+
+#define IS_DUMMY_APPEND(p) \
+ (IsA((p), AppendPath) && ((AppendPath *) (p))->subpaths == NIL)
+
+/*
+ * A relation that's been proven empty will have one path that is dummy
+ * (but might have projection paths on top). For historical reasons,
+ * this is provided as a macro that wraps is_dummy_rel().
+ */
+#define IS_DUMMY_REL(r) is_dummy_rel(r)
+extern bool is_dummy_rel(RelOptInfo *rel);
+
+/*
+ * MergeAppendPath represents a MergeAppend plan, ie, the merging of sorted
+ * results from several member plans to produce similarly-sorted output.
+ */
+typedef struct MergeAppendPath
+{
+ Path path;
+ List *subpaths; /* list of component Paths */
+ Cardinality limit_tuples; /* hard limit on output tuples, or -1 */
+} MergeAppendPath;
+
+/*
+ * GroupResultPath represents use of a Result plan node to compute the
+ * output of a degenerate GROUP BY case, wherein we know we should produce
+ * exactly one row, which might then be filtered by a HAVING qual.
+ *
+ * Note that quals is a list of bare clauses, not RestrictInfos.
+ */
+typedef struct GroupResultPath
+{
+ Path path;
+ List *quals;
+} GroupResultPath;
+
+/*
+ * MaterialPath represents use of a Material plan node, i.e., caching of
+ * the output of its subpath. This is used when the subpath is expensive
+ * and needs to be scanned repeatedly, or when we need mark/restore ability
+ * and the subpath doesn't have it.
+ */
+typedef struct MaterialPath
+{
+ Path path;
+ Path *subpath;
+} MaterialPath;
+
+/*
+ * MemoizePath represents a Memoize plan node, i.e., a cache that caches
+ * tuples from parameterized paths to save the underlying node from having to
+ * be rescanned for parameter values which are already cached.
+ */
+typedef struct MemoizePath
+{
+ Path path;
+ Path *subpath; /* outerpath to cache tuples from */
+ List *hash_operators; /* OIDs of hash equality ops for cache keys */
+ List *param_exprs; /* expressions that are cache keys */
+ bool singlerow; /* true if the cache entry is to be marked as
+ * complete after caching the first record. */
+ bool binary_mode; /* true when cache key should be compared bit
+ * by bit, false when using hash equality ops */
+ Cardinality calls; /* expected number of rescans */
+ uint32 est_entries; /* The maximum number of entries that the
+ * planner expects will fit in the cache, or 0
+ * if unknown */
+} MemoizePath;
+
+/*
+ * UniquePath represents elimination of distinct rows from the output of
+ * its subpath.
+ *
+ * This can represent significantly different plans: either hash-based or
+ * sort-based implementation, or a no-op if the input path can be proven
+ * distinct already. The decision is sufficiently localized that it's not
+ * worth having separate Path node types. (Note: in the no-op case, we could
+ * eliminate the UniquePath node entirely and just return the subpath; but
+ * it's convenient to have a UniquePath in the path tree to signal upper-level
+ * routines that the input is known distinct.)
+ */
+typedef enum UniquePathMethod
+{
+ UNIQUE_PATH_NOOP, /* input is known unique already */
+ UNIQUE_PATH_HASH, /* use hashing */
+ UNIQUE_PATH_SORT /* use sorting */
+} UniquePathMethod;
+
+typedef struct UniquePath
+{
+ Path path;
+ Path *subpath;
+ UniquePathMethod umethod;
+ List *in_operators; /* equality operators of the IN clause */
+ List *uniq_exprs; /* expressions to be made unique */
+} UniquePath;
+
+/*
+ * GatherPath runs several copies of a plan in parallel and collects the
+ * results. The parallel leader may also execute the plan, unless the
+ * single_copy flag is set.
+ */
+typedef struct GatherPath
+{
+ Path path;
+ Path *subpath; /* path for each worker */
+ bool single_copy; /* don't execute path more than once */
+ int num_workers; /* number of workers sought to help */
+} GatherPath;
+
+/*
+ * GatherMergePath runs several copies of a plan in parallel and collects
+ * the results, preserving their common sort order.
+ */
+typedef struct GatherMergePath
+{
+ Path path;
+ Path *subpath; /* path for each worker */
+ int num_workers; /* number of workers sought to help */
+} GatherMergePath;
+
+
+/*
+ * All join-type paths share these fields.
+ */
+
+typedef struct JoinPath
+{
+ pg_node_attr(abstract)
+
+ Path path;
+
+ JoinType jointype;
+
+ bool inner_unique; /* each outer tuple provably matches no more
+ * than one inner tuple */
+
+ Path *outerjoinpath; /* path for the outer side of the join */
+ Path *innerjoinpath; /* path for the inner side of the join */
+
+ List *joinrestrictinfo; /* RestrictInfos to apply to join */
+
+ /*
+ * See the notes for RelOptInfo and ParamPathInfo to understand why
+ * joinrestrictinfo is needed in JoinPath, and can't be merged into the
+ * parent RelOptInfo.
+ */
+} JoinPath;
+
+/*
+ * A nested-loop path needs no special fields.
+ */
+
+typedef struct NestPath
+{
+ JoinPath jpath;
+} NestPath;
+
+/*
+ * A mergejoin path has these fields.
+ *
+ * Unlike other path types, a MergePath node doesn't represent just a single
+ * run-time plan node: it can represent up to four. Aside from the MergeJoin
+ * node itself, there can be a Sort node for the outer input, a Sort node
+ * for the inner input, and/or a Material node for the inner input. We could
+ * represent these nodes by separate path nodes, but considering how many
+ * different merge paths are investigated during a complex join problem,
+ * it seems better to avoid unnecessary palloc overhead.
+ *
+ * path_mergeclauses lists the clauses (in the form of RestrictInfos)
+ * that will be used in the merge.
+ *
+ * Note that the mergeclauses are a subset of the parent relation's
+ * restriction-clause list. Any join clauses that are not mergejoinable
+ * appear only in the parent's restrict list, and must be checked by a
+ * qpqual at execution time.
+ *
+ * outersortkeys (resp. innersortkeys) is NIL if the outer path
+ * (resp. inner path) is already ordered appropriately for the
+ * mergejoin. If it is not NIL then it is a PathKeys list describing
+ * the ordering that must be created by an explicit Sort node.
+ *
+ * skip_mark_restore is true if the executor need not do mark/restore calls.
+ * Mark/restore overhead is usually required, but can be skipped if we know
+ * that the executor need find only one match per outer tuple, and that the
+ * mergeclauses are sufficient to identify a match. In such cases the
+ * executor can immediately advance the outer relation after processing a
+ * match, and therefore it need never back up the inner relation.
+ *
+ * materialize_inner is true if a Material node should be placed atop the
+ * inner input. This may appear with or without an inner Sort step.
+ */
+
+typedef struct MergePath
+{
+ JoinPath jpath;
+ List *path_mergeclauses; /* join clauses to be used for merge */
+ List *outersortkeys; /* keys for explicit sort, if any */
+ List *innersortkeys; /* keys for explicit sort, if any */
+ bool skip_mark_restore; /* can executor skip mark/restore? */
+ bool materialize_inner; /* add Materialize to inner? */
+} MergePath;
+
+/*
+ * A hashjoin path has these fields.
+ *
+ * The remarks above for mergeclauses apply for hashclauses as well.
+ *
+ * Hashjoin does not care what order its inputs appear in, so we have
+ * no need for sortkeys.
+ */
+
+typedef struct HashPath
+{
+ JoinPath jpath;
+ List *path_hashclauses; /* join clauses used for hashing */
+ int num_batches; /* number of batches expected */
+ Cardinality inner_rows_total; /* total inner rows expected */
+} HashPath;
+
+/*
+ * ProjectionPath represents a projection (that is, targetlist computation)
+ *
+ * Nominally, this path node represents using a Result plan node to do a
+ * projection step. However, if the input plan node supports projection,
+ * we can just modify its output targetlist to do the required calculations
+ * directly, and not need a Result. In some places in the planner we can just
+ * jam the desired PathTarget into the input path node (and adjust its cost
+ * accordingly), so we don't need a ProjectionPath. But in other places
+ * it's necessary to not modify the input path node, so we need a separate
+ * ProjectionPath node, which is marked dummy to indicate that we intend to
+ * assign the work to the input plan node. The estimated cost for the
+ * ProjectionPath node will account for whether a Result will be used or not.
+ */
+typedef struct ProjectionPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ bool dummypp; /* true if no separate Result is needed */
+} ProjectionPath;
+
+/*
+ * ProjectSetPath represents evaluation of a targetlist that includes
+ * set-returning function(s), which will need to be implemented by a
+ * ProjectSet plan node.
+ */
+typedef struct ProjectSetPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+} ProjectSetPath;
+
+/*
+ * SortPath represents an explicit sort step
+ *
+ * The sort keys are, by definition, the same as path.pathkeys.
+ *
+ * Note: the Sort plan node cannot project, so path.pathtarget must be the
+ * same as the input's pathtarget.
+ */
+typedef struct SortPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+} SortPath;
+
+/*
+ * IncrementalSortPath represents an incremental sort step
+ *
+ * This is like a regular sort, except some leading key columns are assumed
+ * to be ordered already.
+ */
+typedef struct IncrementalSortPath
+{
+ SortPath spath;
+ int nPresortedCols; /* number of presorted columns */
+} IncrementalSortPath;
+
+/*
+ * GroupPath represents grouping (of presorted input)
+ *
+ * groupClause represents the columns to be grouped on; the input path
+ * must be at least that well sorted.
+ *
+ * We can also apply a qual to the grouped rows (equivalent of HAVING)
+ */
+typedef struct GroupPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ List *groupClause; /* a list of SortGroupClause's */
+ List *qual; /* quals (HAVING quals), if any */
+} GroupPath;
+
+/*
+ * UpperUniquePath represents adjacent-duplicate removal (in presorted input)
+ *
+ * The columns to be compared are the first numkeys columns of the path's
+ * pathkeys. The input is presumed already sorted that way.
+ */
+typedef struct UpperUniquePath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ int numkeys; /* number of pathkey columns to compare */
+} UpperUniquePath;
+
+/*
+ * AggPath represents generic computation of aggregate functions
+ *
+ * This may involve plain grouping (but not grouping sets), using either
+ * sorted or hashed grouping; for the AGG_SORTED case, the input must be
+ * appropriately presorted.
+ */
+typedef struct AggPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ AggStrategy aggstrategy; /* basic strategy, see nodes.h */
+ AggSplit aggsplit; /* agg-splitting mode, see nodes.h */
+ Cardinality numGroups; /* estimated number of groups in input */
+ uint64 transitionSpace; /* for pass-by-ref transition data */
+ List *groupClause; /* a list of SortGroupClause's */
+ List *qual; /* quals (HAVING quals), if any */
+} AggPath;
+
+/*
+ * Various annotations used for grouping sets in the planner.
+ */
+
+typedef struct GroupingSetData
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+ List *set; /* grouping set as list of sortgrouprefs */
+ Cardinality numGroups; /* est. number of result groups */
+} GroupingSetData;
+
+typedef struct RollupData
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+ List *groupClause; /* applicable subset of parse->groupClause */
+ List *gsets; /* lists of integer indexes into groupClause */
+ List *gsets_data; /* list of GroupingSetData */
+ Cardinality numGroups; /* est. number of result groups */
+ bool hashable; /* can be hashed */
+ bool is_hashed; /* to be implemented as a hashagg */
+} RollupData;
+
+/*
+ * GroupingSetsPath represents a GROUPING SETS aggregation
+ */
+
+typedef struct GroupingSetsPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ AggStrategy aggstrategy; /* basic strategy */
+ List *rollups; /* list of RollupData */
+ List *qual; /* quals (HAVING quals), if any */
+ uint64 transitionSpace; /* for pass-by-ref transition data */
+} GroupingSetsPath;
+
+/*
+ * MinMaxAggPath represents computation of MIN/MAX aggregates from indexes
+ */
+typedef struct MinMaxAggPath
+{
+ Path path;
+ List *mmaggregates; /* list of MinMaxAggInfo */
+ List *quals; /* HAVING quals, if any */
+} MinMaxAggPath;
+
+/*
+ * WindowAggPath represents generic computation of window functions
+ */
+typedef struct WindowAggPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ WindowClause *winclause; /* WindowClause we'll be using */
+ List *qual; /* lower-level WindowAgg runconditions */
+ bool topwindow; /* false for all apart from the WindowAgg
+ * that's closest to the root of the plan */
+} WindowAggPath;
+
+/*
+ * SetOpPath represents a set-operation, that is INTERSECT or EXCEPT
+ */
+typedef struct SetOpPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ SetOpCmd cmd; /* what to do, see nodes.h */
+ SetOpStrategy strategy; /* how to do it, see nodes.h */
+ List *distinctList; /* SortGroupClauses identifying target cols */
+ AttrNumber flagColIdx; /* where is the flag column, if any */
+ int firstFlag; /* flag value for first input relation */
+ Cardinality numGroups; /* estimated number of groups in input */
+} SetOpPath;
+
+/*
+ * RecursiveUnionPath represents a recursive UNION node
+ */
+typedef struct RecursiveUnionPath
+{
+ Path path;
+ Path *leftpath; /* paths representing input sources */
+ Path *rightpath;
+ List *distinctList; /* SortGroupClauses identifying target cols */
+ int wtParam; /* ID of Param representing work table */
+ Cardinality numGroups; /* estimated number of groups in input */
+} RecursiveUnionPath;
+
+/*
+ * LockRowsPath represents acquiring row locks for SELECT FOR UPDATE/SHARE
+ */
+typedef struct LockRowsPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ List *rowMarks; /* a list of PlanRowMark's */
+ int epqParam; /* ID of Param for EvalPlanQual re-eval */
+} LockRowsPath;
+
+/*
+ * ModifyTablePath represents performing INSERT/UPDATE/DELETE/MERGE
+ *
+ * We represent most things that will be in the ModifyTable plan node
+ * literally, except we have a child Path not Plan. But analysis of the
+ * OnConflictExpr is deferred to createplan.c, as is collection of FDW data.
+ */
+typedef struct ModifyTablePath
+{
+ Path path;
+ Path *subpath; /* Path producing source data */
+ CmdType operation; /* INSERT, UPDATE, DELETE, or MERGE */
+ bool canSetTag; /* do we set the command tag/es_processed? */
+ Index nominalRelation; /* Parent RT index for use of EXPLAIN */
+ Index rootRelation; /* Root RT index, if partitioned/inherited */
+ bool partColsUpdated; /* some part key in hierarchy updated? */
+ List *resultRelations; /* integer list of RT indexes */
+ List *updateColnosLists; /* per-target-table update_colnos lists */
+ List *withCheckOptionLists; /* per-target-table WCO lists */
+ List *returningLists; /* per-target-table RETURNING tlists */
+ List *rowMarks; /* PlanRowMarks (non-locking only) */
+ OnConflictExpr *onconflict; /* ON CONFLICT clause, or NULL */
+ int epqParam; /* ID of Param for EvalPlanQual re-eval */
+ List *mergeActionLists; /* per-target-table lists of actions for
+ * MERGE */
+} ModifyTablePath;
+
+/*
+ * LimitPath represents applying LIMIT/OFFSET restrictions
+ */
+typedef struct LimitPath
+{
+ Path path;
+ Path *subpath; /* path representing input source */
+ Node *limitOffset; /* OFFSET parameter, or NULL if none */
+ Node *limitCount; /* COUNT parameter, or NULL if none */
+ LimitOption limitOption; /* FETCH FIRST with ties or exact number */
+} LimitPath;
+
+
+/*
+ * Restriction clause info.
+ *
+ * We create one of these for each AND sub-clause of a restriction condition
+ * (WHERE or JOIN/ON clause). Since the restriction clauses are logically
+ * ANDed, we can use any one of them or any subset of them to filter out
+ * tuples, without having to evaluate the rest. The RestrictInfo node itself
+ * stores data used by the optimizer while choosing the best query plan.
+ *
+ * If a restriction clause references a single base relation, it will appear
+ * in the baserestrictinfo list of the RelOptInfo for that base rel.
+ *
+ * If a restriction clause references more than one base+OJ relation, it will
+ * appear in the joininfo list of every RelOptInfo that describes a strict
+ * subset of the relations mentioned in the clause. The joininfo lists are
+ * used to drive join tree building by selecting plausible join candidates.
+ * The clause cannot actually be applied until we have built a join rel
+ * containing all the relations it references, however.
+ *
+ * When we construct a join rel that includes all the relations referenced
+ * in a multi-relation restriction clause, we place that clause into the
+ * joinrestrictinfo lists of paths for the join rel, if neither left nor
+ * right sub-path includes all relations referenced in the clause. The clause
+ * will be applied at that join level, and will not propagate any further up
+ * the join tree. (Note: the "predicate migration" code was once intended to
+ * push restriction clauses up and down the plan tree based on evaluation
+ * costs, but it's dead code and is unlikely to be resurrected in the
+ * foreseeable future.)
+ *
+ * Note that in the presence of more than two rels, a multi-rel restriction
+ * might reach different heights in the join tree depending on the join
+ * sequence we use. So, these clauses cannot be associated directly with
+ * the join RelOptInfo, but must be kept track of on a per-join-path basis.
+ *
+ * RestrictInfos that represent equivalence conditions (i.e., mergejoinable
+ * equalities that are not outerjoin-delayed) are handled a bit differently.
+ * Initially we attach them to the EquivalenceClasses that are derived from
+ * them. When we construct a scan or join path, we look through all the
+ * EquivalenceClasses and generate derived RestrictInfos representing the
+ * minimal set of conditions that need to be checked for this particular scan
+ * or join to enforce that all members of each EquivalenceClass are in fact
+ * equal in all rows emitted by the scan or join.
+ *
+ * The clause_relids field lists the base plus outer-join RT indexes that
+ * actually appear in the clause. required_relids lists the minimum set of
+ * relids needed to evaluate the clause; while this is often equal to
+ * clause_relids, it can be more. We will add relids to required_relids when
+ * we need to force an outer join ON clause to be evaluated exactly at the
+ * level of the outer join, which is true except when it is a "degenerate"
+ * condition that references only Vars from the nullable side of the join.
+ *
+ * RestrictInfo nodes contain a flag to indicate whether a qual has been
+ * pushed down to a lower level than its original syntactic placement in the
+ * join tree would suggest. If an outer join prevents us from pushing a qual
+ * down to its "natural" semantic level (the level associated with just the
+ * base rels used in the qual) then we mark the qual with a "required_relids"
+ * value including more than just the base rels it actually uses. By
+ * pretending that the qual references all the rels required to form the outer
+ * join, we prevent it from being evaluated below the outer join's joinrel.
+ * When we do form the outer join's joinrel, we still need to distinguish
+ * those quals that are actually in that join's JOIN/ON condition from those
+ * that appeared elsewhere in the tree and were pushed down to the join rel
+ * because they used no other rels. That's what the is_pushed_down flag is
+ * for; it tells us that a qual is not an OUTER JOIN qual for the set of base
+ * rels listed in required_relids. A clause that originally came from WHERE
+ * or an INNER JOIN condition will *always* have its is_pushed_down flag set.
+ * It's possible for an OUTER JOIN clause to be marked is_pushed_down too,
+ * if we decide that it can be pushed down into the nullable side of the join.
+ * In that case it acts as a plain filter qual for wherever it gets evaluated.
+ * (In short, is_pushed_down is only false for non-degenerate outer join
+ * conditions. Possibly we should rename it to reflect that meaning? But
+ * see also the comments for RINFO_IS_PUSHED_DOWN, below.)
+ *
+ * There is also an incompatible_relids field, which is a set of outer-join
+ * relids above which we cannot evaluate the clause (because they might null
+ * Vars it uses that should not be nulled yet). In principle this could be
+ * filled in any RestrictInfo as the set of OJ relids that appear above the
+ * clause and null Vars that it uses. In practice we only bother to populate
+ * it for "clone" clauses, as it's currently only needed to prevent multiple
+ * clones of the same clause from being accepted for evaluation at the same
+ * join level.
+ *
+ * There is also an outer_relids field, which is NULL except for outer join
+ * clauses; for those, it is the set of relids on the outer side of the
+ * clause's outer join. (These are rels that the clause cannot be applied to
+ * in parameterized scans, since pushing it into the join's outer side would
+ * lead to wrong answers.)
+ *
+ * To handle security-barrier conditions efficiently, we mark RestrictInfo
+ * nodes with a security_level field, in which higher values identify clauses
+ * coming from less-trusted sources. The exact semantics are that a clause
+ * cannot be evaluated before another clause with a lower security_level value
+ * unless the first clause is leakproof. As with outer-join clauses, this
+ * creates a reason for clauses to sometimes need to be evaluated higher in
+ * the join tree than their contents would suggest; and even at a single plan
+ * node, this rule constrains the order of application of clauses.
+ *
+ * In general, the referenced clause might be arbitrarily complex. The
+ * kinds of clauses we can handle as indexscan quals, mergejoin clauses,
+ * or hashjoin clauses are limited (e.g., no volatile functions). The code
+ * for each kind of path is responsible for identifying the restrict clauses
+ * it can use and ignoring the rest. Clauses not implemented by an indexscan,
+ * mergejoin, or hashjoin will be placed in the plan qual or joinqual field
+ * of the finished Plan node, where they will be enforced by general-purpose
+ * qual-expression-evaluation code. (But we are still entitled to count
+ * their selectivity when estimating the result tuple count, if we
+ * can guess what it is...)
+ *
+ * When the referenced clause is an OR clause, we generate a modified copy
+ * in which additional RestrictInfo nodes are inserted below the top-level
+ * OR/AND structure. This is a convenience for OR indexscan processing:
+ * indexquals taken from either the top level or an OR subclause will have
+ * associated RestrictInfo nodes.
+ *
+ * The can_join flag is set true if the clause looks potentially useful as
+ * a merge or hash join clause, that is if it is a binary opclause with
+ * nonoverlapping sets of relids referenced in the left and right sides.
+ * (Whether the operator is actually merge or hash joinable isn't checked,
+ * however.)
+ *
+ * The pseudoconstant flag is set true if the clause contains no Vars of
+ * the current query level and no volatile functions. Such a clause can be
+ * pulled out and used as a one-time qual in a gating Result node. We keep
+ * pseudoconstant clauses in the same lists as other RestrictInfos so that
+ * the regular clause-pushing machinery can assign them to the correct join
+ * level, but they need to be treated specially for cost and selectivity
+ * estimates. Note that a pseudoconstant clause can never be an indexqual
+ * or merge or hash join clause, so it's of no interest to large parts of
+ * the planner.
+ *
+ * When we generate multiple versions of a clause so as to have versions
+ * that will work after commuting some left joins per outer join identity 3,
+ * we mark the one with the fewest nullingrels bits with has_clone = true,
+ * and the rest with is_clone = true. This allows proper filtering of
+ * these redundant clauses, so that we apply only one version of them.
+ *
+ * When join clauses are generated from EquivalenceClasses, there may be
+ * several equally valid ways to enforce join equivalence, of which we need
+ * apply only one. We mark clauses of this kind by setting parent_ec to
+ * point to the generating EquivalenceClass. Multiple clauses with the same
+ * parent_ec in the same join are redundant.
+ *
+ * Most fields are ignored for equality, since they may not be set yet, and
+ * should be derivable from the clause anyway.
+ *
+ * parent_ec, left_ec, right_ec are not printed, lest it lead to infinite
+ * recursion in plan tree dump.
+ */
+
+typedef struct RestrictInfo
+{
+ pg_node_attr(no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* the represented clause of WHERE or JOIN */
+ Expr *clause;
+
+ /* true if clause was pushed down in level */
+ bool is_pushed_down;
+
+ /* see comment above */
+ bool can_join pg_node_attr(equal_ignore);
+
+ /* see comment above */
+ bool pseudoconstant pg_node_attr(equal_ignore);
+
+ /* see comment above */
+ bool has_clone;
+ bool is_clone;
+
+ /* true if known to contain no leaked Vars */
+ bool leakproof pg_node_attr(equal_ignore);
+
+ /* indicates if clause contains any volatile functions */
+ VolatileFunctionStatus has_volatile pg_node_attr(equal_ignore);
+
+ /* see comment above */
+ Index security_level;
+
+ /* number of base rels in clause_relids */
+ int num_base_rels pg_node_attr(equal_ignore);
+
+ /* The relids (varnos+varnullingrels) actually referenced in the clause: */
+ Relids clause_relids pg_node_attr(equal_ignore);
+
+ /* The set of relids required to evaluate the clause: */
+ Relids required_relids;
+
+ /* Relids above which we cannot evaluate the clause (see comment above) */
+ Relids incompatible_relids;
+
+ /* If an outer-join clause, the outer-side relations, else NULL: */
+ Relids outer_relids;
+
+ /*
+ * Relids in the left/right side of the clause. These fields are set for
+ * any binary opclause.
+ */
+ Relids left_relids pg_node_attr(equal_ignore);
+ Relids right_relids pg_node_attr(equal_ignore);
+
+ /*
+ * Modified clause with RestrictInfos. This field is NULL unless clause
+ * is an OR clause.
+ */
+ Expr *orclause pg_node_attr(equal_ignore);
+
+ /*----------
+ * Serial number of this RestrictInfo. This is unique within the current
+ * PlannerInfo context, with a few critical exceptions:
+ * 1. When we generate multiple clones of the same qual condition to
+ * cope with outer join identity 3, all the clones get the same serial
+ * number. This reflects that we only want to apply one of them in any
+ * given plan.
+ * 2. If we manufacture a commuted version of a qual to use as an index
+ * condition, it copies the original's rinfo_serial, since it is in
+ * practice the same condition.
+ * 3. RestrictInfos made for a child relation copy their parent's
+ * rinfo_serial. Likewise, when an EquivalenceClass makes a derived
+ * equality clause for a child relation, it copies the rinfo_serial of
+ * the matching equality clause for the parent. This allows detection
+ * of redundant pushed-down equality clauses.
+ *----------
+ */
+ int rinfo_serial;
+
+ /*
+ * Generating EquivalenceClass. This field is NULL unless clause is
+ * potentially redundant.
+ */
+ EquivalenceClass *parent_ec pg_node_attr(copy_as_scalar, equal_ignore, read_write_ignore);
+
+ /*
+ * cache space for cost and selectivity
+ */
+
+ /* eval cost of clause; -1 if not yet set */
+ QualCost eval_cost pg_node_attr(equal_ignore);
+
+ /* selectivity for "normal" (JOIN_INNER) semantics; -1 if not yet set */
+ Selectivity norm_selec pg_node_attr(equal_ignore);
+ /* selectivity for outer join semantics; -1 if not yet set */
+ Selectivity outer_selec pg_node_attr(equal_ignore);
+
+ /*
+ * opfamilies containing clause operator; valid if clause is
+ * mergejoinable, else NIL
+ */
+ List *mergeopfamilies pg_node_attr(equal_ignore);
+
+ /*
+ * cache space for mergeclause processing; NULL if not yet set
+ */
+
+ /* EquivalenceClass containing lefthand */
+ EquivalenceClass *left_ec pg_node_attr(copy_as_scalar, equal_ignore, read_write_ignore);
+ /* EquivalenceClass containing righthand */
+ EquivalenceClass *right_ec pg_node_attr(copy_as_scalar, equal_ignore, read_write_ignore);
+ /* EquivalenceMember for lefthand */
+ EquivalenceMember *left_em pg_node_attr(copy_as_scalar, equal_ignore);
+ /* EquivalenceMember for righthand */
+ EquivalenceMember *right_em pg_node_attr(copy_as_scalar, equal_ignore);
+
+ /*
+ * List of MergeScanSelCache structs. Those aren't Nodes, so hard to
+ * copy; instead replace with NIL. That has the effect that copying will
+ * just reset the cache. Likewise, can't compare or print them.
+ */
+ List *scansel_cache pg_node_attr(copy_as(NIL), equal_ignore, read_write_ignore);
+
+ /*
+ * transient workspace for use while considering a specific join path; T =
+ * outer var on left, F = on right
+ */
+ bool outer_is_left pg_node_attr(equal_ignore);
+
+ /*
+ * copy of clause operator; valid if clause is hashjoinable, else
+ * InvalidOid
+ */
+ Oid hashjoinoperator pg_node_attr(equal_ignore);
+
+ /*
+ * cache space for hashclause processing; -1 if not yet set
+ */
+ /* avg bucketsize of left side */
+ Selectivity left_bucketsize pg_node_attr(equal_ignore);
+ /* avg bucketsize of right side */
+ Selectivity right_bucketsize pg_node_attr(equal_ignore);
+ /* left side's most common val's freq */
+ Selectivity left_mcvfreq pg_node_attr(equal_ignore);
+ /* right side's most common val's freq */
+ Selectivity right_mcvfreq pg_node_attr(equal_ignore);
+
+ /* hash equality operators used for memoize nodes, else InvalidOid */
+ Oid left_hasheqoperator pg_node_attr(equal_ignore);
+ Oid right_hasheqoperator pg_node_attr(equal_ignore);
+} RestrictInfo;
+
+/*
+ * This macro embodies the correct way to test whether a RestrictInfo is
+ * "pushed down" to a given outer join, that is, should be treated as a filter
+ * clause rather than a join clause at that outer join. This is certainly so
+ * if is_pushed_down is true; but examining that is not sufficient anymore,
+ * because outer-join clauses will get pushed down to lower outer joins when
+ * we generate a path for the lower outer join that is parameterized by the
+ * LHS of the upper one. We can detect such a clause by noting that its
+ * required_relids exceed the scope of the join.
+ */
+#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids) \
+ ((rinfo)->is_pushed_down || \
+ !bms_is_subset((rinfo)->required_relids, joinrelids))
+
+/*
+ * Since mergejoinscansel() is a relatively expensive function, and would
+ * otherwise be invoked many times while planning a large join tree,
+ * we go out of our way to cache its results. Each mergejoinable
+ * RestrictInfo carries a list of the specific sort orderings that have
+ * been considered for use with it, and the resulting selectivities.
+ */
+typedef struct MergeScanSelCache
+{
+ /* Ordering details (cache lookup key) */
+ Oid opfamily; /* btree opfamily defining the ordering */
+ Oid collation; /* collation for the ordering */
+ int strategy; /* sort direction (ASC or DESC) */
+ bool nulls_first; /* do NULLs come before normal values? */
+ /* Results */
+ Selectivity leftstartsel; /* first-join fraction for clause left side */
+ Selectivity leftendsel; /* last-join fraction for clause left side */
+ Selectivity rightstartsel; /* first-join fraction for clause right side */
+ Selectivity rightendsel; /* last-join fraction for clause right side */
+} MergeScanSelCache;
+
+/*
+ * Placeholder node for an expression to be evaluated below the top level
+ * of a plan tree. This is used during planning to represent the contained
+ * expression. At the end of the planning process it is replaced by either
+ * the contained expression or a Var referring to a lower-level evaluation of
+ * the contained expression. Generally the evaluation occurs below an outer
+ * join, and Var references above the outer join might thereby yield NULL
+ * instead of the expression value.
+ *
+ * phrels and phlevelsup correspond to the varno/varlevelsup fields of a
+ * plain Var, except that phrels has to be a relid set since the evaluation
+ * level of a PlaceHolderVar might be a join rather than a base relation.
+ * Likewise, phnullingrels corresponds to varnullingrels.
+ *
+ * Although the planner treats this as an expression node type, it is not
+ * recognized by the parser or executor, so we declare it here rather than
+ * in primnodes.h.
+ *
+ * We intentionally do not compare phexpr. Two PlaceHolderVars with the
+ * same ID and levelsup should be considered equal even if the contained
+ * expressions have managed to mutate to different states. This will
+ * happen during final plan construction when there are nested PHVs, since
+ * the inner PHV will get replaced by a Param in some copies of the outer
+ * PHV. Another way in which it can happen is that initplan sublinks
+ * could get replaced by differently-numbered Params when sublink folding
+ * is done. (The end result of such a situation would be some
+ * unreferenced initplans, which is annoying but not really a problem.)
+ * On the same reasoning, there is no need to examine phrels. But we do
+ * need to compare phnullingrels, as that represents effects that are
+ * external to the original value of the PHV.
+ */
+
+typedef struct PlaceHolderVar
+{
+ pg_node_attr(no_query_jumble)
+
+ Expr xpr;
+
+ /* the represented expression */
+ Expr *phexpr pg_node_attr(equal_ignore);
+
+ /* base+OJ relids syntactically within expr src */
+ Relids phrels pg_node_attr(equal_ignore);
+
+ /* RT indexes of outer joins that can null PHV's value */
+ Relids phnullingrels;
+
+ /* ID for PHV (unique within planner run) */
+ Index phid;
+
+ /* > 0 if PHV belongs to outer query */
+ Index phlevelsup;
+} PlaceHolderVar;
+
+/*
+ * "Special join" info.
+ *
+ * One-sided outer joins constrain the order of joining partially but not
+ * completely. We flatten such joins into the planner's top-level list of
+ * relations to join, but record information about each outer join in a
+ * SpecialJoinInfo struct. These structs are kept in the PlannerInfo node's
+ * join_info_list.
+ *
+ * Similarly, semijoins and antijoins created by flattening IN (subselect)
+ * and EXISTS(subselect) clauses create partial constraints on join order.
+ * These are likewise recorded in SpecialJoinInfo structs.
+ *
+ * We make SpecialJoinInfos for FULL JOINs even though there is no flexibility
+ * of planning for them, because this simplifies make_join_rel()'s API.
+ *
+ * min_lefthand and min_righthand are the sets of base+OJ relids that must be
+ * available on each side when performing the special join.
+ * It is not valid for either min_lefthand or min_righthand to be empty sets;
+ * if they were, this would break the logic that enforces join order.
+ *
+ * syn_lefthand and syn_righthand are the sets of base+OJ relids that are
+ * syntactically below this special join. (These are needed to help compute
+ * min_lefthand and min_righthand for higher joins.)
+ *
+ * jointype is never JOIN_RIGHT; a RIGHT JOIN is handled by switching
+ * the inputs to make it a LEFT JOIN. It's never JOIN_RIGHT_ANTI either.
+ * So the allowed values of jointype in a join_info_list member are only
+ * LEFT, FULL, SEMI, or ANTI.
+ *
+ * ojrelid is the RT index of the join RTE representing this outer join,
+ * if there is one. It is zero when jointype is INNER or SEMI, and can be
+ * zero for jointype ANTI (if the join was transformed from a SEMI join).
+ * One use for this field is that when constructing the output targetlist of a
+ * join relation that implements this OJ, we add ojrelid to the varnullingrels
+ * and phnullingrels fields of nullable (RHS) output columns, so that the
+ * output Vars and PlaceHolderVars correctly reflect the nulling that has
+ * potentially happened to them.
+ *
+ * commute_above_l is filled with the relids of syntactically-higher outer
+ * joins that have been found to commute with this one per outer join identity
+ * 3 (see optimizer/README), when this join is in the LHS of the upper join
+ * (so, this is the lower join in the first form of the identity).
+ *
+ * commute_above_r is filled with the relids of syntactically-higher outer
+ * joins that have been found to commute with this one per outer join identity
+ * 3, when this join is in the RHS of the upper join (so, this is the lower
+ * join in the second form of the identity).
+ *
+ * commute_below_l is filled with the relids of syntactically-lower outer
+ * joins that have been found to commute with this one per outer join identity
+ * 3 and are in the LHS of this join (so, this is the upper join in the first
+ * form of the identity).
+ *
+ * commute_below_r is filled with the relids of syntactically-lower outer
+ * joins that have been found to commute with this one per outer join identity
+ * 3 and are in the RHS of this join (so, this is the upper join in the second
+ * form of the identity).
+ *
+ * lhs_strict is true if the special join's condition cannot succeed when the
+ * LHS variables are all NULL (this means that an outer join can commute with
+ * upper-level outer joins even if it appears in their RHS). We don't bother
+ * to set lhs_strict for FULL JOINs, however.
+ *
+ * For a semijoin, we also extract the join operators and their RHS arguments
+ * and set semi_operators, semi_rhs_exprs, semi_can_btree, and semi_can_hash.
+ * This is done in support of possibly unique-ifying the RHS, so we don't
+ * bother unless at least one of semi_can_btree and semi_can_hash can be set
+ * true. (You might expect that this information would be computed during
+ * join planning; but it's helpful to have it available during planning of
+ * parameterized table scans, so we store it in the SpecialJoinInfo structs.)
+ *
+ * For purposes of join selectivity estimation, we create transient
+ * SpecialJoinInfo structures for regular inner joins; so it is possible
+ * to have jointype == JOIN_INNER in such a structure, even though this is
+ * not allowed within join_info_list. We also create transient
+ * SpecialJoinInfos with jointype == JOIN_INNER for outer joins, since for
+ * cost estimation purposes it is sometimes useful to know the join size under
+ * plain innerjoin semantics. Note that lhs_strict and the semi_xxx fields
+ * are not set meaningfully within such structs.
+ */
+#ifndef HAVE_SPECIALJOININFO_TYPEDEF
+typedef struct SpecialJoinInfo SpecialJoinInfo;
+#define HAVE_SPECIALJOININFO_TYPEDEF 1
+#endif
+
+struct SpecialJoinInfo
+{
+ pg_node_attr(no_read, no_query_jumble)
+
+ NodeTag type;
+ Relids min_lefthand; /* base+OJ relids in minimum LHS for join */
+ Relids min_righthand; /* base+OJ relids in minimum RHS for join */
+ Relids syn_lefthand; /* base+OJ relids syntactically within LHS */
+ Relids syn_righthand; /* base+OJ relids syntactically within RHS */
+ JoinType jointype; /* always INNER, LEFT, FULL, SEMI, or ANTI */
+ Index ojrelid; /* outer join's RT index; 0 if none */
+ Relids commute_above_l; /* commuting OJs above this one, if LHS */
+ Relids commute_above_r; /* commuting OJs above this one, if RHS */
+ Relids commute_below_l; /* commuting OJs in this one's LHS */
+ Relids commute_below_r; /* commuting OJs in this one's RHS */
+ bool lhs_strict; /* joinclause is strict for some LHS rel */
+ /* Remaining fields are set only for JOIN_SEMI jointype: */
+ bool semi_can_btree; /* true if semi_operators are all btree */
+ bool semi_can_hash; /* true if semi_operators are all hash */
+ List *semi_operators; /* OIDs of equality join operators */
+ List *semi_rhs_exprs; /* righthand-side expressions of these ops */
+};
+
+/*
+ * Transient outer-join clause info.
+ *
+ * We set aside every outer join ON clause that looks mergejoinable,
+ * and process it specially at the end of qual distribution.
+ */
+typedef struct OuterJoinClauseInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+ RestrictInfo *rinfo; /* a mergejoinable outer-join clause */
+ SpecialJoinInfo *sjinfo; /* the outer join's SpecialJoinInfo */
+} OuterJoinClauseInfo;
+
+/*
+ * Append-relation info.
+ *
+ * When we expand an inheritable table or a UNION-ALL subselect into an
+ * "append relation" (essentially, a list of child RTEs), we build an
+ * AppendRelInfo for each child RTE. The list of AppendRelInfos indicates
+ * which child RTEs must be included when expanding the parent, and each node
+ * carries information needed to translate between columns of the parent and
+ * columns of the child.
+ *
+ * These structs are kept in the PlannerInfo node's append_rel_list, with
+ * append_rel_array[] providing a convenient lookup method for the struct
+ * associated with a particular child relid (there can be only one, though
+ * parent rels may have many entries in append_rel_list).
+ *
+ * Note: after completion of the planner prep phase, any given RTE is an
+ * append parent having entries in append_rel_list if and only if its
+ * "inh" flag is set. We clear "inh" for plain tables that turn out not
+ * to have inheritance children, and (in an abuse of the original meaning
+ * of the flag) we set "inh" for subquery RTEs that turn out to be
+ * flattenable UNION ALL queries. This lets us avoid useless searches
+ * of append_rel_list.
+ *
+ * Note: the data structure assumes that append-rel members are single
+ * baserels. This is OK for inheritance, but it prevents us from pulling
+ * up a UNION ALL member subquery if it contains a join. While that could
+ * be fixed with a more complex data structure, at present there's not much
+ * point because no improvement in the plan could result.
+ */
+
+typedef struct AppendRelInfo
+{
+ pg_node_attr(no_query_jumble)
+
+ NodeTag type;
+
+ /*
+ * These fields uniquely identify this append relationship. There can be
+ * (in fact, always should be) multiple AppendRelInfos for the same
+ * parent_relid, but never more than one per child_relid, since a given
+ * RTE cannot be a child of more than one append parent.
+ */
+ Index parent_relid; /* RT index of append parent rel */
+ Index child_relid; /* RT index of append child rel */
+
+ /*
+ * For an inheritance appendrel, the parent and child are both regular
+ * relations, and we store their rowtype OIDs here for use in translating
+ * whole-row Vars. For a UNION-ALL appendrel, the parent and child are
+ * both subqueries with no named rowtype, and we store InvalidOid here.
+ */
+ Oid parent_reltype; /* OID of parent's composite type */
+ Oid child_reltype; /* OID of child's composite type */
+
+ /*
+ * The N'th element of this list is a Var or expression representing the
+ * child column corresponding to the N'th column of the parent. This is
+ * used to translate Vars referencing the parent rel into references to
+ * the child. A list element is NULL if it corresponds to a dropped
+ * column of the parent (this is only possible for inheritance cases, not
+ * UNION ALL). The list elements are always simple Vars for inheritance
+ * cases, but can be arbitrary expressions in UNION ALL cases.
+ *
+ * Notice we only store entries for user columns (attno > 0). Whole-row
+ * Vars are special-cased, and system columns (attno < 0) need no special
+ * translation since their attnos are the same for all tables.
+ *
+ * Caution: the Vars have varlevelsup = 0. Be careful to adjust as needed
+ * when copying into a subquery.
+ */
+ List *translated_vars; /* Expressions in the child's Vars */
+
+ /*
+ * This array simplifies translations in the reverse direction, from
+ * child's column numbers to parent's. The entry at [ccolno - 1] is the
+ * 1-based parent column number for child column ccolno, or zero if that
+ * child column is dropped or doesn't exist in the parent.
+ */
+ int num_child_cols; /* length of array */
+ AttrNumber *parent_colnos pg_node_attr(array_size(num_child_cols));
+
+ /*
+ * We store the parent table's OID here for inheritance, or InvalidOid for
+ * UNION ALL. This is only needed to help in generating error messages if
+ * an attempt is made to reference a dropped parent column.
+ */
+ Oid parent_reloid; /* OID of parent relation */
+} AppendRelInfo;
+
+/*
+ * Information about a row-identity "resjunk" column in UPDATE/DELETE/MERGE.
+ *
+ * In partitioned UPDATE/DELETE/MERGE it's important for child partitions to
+ * share row-identity columns whenever possible, so as not to chew up too many
+ * targetlist columns. We use these structs to track which identity columns
+ * have been requested. In the finished plan, each of these will give rise
+ * to one resjunk entry in the targetlist of the ModifyTable's subplan node.
+ *
+ * All the Vars stored in RowIdentityVarInfos must have varno ROWID_VAR, for
+ * convenience of detecting duplicate requests. We'll replace that, in the
+ * final plan, with the varno of the generating rel.
+ *
+ * Outside this list, a Var with varno ROWID_VAR and varattno k is a reference
+ * to the k-th element of the row_identity_vars list (k counting from 1).
+ * We add such a reference to root->processed_tlist when creating the entry,
+ * and it propagates into the plan tree from there.
+ */
+typedef struct RowIdentityVarInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ Var *rowidvar; /* Var to be evaluated (but varno=ROWID_VAR) */
+ int32 rowidwidth; /* estimated average width */
+ char *rowidname; /* name of the resjunk column */
+ Relids rowidrels; /* RTE indexes of target rels using this */
+} RowIdentityVarInfo;
+
+/*
+ * For each distinct placeholder expression generated during planning, we
+ * store a PlaceHolderInfo node in the PlannerInfo node's placeholder_list.
+ * This stores info that is needed centrally rather than in each copy of the
+ * PlaceHolderVar. The phid fields identify which PlaceHolderInfo goes with
+ * each PlaceHolderVar. Note that phid is unique throughout a planner run,
+ * not just within a query level --- this is so that we need not reassign ID's
+ * when pulling a subquery into its parent.
+ *
+ * The idea is to evaluate the expression at (only) the ph_eval_at join level,
+ * then allow it to bubble up like a Var until the ph_needed join level.
+ * ph_needed has the same definition as attr_needed for a regular Var.
+ *
+ * The PlaceHolderVar's expression might contain LATERAL references to vars
+ * coming from outside its syntactic scope. If so, those rels are *not*
+ * included in ph_eval_at, but they are recorded in ph_lateral.
+ *
+ * Notice that when ph_eval_at is a join rather than a single baserel, the
+ * PlaceHolderInfo may create constraints on join order: the ph_eval_at join
+ * has to be formed below any outer joins that should null the PlaceHolderVar.
+ *
+ * We create a PlaceHolderInfo only after determining that the PlaceHolderVar
+ * is actually referenced in the plan tree, so that unreferenced placeholders
+ * don't result in unnecessary constraints on join order.
+ */
+
+typedef struct PlaceHolderInfo
+{
+ pg_node_attr(no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* ID for PH (unique within planner run) */
+ Index phid;
+
+ /*
+ * copy of PlaceHolderVar tree (should be redundant for comparison, could
+ * be ignored)
+ */
+ PlaceHolderVar *ph_var;
+
+ /* lowest level we can evaluate value at */
+ Relids ph_eval_at;
+
+ /* relids of contained lateral refs, if any */
+ Relids ph_lateral;
+
+ /* highest level the value is needed at */
+ Relids ph_needed;
+
+ /* estimated attribute width */
+ int32 ph_width;
+} PlaceHolderInfo;
+
+/*
+ * This struct describes one potentially index-optimizable MIN/MAX aggregate
+ * function. MinMaxAggPath contains a list of these, and if we accept that
+ * path, the list is stored into root->minmax_aggs for use during setrefs.c.
+ */
+typedef struct MinMaxAggInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* pg_proc Oid of the aggregate */
+ Oid aggfnoid;
+
+ /* Oid of its sort operator */
+ Oid aggsortop;
+
+ /* expression we are aggregating on */
+ Expr *target;
+
+ /*
+ * modified "root" for planning the subquery; not printed, too large, not
+ * interesting enough
+ */
+ PlannerInfo *subroot pg_node_attr(read_write_ignore);
+
+ /* access path for subquery */
+ Path *path;
+
+ /* estimated cost to fetch first row */
+ Cost pathcost;
+
+ /* param for subplan's output */
+ Param *param;
+} MinMaxAggInfo;
+
+/*
+ * At runtime, PARAM_EXEC slots are used to pass values around from one plan
+ * node to another. They can be used to pass values down into subqueries (for
+ * outer references in subqueries), or up out of subqueries (for the results
+ * of a subplan), or from a NestLoop plan node into its inner relation (when
+ * the inner scan is parameterized with values from the outer relation).
+ * The planner is responsible for assigning nonconflicting PARAM_EXEC IDs to
+ * the PARAM_EXEC Params it generates.
+ *
+ * Outer references are managed via root->plan_params, which is a list of
+ * PlannerParamItems. While planning a subquery, each parent query level's
+ * plan_params contains the values required from it by the current subquery.
+ * During create_plan(), we use plan_params to track values that must be
+ * passed from outer to inner sides of NestLoop plan nodes.
+ *
+ * The item a PlannerParamItem represents can be one of three kinds:
+ *
+ * A Var: the slot represents a variable of this level that must be passed
+ * down because subqueries have outer references to it, or must be passed
+ * from a NestLoop node to its inner scan. The varlevelsup value in the Var
+ * will always be zero.
+ *
+ * A PlaceHolderVar: this works much like the Var case, except that the
+ * entry is a PlaceHolderVar node with a contained expression. The PHV
+ * will have phlevelsup = 0, and the contained expression is adjusted
+ * to match in level.
+ *
+ * An Aggref (with an expression tree representing its argument): the slot
+ * represents an aggregate expression that is an outer reference for some
+ * subquery. The Aggref itself has agglevelsup = 0, and its argument tree
+ * is adjusted to match in level.
+ *
+ * Note: we detect duplicate Var and PlaceHolderVar parameters and coalesce
+ * them into one slot, but we do not bother to do that for Aggrefs.
+ * The scope of duplicate-elimination only extends across the set of
+ * parameters passed from one query level into a single subquery, or for
+ * nestloop parameters across the set of nestloop parameters used in a single
+ * query level. So there is no possibility of a PARAM_EXEC slot being used
+ * for conflicting purposes.
+ *
+ * In addition, PARAM_EXEC slots are assigned for Params representing outputs
+ * from subplans (values that are setParam items for those subplans). These
+ * IDs need not be tracked via PlannerParamItems, since we do not need any
+ * duplicate-elimination nor later processing of the represented expressions.
+ * Instead, we just record the assignment of the slot number by appending to
+ * root->glob->paramExecTypes.
+ */
+typedef struct PlannerParamItem
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ Node *item; /* the Var, PlaceHolderVar, or Aggref */
+ int paramId; /* its assigned PARAM_EXEC slot number */
+} PlannerParamItem;
+
+/*
+ * When making cost estimates for a SEMI/ANTI/inner_unique join, there are
+ * some correction factors that are needed in both nestloop and hash joins
+ * to account for the fact that the executor can stop scanning inner rows
+ * as soon as it finds a match to the current outer row. These numbers
+ * depend only on the selected outer and inner join relations, not on the
+ * particular paths used for them, so it's worthwhile to calculate them
+ * just once per relation pair not once per considered path. This struct
+ * is filled by compute_semi_anti_join_factors and must be passed along
+ * to the join cost estimation functions.
+ *
+ * outer_match_frac is the fraction of the outer tuples that are
+ * expected to have at least one match.
+ * match_count is the average number of matches expected for
+ * outer tuples that have at least one match.
+ */
+typedef struct SemiAntiJoinFactors
+{
+ Selectivity outer_match_frac;
+ Selectivity match_count;
+} SemiAntiJoinFactors;
+
+/*
+ * Struct for extra information passed to subroutines of add_paths_to_joinrel
+ *
+ * restrictlist contains all of the RestrictInfo nodes for restriction
+ * clauses that apply to this join
+ * mergeclause_list is a list of RestrictInfo nodes for available
+ * mergejoin clauses in this join
+ * inner_unique is true if each outer tuple provably matches no more
+ * than one inner tuple
+ * sjinfo is extra info about special joins for selectivity estimation
+ * semifactors is as shown above (only valid for SEMI/ANTI/inner_unique joins)
+ * param_source_rels are OK targets for parameterization of result paths
+ */
+typedef struct JoinPathExtraData
+{
+ List *restrictlist;
+ List *mergeclause_list;
+ bool inner_unique;
+ SpecialJoinInfo *sjinfo;
+ SemiAntiJoinFactors semifactors;
+ Relids param_source_rels;
+} JoinPathExtraData;
+
+/*
+ * Various flags indicating what kinds of grouping are possible.
+ *
+ * GROUPING_CAN_USE_SORT should be set if it's possible to perform
+ * sort-based implementations of grouping. When grouping sets are in use,
+ * this will be true if sorting is potentially usable for any of the grouping
+ * sets, even if it's not usable for all of them.
+ *
+ * GROUPING_CAN_USE_HASH should be set if it's possible to perform
+ * hash-based implementations of grouping.
+ *
+ * GROUPING_CAN_PARTIAL_AGG should be set if the aggregation is of a type
+ * for which we support partial aggregation (not, for example, grouping sets).
+ * It says nothing about parallel-safety or the availability of suitable paths.
+ */
+#define GROUPING_CAN_USE_SORT 0x0001
+#define GROUPING_CAN_USE_HASH 0x0002
+#define GROUPING_CAN_PARTIAL_AGG 0x0004
+
+/*
+ * What kind of partitionwise aggregation is in use?
+ *
+ * PARTITIONWISE_AGGREGATE_NONE: Not used.
+ *
+ * PARTITIONWISE_AGGREGATE_FULL: Aggregate each partition separately, and
+ * append the results.
+ *
+ * PARTITIONWISE_AGGREGATE_PARTIAL: Partially aggregate each partition
+ * separately, append the results, and then finalize aggregation.
+ */
+typedef enum
+{
+ PARTITIONWISE_AGGREGATE_NONE,
+ PARTITIONWISE_AGGREGATE_FULL,
+ PARTITIONWISE_AGGREGATE_PARTIAL
+} PartitionwiseAggregateType;
+
+/*
+ * Struct for extra information passed to subroutines of create_grouping_paths
+ *
+ * flags indicating what kinds of grouping are possible.
+ * partial_costs_set is true if the agg_partial_costs and agg_final_costs
+ * have been initialized.
+ * agg_partial_costs gives partial aggregation costs.
+ * agg_final_costs gives finalization costs.
+ * target_parallel_safe is true if target is parallel safe.
+ * havingQual gives list of quals to be applied after aggregation.
+ * targetList gives list of columns to be projected.
+ * patype is the type of partitionwise aggregation that is being performed.
+ */
+typedef struct
+{
+ /* Data which remains constant once set. */
+ int flags;
+ bool partial_costs_set;
+ AggClauseCosts agg_partial_costs;
+ AggClauseCosts agg_final_costs;
+
+ /* Data which may differ across partitions. */
+ bool target_parallel_safe;
+ Node *havingQual;
+ List *targetList;
+ PartitionwiseAggregateType patype;
+} GroupPathExtraData;
+
+/*
+ * Struct for extra information passed to subroutines of grouping_planner
+ *
+ * limit_needed is true if we actually need a Limit plan node.
+ * limit_tuples is an estimated bound on the number of output tuples,
+ * or -1 if no LIMIT or couldn't estimate.
+ * count_est and offset_est are the estimated values of the LIMIT and OFFSET
+ * expressions computed by preprocess_limit() (see comments for
+ * preprocess_limit() for more information).
+ */
+typedef struct
+{
+ bool limit_needed;
+ Cardinality limit_tuples;
+ int64 count_est;
+ int64 offset_est;
+} FinalPathExtraData;
+
+/*
+ * For speed reasons, cost estimation for join paths is performed in two
+ * phases: the first phase tries to quickly derive a lower bound for the
+ * join cost, and then we check if that's sufficient to reject the path.
+ * If not, we come back for a more refined cost estimate. The first phase
+ * fills a JoinCostWorkspace struct with its preliminary cost estimates
+ * and possibly additional intermediate values. The second phase takes
+ * these values as inputs to avoid repeating work.
+ *
+ * (Ideally we'd declare this in cost.h, but it's also needed in pathnode.h,
+ * so seems best to put it here.)
+ */
+typedef struct JoinCostWorkspace
+{
+ /* Preliminary cost estimates --- must not be larger than final ones! */
+ Cost startup_cost; /* cost expended before fetching any tuples */
+ Cost total_cost; /* total cost (assuming all tuples fetched) */
+
+ /* Fields below here should be treated as private to costsize.c */
+ Cost run_cost; /* non-startup cost components */
+
+ /* private for cost_nestloop code */
+ Cost inner_run_cost; /* also used by cost_mergejoin code */
+ Cost inner_rescan_run_cost;
+
+ /* private for cost_mergejoin code */
+ Cardinality outer_rows;
+ Cardinality inner_rows;
+ Cardinality outer_skip_rows;
+ Cardinality inner_skip_rows;
+
+ /* private for cost_hashjoin code */
+ int numbuckets;
+ int numbatches;
+ Cardinality inner_rows_total;
+} JoinCostWorkspace;
+
+/*
+ * AggInfo holds information about an aggregate that needs to be computed.
+ * Multiple Aggrefs in a query can refer to the same AggInfo by having the
+ * same 'aggno' value, so that the aggregate is computed only once.
+ */
+typedef struct AggInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /*
+ * List of Aggref exprs that this state value is for.
+ *
+ * There will always be at least one, but there can be multiple identical
+ * Aggref's sharing the same per-agg.
+ */
+ List *aggrefs;
+
+ /* Transition state number for this aggregate */
+ int transno;
+
+ /*
+ * "shareable" is false if this agg cannot share state values with other
+ * aggregates because the final function is read-write.
+ */
+ bool shareable;
+
+ /* Oid of the final function, or InvalidOid if none */
+ Oid finalfn_oid;
+} AggInfo;
+
+/*
+ * AggTransInfo holds information about transition state that is used by one
+ * or more aggregates in the query. Multiple aggregates can share the same
+ * transition state, if they have the same inputs and the same transition
+ * function. Aggrefs that share the same transition info have the same
+ * 'aggtransno' value.
+ */
+typedef struct AggTransInfo
+{
+ pg_node_attr(no_copy_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+
+ /* Inputs for this transition state */
+ List *args;
+ Expr *aggfilter;
+
+ /* Oid of the state transition function */
+ Oid transfn_oid;
+
+ /* Oid of the serialization function, or InvalidOid if none */
+ Oid serialfn_oid;
+
+ /* Oid of the deserialization function, or InvalidOid if none */
+ Oid deserialfn_oid;
+
+ /* Oid of the combine function, or InvalidOid if none */
+ Oid combinefn_oid;
+
+ /* Oid of state value's datatype */
+ Oid aggtranstype;
+
+ /* Additional data about transtype */
+ int32 aggtranstypmod;
+ int transtypeLen;
+ bool transtypeByVal;
+
+ /* Space-consumption estimate */
+ int32 aggtransspace;
+
+ /* Initial value from pg_aggregate entry */
+ Datum initValue pg_node_attr(read_write_ignore);
+ bool initValueIsNull;
+} AggTransInfo;
+
+#endif /* PATHNODES_H */
diff --git a/pgsql/include/server/nodes/pg_list.h b/pgsql/include/server/nodes/pg_list.h
new file mode 100644
index 0000000000000000000000000000000000000000..529a382d284c38f3a3a57cb0ef839c18f6fac3da
--- /dev/null
+++ b/pgsql/include/server/nodes/pg_list.h
@@ -0,0 +1,635 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_list.h
+ * interface for PostgreSQL generic list package
+ *
+ * Once upon a time, parts of Postgres were written in Lisp and used real
+ * cons-cell lists for major data structures. When that code was rewritten
+ * in C, we initially had a faithful emulation of cons-cell lists, which
+ * unsurprisingly was a performance bottleneck. A couple of major rewrites
+ * later, these data structures are actually simple expansible arrays;
+ * but the "List" name and a lot of the notation survives.
+ *
+ * One important concession to the original implementation is that an empty
+ * list is always represented by a null pointer (preferentially written NIL).
+ * Non-empty lists have a header, which will not be relocated as long as the
+ * list remains non-empty, and an expansible data array.
+ *
+ * We support four types of lists:
+ *
+ * T_List: lists of pointers
+ * (in practice usually pointers to Nodes, but not always;
+ * declared as "void *" to minimize casting annoyances)
+ * T_IntList: lists of integers
+ * T_OidList: lists of Oids
+ * T_XidList: lists of TransactionIds
+ * (the XidList infrastructure is less complete than the other cases)
+ *
+ * (At the moment, ints, Oids, and XIDs are the same size, but they may not
+ * always be so; be careful to use the appropriate list type for your data.)
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/pg_list.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_LIST_H
+#define PG_LIST_H
+
+#include "nodes/nodes.h"
+
+
+typedef union ListCell
+{
+ void *ptr_value;
+ int int_value;
+ Oid oid_value;
+ TransactionId xid_value;
+} ListCell;
+
+typedef struct List
+{
+ NodeTag type; /* T_List, T_IntList, T_OidList, or T_XidList */
+ int length; /* number of elements currently present */
+ int max_length; /* allocated length of elements[] */
+ ListCell *elements; /* re-allocatable array of cells */
+ /* We may allocate some cells along with the List header: */
+ ListCell initial_elements[FLEXIBLE_ARRAY_MEMBER];
+ /* If elements == initial_elements, it's not a separate allocation */
+} List;
+
+/*
+ * The *only* valid representation of an empty list is NIL; in other
+ * words, a non-NIL list is guaranteed to have length >= 1.
+ */
+#define NIL ((List *) NULL)
+
+/*
+ * State structs for various looping macros below.
+ */
+typedef struct ForEachState
+{
+ const List *l; /* list we're looping through */
+ int i; /* current element index */
+} ForEachState;
+
+typedef struct ForBothState
+{
+ const List *l1; /* lists we're looping through */
+ const List *l2;
+ int i; /* common element index */
+} ForBothState;
+
+typedef struct ForBothCellState
+{
+ const List *l1; /* lists we're looping through */
+ const List *l2;
+ int i1; /* current element indexes */
+ int i2;
+} ForBothCellState;
+
+typedef struct ForThreeState
+{
+ const List *l1; /* lists we're looping through */
+ const List *l2;
+ const List *l3;
+ int i; /* common element index */
+} ForThreeState;
+
+typedef struct ForFourState
+{
+ const List *l1; /* lists we're looping through */
+ const List *l2;
+ const List *l3;
+ const List *l4;
+ int i; /* common element index */
+} ForFourState;
+
+typedef struct ForFiveState
+{
+ const List *l1; /* lists we're looping through */
+ const List *l2;
+ const List *l3;
+ const List *l4;
+ const List *l5;
+ int i; /* common element index */
+} ForFiveState;
+
+/*
+ * These routines are small enough, and used often enough, to justify being
+ * inline.
+ */
+
+/* Fetch address of list's first cell; NULL if empty list */
+static inline ListCell *
+list_head(const List *l)
+{
+ return l ? &l->elements[0] : NULL;
+}
+
+/* Fetch address of list's last cell; NULL if empty list */
+static inline ListCell *
+list_tail(const List *l)
+{
+ return l ? &l->elements[l->length - 1] : NULL;
+}
+
+/* Fetch address of list's second cell, if it has one, else NULL */
+static inline ListCell *
+list_second_cell(const List *l)
+{
+ if (l && l->length >= 2)
+ return &l->elements[1];
+ else
+ return NULL;
+}
+
+/* Fetch list's length */
+static inline int
+list_length(const List *l)
+{
+ return l ? l->length : 0;
+}
+
+/*
+ * Macros to access the data values within List cells.
+ *
+ * Note that with the exception of the "xxx_node" macros, these are
+ * lvalues and can be assigned to.
+ *
+ * NB: There is an unfortunate legacy from a previous incarnation of
+ * the List API: the macro lfirst() was used to mean "the data in this
+ * cons cell". To avoid changing every usage of lfirst(), that meaning
+ * has been kept. As a result, lfirst() takes a ListCell and returns
+ * the data it contains; to get the data in the first cell of a
+ * List, use linitial(). Worse, lsecond() is more closely related to
+ * linitial() than lfirst(): given a List, lsecond() returns the data
+ * in the second list cell.
+ */
+#define lfirst(lc) ((lc)->ptr_value)
+#define lfirst_int(lc) ((lc)->int_value)
+#define lfirst_oid(lc) ((lc)->oid_value)
+#define lfirst_xid(lc) ((lc)->xid_value)
+#define lfirst_node(type,lc) castNode(type, lfirst(lc))
+
+#define linitial(l) lfirst(list_nth_cell(l, 0))
+#define linitial_int(l) lfirst_int(list_nth_cell(l, 0))
+#define linitial_oid(l) lfirst_oid(list_nth_cell(l, 0))
+#define linitial_node(type,l) castNode(type, linitial(l))
+
+#define lsecond(l) lfirst(list_nth_cell(l, 1))
+#define lsecond_int(l) lfirst_int(list_nth_cell(l, 1))
+#define lsecond_oid(l) lfirst_oid(list_nth_cell(l, 1))
+#define lsecond_node(type,l) castNode(type, lsecond(l))
+
+#define lthird(l) lfirst(list_nth_cell(l, 2))
+#define lthird_int(l) lfirst_int(list_nth_cell(l, 2))
+#define lthird_oid(l) lfirst_oid(list_nth_cell(l, 2))
+#define lthird_node(type,l) castNode(type, lthird(l))
+
+#define lfourth(l) lfirst(list_nth_cell(l, 3))
+#define lfourth_int(l) lfirst_int(list_nth_cell(l, 3))
+#define lfourth_oid(l) lfirst_oid(list_nth_cell(l, 3))
+#define lfourth_node(type,l) castNode(type, lfourth(l))
+
+#define llast(l) lfirst(list_last_cell(l))
+#define llast_int(l) lfirst_int(list_last_cell(l))
+#define llast_oid(l) lfirst_oid(list_last_cell(l))
+#define llast_xid(l) lfirst_xid(list_last_cell(l))
+#define llast_node(type,l) castNode(type, llast(l))
+
+/*
+ * Convenience macros for building fixed-length lists
+ */
+#define list_make_ptr_cell(v) ((ListCell) {.ptr_value = (v)})
+#define list_make_int_cell(v) ((ListCell) {.int_value = (v)})
+#define list_make_oid_cell(v) ((ListCell) {.oid_value = (v)})
+#define list_make_xid_cell(v) ((ListCell) {.xid_value = (v)})
+
+#define list_make1(x1) \
+ list_make1_impl(T_List, list_make_ptr_cell(x1))
+#define list_make2(x1,x2) \
+ list_make2_impl(T_List, list_make_ptr_cell(x1), list_make_ptr_cell(x2))
+#define list_make3(x1,x2,x3) \
+ list_make3_impl(T_List, list_make_ptr_cell(x1), list_make_ptr_cell(x2), \
+ list_make_ptr_cell(x3))
+#define list_make4(x1,x2,x3,x4) \
+ list_make4_impl(T_List, list_make_ptr_cell(x1), list_make_ptr_cell(x2), \
+ list_make_ptr_cell(x3), list_make_ptr_cell(x4))
+#define list_make5(x1,x2,x3,x4,x5) \
+ list_make5_impl(T_List, list_make_ptr_cell(x1), list_make_ptr_cell(x2), \
+ list_make_ptr_cell(x3), list_make_ptr_cell(x4), \
+ list_make_ptr_cell(x5))
+
+#define list_make1_int(x1) \
+ list_make1_impl(T_IntList, list_make_int_cell(x1))
+#define list_make2_int(x1,x2) \
+ list_make2_impl(T_IntList, list_make_int_cell(x1), list_make_int_cell(x2))
+#define list_make3_int(x1,x2,x3) \
+ list_make3_impl(T_IntList, list_make_int_cell(x1), list_make_int_cell(x2), \
+ list_make_int_cell(x3))
+#define list_make4_int(x1,x2,x3,x4) \
+ list_make4_impl(T_IntList, list_make_int_cell(x1), list_make_int_cell(x2), \
+ list_make_int_cell(x3), list_make_int_cell(x4))
+#define list_make5_int(x1,x2,x3,x4,x5) \
+ list_make5_impl(T_IntList, list_make_int_cell(x1), list_make_int_cell(x2), \
+ list_make_int_cell(x3), list_make_int_cell(x4), \
+ list_make_int_cell(x5))
+
+#define list_make1_oid(x1) \
+ list_make1_impl(T_OidList, list_make_oid_cell(x1))
+#define list_make2_oid(x1,x2) \
+ list_make2_impl(T_OidList, list_make_oid_cell(x1), list_make_oid_cell(x2))
+#define list_make3_oid(x1,x2,x3) \
+ list_make3_impl(T_OidList, list_make_oid_cell(x1), list_make_oid_cell(x2), \
+ list_make_oid_cell(x3))
+#define list_make4_oid(x1,x2,x3,x4) \
+ list_make4_impl(T_OidList, list_make_oid_cell(x1), list_make_oid_cell(x2), \
+ list_make_oid_cell(x3), list_make_oid_cell(x4))
+#define list_make5_oid(x1,x2,x3,x4,x5) \
+ list_make5_impl(T_OidList, list_make_oid_cell(x1), list_make_oid_cell(x2), \
+ list_make_oid_cell(x3), list_make_oid_cell(x4), \
+ list_make_oid_cell(x5))
+
+#define list_make1_xid(x1) \
+ list_make1_impl(T_XidList, list_make_xid_cell(x1))
+#define list_make2_xid(x1,x2) \
+ list_make2_impl(T_XidList, list_make_xid_cell(x1), list_make_xid_cell(x2))
+#define list_make3_xid(x1,x2,x3) \
+ list_make3_impl(T_XidList, list_make_xid_cell(x1), list_make_xid_cell(x2), \
+ list_make_xid_cell(x3))
+#define list_make4_xid(x1,x2,x3,x4) \
+ list_make4_impl(T_XidList, list_make_xid_cell(x1), list_make_xid_cell(x2), \
+ list_make_xid_cell(x3), list_make_xid_cell(x4))
+#define list_make5_xid(x1,x2,x3,x4,x5) \
+ list_make5_impl(T_XidList, list_make_xid_cell(x1), list_make_xid_cell(x2), \
+ list_make_xid_cell(x3), list_make_xid_cell(x4), \
+ list_make_xid_cell(x5))
+
+/*
+ * Locate the n'th cell (counting from 0) of the list.
+ * It is an assertion failure if there is no such cell.
+ */
+static inline ListCell *
+list_nth_cell(const List *list, int n)
+{
+ Assert(list != NIL);
+ Assert(n >= 0 && n < list->length);
+ return &list->elements[n];
+}
+
+/*
+ * Return the last cell in a non-NIL List.
+ */
+static inline ListCell *
+list_last_cell(const List *list)
+{
+ Assert(list != NIL);
+ return &list->elements[list->length - 1];
+}
+
+/*
+ * Return the pointer value contained in the n'th element of the
+ * specified list. (List elements begin at 0.)
+ */
+static inline void *
+list_nth(const List *list, int n)
+{
+ Assert(IsA(list, List));
+ return lfirst(list_nth_cell(list, n));
+}
+
+/*
+ * Return the integer value contained in the n'th element of the
+ * specified list.
+ */
+static inline int
+list_nth_int(const List *list, int n)
+{
+ Assert(IsA(list, IntList));
+ return lfirst_int(list_nth_cell(list, n));
+}
+
+/*
+ * Return the OID value contained in the n'th element of the specified
+ * list.
+ */
+static inline Oid
+list_nth_oid(const List *list, int n)
+{
+ Assert(IsA(list, OidList));
+ return lfirst_oid(list_nth_cell(list, n));
+}
+
+#define list_nth_node(type,list,n) castNode(type, list_nth(list, n))
+
+/*
+ * Get the given ListCell's index (from 0) in the given List.
+ */
+static inline int
+list_cell_number(const List *l, const ListCell *c)
+{
+ Assert(c >= &l->elements[0] && c < &l->elements[l->length]);
+ return c - l->elements;
+}
+
+/*
+ * Get the address of the next cell after "c" within list "l", or NULL if none.
+ */
+static inline ListCell *
+lnext(const List *l, const ListCell *c)
+{
+ Assert(c >= &l->elements[0] && c < &l->elements[l->length]);
+ c++;
+ if (c < &l->elements[l->length])
+ return (ListCell *) c;
+ else
+ return NULL;
+}
+
+/*
+ * foreach -
+ * a convenience macro for looping through a list
+ *
+ * "cell" must be the name of a "ListCell *" variable; it's made to point
+ * to each List element in turn. "cell" will be NULL after normal exit from
+ * the loop, but an early "break" will leave it pointing at the current
+ * List element.
+ *
+ * Beware of changing the List object while the loop is iterating.
+ * The current semantics are that we examine successive list indices in
+ * each iteration, so that insertion or deletion of list elements could
+ * cause elements to be re-visited or skipped unexpectedly. Previous
+ * implementations of foreach() behaved differently. However, it's safe
+ * to append elements to the List (or in general, insert them after the
+ * current element); such new elements are guaranteed to be visited.
+ * Also, the current element of the List can be deleted, if you use
+ * foreach_delete_current() to do so. BUT: either of these actions will
+ * invalidate the "cell" pointer for the remainder of the current iteration.
+ */
+#define foreach(cell, lst) \
+ for (ForEachState cell##__state = {(lst), 0}; \
+ (cell##__state.l != NIL && \
+ cell##__state.i < cell##__state.l->length) ? \
+ (cell = &cell##__state.l->elements[cell##__state.i], true) : \
+ (cell = NULL, false); \
+ cell##__state.i++)
+
+/*
+ * foreach_delete_current -
+ * delete the current list element from the List associated with a
+ * surrounding foreach() loop, returning the new List pointer.
+ *
+ * This is equivalent to list_delete_cell(), but it also adjusts the foreach
+ * loop's state so that no list elements will be missed. Do not delete
+ * elements from an active foreach loop's list in any other way!
+ */
+#define foreach_delete_current(lst, cell) \
+ (cell##__state.i--, \
+ (List *) (cell##__state.l = list_delete_cell(lst, cell)))
+
+/*
+ * foreach_current_index -
+ * get the zero-based list index of a surrounding foreach() loop's
+ * current element; pass the name of the "ListCell *" iterator variable.
+ *
+ * Beware of using this after foreach_delete_current(); the value will be
+ * out of sync for the rest of the current loop iteration. Anyway, since
+ * you just deleted the current element, the value is pretty meaningless.
+ */
+#define foreach_current_index(cell) (cell##__state.i)
+
+/*
+ * for_each_from -
+ * Like foreach(), but start from the N'th (zero-based) list element,
+ * not necessarily the first one.
+ *
+ * It's okay for N to exceed the list length, but not for it to be negative.
+ *
+ * The caveats for foreach() apply equally here.
+ */
+#define for_each_from(cell, lst, N) \
+ for (ForEachState cell##__state = for_each_from_setup(lst, N); \
+ (cell##__state.l != NIL && \
+ cell##__state.i < cell##__state.l->length) ? \
+ (cell = &cell##__state.l->elements[cell##__state.i], true) : \
+ (cell = NULL, false); \
+ cell##__state.i++)
+
+static inline ForEachState
+for_each_from_setup(const List *lst, int N)
+{
+ ForEachState r = {lst, N};
+
+ Assert(N >= 0);
+ return r;
+}
+
+/*
+ * for_each_cell -
+ * a convenience macro which loops through a list starting from a
+ * specified cell
+ *
+ * The caveats for foreach() apply equally here.
+ */
+#define for_each_cell(cell, lst, initcell) \
+ for (ForEachState cell##__state = for_each_cell_setup(lst, initcell); \
+ (cell##__state.l != NIL && \
+ cell##__state.i < cell##__state.l->length) ? \
+ (cell = &cell##__state.l->elements[cell##__state.i], true) : \
+ (cell = NULL, false); \
+ cell##__state.i++)
+
+static inline ForEachState
+for_each_cell_setup(const List *lst, const ListCell *initcell)
+{
+ ForEachState r = {lst,
+ initcell ? list_cell_number(lst, initcell) : list_length(lst)};
+
+ return r;
+}
+
+/*
+ * forboth -
+ * a convenience macro for advancing through two linked lists
+ * simultaneously. This macro loops through both lists at the same
+ * time, stopping when either list runs out of elements. Depending
+ * on the requirements of the call site, it may also be wise to
+ * assert that the lengths of the two lists are equal. (But, if they
+ * are not, some callers rely on the ending cell values being separately
+ * NULL or non-NULL as defined here; don't try to optimize that.)
+ *
+ * The caveats for foreach() apply equally here.
+ */
+#define forboth(cell1, list1, cell2, list2) \
+ for (ForBothState cell1##__state = {(list1), (list2), 0}; \
+ multi_for_advance_cell(cell1, cell1##__state, l1, i), \
+ multi_for_advance_cell(cell2, cell1##__state, l2, i), \
+ (cell1 != NULL && cell2 != NULL); \
+ cell1##__state.i++)
+
+#define multi_for_advance_cell(cell, state, l, i) \
+ (cell = (state.l != NIL && state.i < state.l->length) ? \
+ &state.l->elements[state.i] : NULL)
+
+/*
+ * for_both_cell -
+ * a convenience macro which loops through two lists starting from the
+ * specified cells of each. This macro loops through both lists at the same
+ * time, stopping when either list runs out of elements. Depending on the
+ * requirements of the call site, it may also be wise to assert that the
+ * lengths of the two lists are equal, and initcell1 and initcell2 are at
+ * the same position in the respective lists.
+ *
+ * The caveats for foreach() apply equally here.
+ */
+#define for_both_cell(cell1, list1, initcell1, cell2, list2, initcell2) \
+ for (ForBothCellState cell1##__state = \
+ for_both_cell_setup(list1, initcell1, list2, initcell2); \
+ multi_for_advance_cell(cell1, cell1##__state, l1, i1), \
+ multi_for_advance_cell(cell2, cell1##__state, l2, i2), \
+ (cell1 != NULL && cell2 != NULL); \
+ cell1##__state.i1++, cell1##__state.i2++)
+
+static inline ForBothCellState
+for_both_cell_setup(const List *list1, const ListCell *initcell1,
+ const List *list2, const ListCell *initcell2)
+{
+ ForBothCellState r = {list1, list2,
+ initcell1 ? list_cell_number(list1, initcell1) : list_length(list1),
+ initcell2 ? list_cell_number(list2, initcell2) : list_length(list2)};
+
+ return r;
+}
+
+/*
+ * forthree -
+ * the same for three lists
+ */
+#define forthree(cell1, list1, cell2, list2, cell3, list3) \
+ for (ForThreeState cell1##__state = {(list1), (list2), (list3), 0}; \
+ multi_for_advance_cell(cell1, cell1##__state, l1, i), \
+ multi_for_advance_cell(cell2, cell1##__state, l2, i), \
+ multi_for_advance_cell(cell3, cell1##__state, l3, i), \
+ (cell1 != NULL && cell2 != NULL && cell3 != NULL); \
+ cell1##__state.i++)
+
+/*
+ * forfour -
+ * the same for four lists
+ */
+#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4) \
+ for (ForFourState cell1##__state = {(list1), (list2), (list3), (list4), 0}; \
+ multi_for_advance_cell(cell1, cell1##__state, l1, i), \
+ multi_for_advance_cell(cell2, cell1##__state, l2, i), \
+ multi_for_advance_cell(cell3, cell1##__state, l3, i), \
+ multi_for_advance_cell(cell4, cell1##__state, l4, i), \
+ (cell1 != NULL && cell2 != NULL && cell3 != NULL && cell4 != NULL); \
+ cell1##__state.i++)
+
+/*
+ * forfive -
+ * the same for five lists
+ */
+#define forfive(cell1, list1, cell2, list2, cell3, list3, cell4, list4, cell5, list5) \
+ for (ForFiveState cell1##__state = {(list1), (list2), (list3), (list4), (list5), 0}; \
+ multi_for_advance_cell(cell1, cell1##__state, l1, i), \
+ multi_for_advance_cell(cell2, cell1##__state, l2, i), \
+ multi_for_advance_cell(cell3, cell1##__state, l3, i), \
+ multi_for_advance_cell(cell4, cell1##__state, l4, i), \
+ multi_for_advance_cell(cell5, cell1##__state, l5, i), \
+ (cell1 != NULL && cell2 != NULL && cell3 != NULL && \
+ cell4 != NULL && cell5 != NULL); \
+ cell1##__state.i++)
+
+/* Functions in src/backend/nodes/list.c */
+
+extern List *list_make1_impl(NodeTag t, ListCell datum1);
+extern List *list_make2_impl(NodeTag t, ListCell datum1, ListCell datum2);
+extern List *list_make3_impl(NodeTag t, ListCell datum1, ListCell datum2,
+ ListCell datum3);
+extern List *list_make4_impl(NodeTag t, ListCell datum1, ListCell datum2,
+ ListCell datum3, ListCell datum4);
+extern List *list_make5_impl(NodeTag t, ListCell datum1, ListCell datum2,
+ ListCell datum3, ListCell datum4,
+ ListCell datum5);
+
+extern pg_nodiscard List *lappend(List *list, void *datum);
+extern pg_nodiscard List *lappend_int(List *list, int datum);
+extern pg_nodiscard List *lappend_oid(List *list, Oid datum);
+extern pg_nodiscard List *lappend_xid(List *list, TransactionId datum);
+
+extern pg_nodiscard List *list_insert_nth(List *list, int pos, void *datum);
+extern pg_nodiscard List *list_insert_nth_int(List *list, int pos, int datum);
+extern pg_nodiscard List *list_insert_nth_oid(List *list, int pos, Oid datum);
+
+extern pg_nodiscard List *lcons(void *datum, List *list);
+extern pg_nodiscard List *lcons_int(int datum, List *list);
+extern pg_nodiscard List *lcons_oid(Oid datum, List *list);
+
+extern pg_nodiscard List *list_concat(List *list1, const List *list2);
+extern pg_nodiscard List *list_concat_copy(const List *list1, const List *list2);
+
+extern pg_nodiscard List *list_truncate(List *list, int new_size);
+
+extern bool list_member(const List *list, const void *datum);
+extern bool list_member_ptr(const List *list, const void *datum);
+extern bool list_member_int(const List *list, int datum);
+extern bool list_member_oid(const List *list, Oid datum);
+extern bool list_member_xid(const List *list, TransactionId datum);
+
+extern pg_nodiscard List *list_delete(List *list, void *datum);
+extern pg_nodiscard List *list_delete_ptr(List *list, void *datum);
+extern pg_nodiscard List *list_delete_int(List *list, int datum);
+extern pg_nodiscard List *list_delete_oid(List *list, Oid datum);
+extern pg_nodiscard List *list_delete_first(List *list);
+extern pg_nodiscard List *list_delete_last(List *list);
+extern pg_nodiscard List *list_delete_first_n(List *list, int n);
+extern pg_nodiscard List *list_delete_nth_cell(List *list, int n);
+extern pg_nodiscard List *list_delete_cell(List *list, ListCell *cell);
+
+extern List *list_union(const List *list1, const List *list2);
+extern List *list_union_ptr(const List *list1, const List *list2);
+extern List *list_union_int(const List *list1, const List *list2);
+extern List *list_union_oid(const List *list1, const List *list2);
+
+extern List *list_intersection(const List *list1, const List *list2);
+extern List *list_intersection_int(const List *list1, const List *list2);
+
+/* currently, there's no need for list_intersection_ptr etc */
+
+extern List *list_difference(const List *list1, const List *list2);
+extern List *list_difference_ptr(const List *list1, const List *list2);
+extern List *list_difference_int(const List *list1, const List *list2);
+extern List *list_difference_oid(const List *list1, const List *list2);
+
+extern pg_nodiscard List *list_append_unique(List *list, void *datum);
+extern pg_nodiscard List *list_append_unique_ptr(List *list, void *datum);
+extern pg_nodiscard List *list_append_unique_int(List *list, int datum);
+extern pg_nodiscard List *list_append_unique_oid(List *list, Oid datum);
+
+extern pg_nodiscard List *list_concat_unique(List *list1, const List *list2);
+extern pg_nodiscard List *list_concat_unique_ptr(List *list1, const List *list2);
+extern pg_nodiscard List *list_concat_unique_int(List *list1, const List *list2);
+extern pg_nodiscard List *list_concat_unique_oid(List *list1, const List *list2);
+
+extern void list_deduplicate_oid(List *list);
+
+extern void list_free(List *list);
+extern void list_free_deep(List *list);
+
+extern pg_nodiscard List *list_copy(const List *oldlist);
+extern pg_nodiscard List *list_copy_head(const List *oldlist, int len);
+extern pg_nodiscard List *list_copy_tail(const List *oldlist, int nskip);
+extern pg_nodiscard List *list_copy_deep(const List *oldlist);
+
+typedef int (*list_sort_comparator) (const ListCell *a, const ListCell *b);
+extern void list_sort(List *list, list_sort_comparator cmp);
+
+extern int list_int_cmp(const ListCell *p1, const ListCell *p2);
+extern int list_oid_cmp(const ListCell *p1, const ListCell *p2);
+
+#endif /* PG_LIST_H */
diff --git a/pgsql/include/server/nodes/plannodes.h b/pgsql/include/server/nodes/plannodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..d64fe6a328ba32dcd902abe81de760dca73822ed
--- /dev/null
+++ b/pgsql/include/server/nodes/plannodes.h
@@ -0,0 +1,1592 @@
+/*-------------------------------------------------------------------------
+ *
+ * plannodes.h
+ * definitions for query plan nodes
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/plannodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PLANNODES_H
+#define PLANNODES_H
+
+#include "access/sdir.h"
+#include "access/stratnum.h"
+#include "common/relpath.h"
+#include "lib/stringinfo.h"
+#include "nodes/bitmapset.h"
+#include "nodes/lockoptions.h"
+#include "nodes/parsenodes.h"
+#include "nodes/primnodes.h"
+
+
+/* ----------------------------------------------------------------
+ * node definitions
+ * ----------------------------------------------------------------
+ */
+
+/* ----------------
+ * PlannedStmt node
+ *
+ * The output of the planner is a Plan tree headed by a PlannedStmt node.
+ * PlannedStmt holds the "one time" information needed by the executor.
+ *
+ * For simplicity in APIs, we also wrap utility statements in PlannedStmt
+ * nodes; in such cases, commandType == CMD_UTILITY, the statement itself
+ * is in the utilityStmt field, and the rest of the struct is mostly dummy.
+ * (We do use canSetTag, stmt_location, stmt_len, and possibly queryId.)
+ *
+ * PlannedStmt, as well as all varieties of Plan, do not support equal(),
+ * not because it's not sensible but because we currently have no need.
+ * ----------------
+ */
+typedef struct PlannedStmt
+{
+ pg_node_attr(no_equal, no_query_jumble)
+
+ NodeTag type;
+
+ CmdType commandType; /* select|insert|update|delete|merge|utility */
+
+ uint64 queryId; /* query identifier (copied from Query) */
+
+ bool hasReturning; /* is it insert|update|delete RETURNING? */
+
+ bool hasModifyingCTE; /* has insert|update|delete in WITH? */
+
+ bool canSetTag; /* do I set the command result tag? */
+
+ bool transientPlan; /* redo plan when TransactionXmin changes? */
+
+ bool dependsOnRole; /* is plan specific to current role? */
+
+ bool parallelModeNeeded; /* parallel mode required to execute? */
+
+ int jitFlags; /* which forms of JIT should be performed */
+
+ struct Plan *planTree; /* tree of Plan nodes */
+
+ List *rtable; /* list of RangeTblEntry nodes */
+
+ List *permInfos; /* list of RTEPermissionInfo nodes for rtable
+ * entries needing one */
+
+ /* rtable indexes of target relations for INSERT/UPDATE/DELETE/MERGE */
+ List *resultRelations; /* integer list of RT indexes, or NIL */
+
+ List *appendRelations; /* list of AppendRelInfo nodes */
+
+ List *subplans; /* Plan trees for SubPlan expressions; note
+ * that some could be NULL */
+
+ Bitmapset *rewindPlanIDs; /* indices of subplans that require REWIND */
+
+ List *rowMarks; /* a list of PlanRowMark's */
+
+ List *relationOids; /* OIDs of relations the plan depends on */
+
+ List *invalItems; /* other dependencies, as PlanInvalItems */
+
+ List *paramExecTypes; /* type OIDs for PARAM_EXEC Params */
+
+ Node *utilityStmt; /* non-null if this is utility stmt */
+
+ /* statement location in source string (copied from Query) */
+ int stmt_location; /* start location, or -1 if unknown */
+ int stmt_len; /* length in bytes; 0 means "rest of string" */
+} PlannedStmt;
+
+/* macro for fetching the Plan associated with a SubPlan node */
+#define exec_subplan_get_plan(plannedstmt, subplan) \
+ ((Plan *) list_nth((plannedstmt)->subplans, (subplan)->plan_id - 1))
+
+
+/* ----------------
+ * Plan node
+ *
+ * All plan nodes "derive" from the Plan structure by having the
+ * Plan structure as the first field. This ensures that everything works
+ * when nodes are cast to Plan's. (node pointers are frequently cast to Plan*
+ * when passed around generically in the executor)
+ *
+ * We never actually instantiate any Plan nodes; this is just the common
+ * abstract superclass for all Plan-type nodes.
+ * ----------------
+ */
+typedef struct Plan
+{
+ pg_node_attr(abstract, no_equal, no_query_jumble)
+
+ NodeTag type;
+
+ /*
+ * estimated execution costs for plan (see costsize.c for more info)
+ */
+ Cost startup_cost; /* cost expended before fetching any tuples */
+ Cost total_cost; /* total cost (assuming all tuples fetched) */
+
+ /*
+ * planner's estimate of result size of this plan step
+ */
+ Cardinality plan_rows; /* number of rows plan is expected to emit */
+ int plan_width; /* average row width in bytes */
+
+ /*
+ * information needed for parallel query
+ */
+ bool parallel_aware; /* engage parallel-aware logic? */
+ bool parallel_safe; /* OK to use as part of parallel plan? */
+
+ /*
+ * information needed for asynchronous execution
+ */
+ bool async_capable; /* engage asynchronous-capable logic? */
+
+ /*
+ * Common structural data for all Plan types.
+ */
+ int plan_node_id; /* unique across entire final plan tree */
+ List *targetlist; /* target list to be computed at this node */
+ List *qual; /* implicitly-ANDed qual conditions */
+ struct Plan *lefttree; /* input plan tree(s) */
+ struct Plan *righttree;
+ List *initPlan; /* Init Plan nodes (un-correlated expr
+ * subselects) */
+
+ /*
+ * Information for management of parameter-change-driven rescanning
+ *
+ * extParam includes the paramIDs of all external PARAM_EXEC params
+ * affecting this plan node or its children. setParam params from the
+ * node's initPlans are not included, but their extParams are.
+ *
+ * allParam includes all the extParam paramIDs, plus the IDs of local
+ * params that affect the node (i.e., the setParams of its initplans).
+ * These are _all_ the PARAM_EXEC params that affect this node.
+ */
+ Bitmapset *extParam;
+ Bitmapset *allParam;
+} Plan;
+
+/* ----------------
+ * these are defined to avoid confusion problems with "left"
+ * and "right" and "inner" and "outer". The convention is that
+ * the "left" plan is the "outer" plan and the "right" plan is
+ * the inner plan, but these make the code more readable.
+ * ----------------
+ */
+#define innerPlan(node) (((Plan *)(node))->righttree)
+#define outerPlan(node) (((Plan *)(node))->lefttree)
+
+
+/* ----------------
+ * Result node -
+ * If no outer plan, evaluate a variable-free targetlist.
+ * If outer plan, return tuples from outer plan (after a level of
+ * projection as shown by targetlist).
+ *
+ * If resconstantqual isn't NULL, it represents a one-time qualification
+ * test (i.e., one that doesn't depend on any variables from the outer plan,
+ * so needs to be evaluated only once).
+ * ----------------
+ */
+typedef struct Result
+{
+ Plan plan;
+ Node *resconstantqual;
+} Result;
+
+/* ----------------
+ * ProjectSet node -
+ * Apply a projection that includes set-returning functions to the
+ * output tuples of the outer plan.
+ * ----------------
+ */
+typedef struct ProjectSet
+{
+ Plan plan;
+} ProjectSet;
+
+/* ----------------
+ * ModifyTable node -
+ * Apply rows produced by outer plan to result table(s),
+ * by inserting, updating, or deleting.
+ *
+ * If the originally named target table is a partitioned table or inheritance
+ * tree, both nominalRelation and rootRelation contain the RT index of the
+ * partition root or appendrel RTE, which is not otherwise mentioned in the
+ * plan. Otherwise rootRelation is zero. However, nominalRelation will
+ * always be set, as it's the rel that EXPLAIN should claim is the
+ * INSERT/UPDATE/DELETE/MERGE target.
+ *
+ * Note that rowMarks and epqParam are presumed to be valid for all the
+ * table(s); they can't contain any info that varies across tables.
+ * ----------------
+ */
+typedef struct ModifyTable
+{
+ Plan plan;
+ CmdType operation; /* INSERT, UPDATE, DELETE, or MERGE */
+ bool canSetTag; /* do we set the command tag/es_processed? */
+ Index nominalRelation; /* Parent RT index for use of EXPLAIN */
+ Index rootRelation; /* Root RT index, if partitioned/inherited */
+ bool partColsUpdated; /* some part key in hierarchy updated? */
+ List *resultRelations; /* integer list of RT indexes */
+ List *updateColnosLists; /* per-target-table update_colnos lists */
+ List *withCheckOptionLists; /* per-target-table WCO lists */
+ List *returningLists; /* per-target-table RETURNING tlists */
+ List *fdwPrivLists; /* per-target-table FDW private data lists */
+ Bitmapset *fdwDirectModifyPlans; /* indices of FDW DM plans */
+ List *rowMarks; /* PlanRowMarks (non-locking only) */
+ int epqParam; /* ID of Param for EvalPlanQual re-eval */
+ OnConflictAction onConflictAction; /* ON CONFLICT action */
+ List *arbiterIndexes; /* List of ON CONFLICT arbiter index OIDs */
+ List *onConflictSet; /* INSERT ON CONFLICT DO UPDATE targetlist */
+ List *onConflictCols; /* target column numbers for onConflictSet */
+ Node *onConflictWhere; /* WHERE for ON CONFLICT UPDATE */
+ Index exclRelRTI; /* RTI of the EXCLUDED pseudo relation */
+ List *exclRelTlist; /* tlist of the EXCLUDED pseudo relation */
+ List *mergeActionLists; /* per-target-table lists of actions for
+ * MERGE */
+} ModifyTable;
+
+struct PartitionPruneInfo; /* forward reference to struct below */
+
+/* ----------------
+ * Append node -
+ * Generate the concatenation of the results of sub-plans.
+ * ----------------
+ */
+typedef struct Append
+{
+ Plan plan;
+ Bitmapset *apprelids; /* RTIs of appendrel(s) formed by this node */
+ List *appendplans;
+ int nasyncplans; /* # of asynchronous plans */
+
+ /*
+ * All 'appendplans' preceding this index are non-partial plans. All
+ * 'appendplans' from this index onwards are partial plans.
+ */
+ int first_partial_plan;
+
+ /* Info for run-time subplan pruning; NULL if we're not doing that */
+ struct PartitionPruneInfo *part_prune_info;
+} Append;
+
+/* ----------------
+ * MergeAppend node -
+ * Merge the results of pre-sorted sub-plans to preserve the ordering.
+ * ----------------
+ */
+typedef struct MergeAppend
+{
+ Plan plan;
+
+ /* RTIs of appendrel(s) formed by this node */
+ Bitmapset *apprelids;
+
+ List *mergeplans;
+
+ /* these fields are just like the sort-key info in struct Sort: */
+
+ /* number of sort-key columns */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *sortColIdx pg_node_attr(array_size(numCols));
+
+ /* OIDs of operators to sort them by */
+ Oid *sortOperators pg_node_attr(array_size(numCols));
+
+ /* OIDs of collations */
+ Oid *collations pg_node_attr(array_size(numCols));
+
+ /* NULLS FIRST/LAST directions */
+ bool *nullsFirst pg_node_attr(array_size(numCols));
+
+ /* Info for run-time subplan pruning; NULL if we're not doing that */
+ struct PartitionPruneInfo *part_prune_info;
+} MergeAppend;
+
+/* ----------------
+ * RecursiveUnion node -
+ * Generate a recursive union of two subplans.
+ *
+ * The "outer" subplan is always the non-recursive term, and the "inner"
+ * subplan is the recursive term.
+ * ----------------
+ */
+typedef struct RecursiveUnion
+{
+ Plan plan;
+
+ /* ID of Param representing work table */
+ int wtParam;
+
+ /* Remaining fields are zero/null in UNION ALL case */
+
+ /* number of columns to check for duplicate-ness */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *dupColIdx pg_node_attr(array_size(numCols));
+
+ /* equality operators to compare with */
+ Oid *dupOperators pg_node_attr(array_size(numCols));
+ Oid *dupCollations pg_node_attr(array_size(numCols));
+
+ /* estimated number of groups in input */
+ long numGroups;
+} RecursiveUnion;
+
+/* ----------------
+ * BitmapAnd node -
+ * Generate the intersection of the results of sub-plans.
+ *
+ * The subplans must be of types that yield tuple bitmaps. The targetlist
+ * and qual fields of the plan are unused and are always NIL.
+ * ----------------
+ */
+typedef struct BitmapAnd
+{
+ Plan plan;
+ List *bitmapplans;
+} BitmapAnd;
+
+/* ----------------
+ * BitmapOr node -
+ * Generate the union of the results of sub-plans.
+ *
+ * The subplans must be of types that yield tuple bitmaps. The targetlist
+ * and qual fields of the plan are unused and are always NIL.
+ * ----------------
+ */
+typedef struct BitmapOr
+{
+ Plan plan;
+ bool isshared;
+ List *bitmapplans;
+} BitmapOr;
+
+/*
+ * ==========
+ * Scan nodes
+ *
+ * Scan is an abstract type that all relation scan plan types inherit from.
+ * ==========
+ */
+typedef struct Scan
+{
+ pg_node_attr(abstract)
+
+ Plan plan;
+ Index scanrelid; /* relid is index into the range table */
+} Scan;
+
+/* ----------------
+ * sequential scan node
+ * ----------------
+ */
+typedef struct SeqScan
+{
+ Scan scan;
+} SeqScan;
+
+/* ----------------
+ * table sample scan node
+ * ----------------
+ */
+typedef struct SampleScan
+{
+ Scan scan;
+ /* use struct pointer to avoid including parsenodes.h here */
+ struct TableSampleClause *tablesample;
+} SampleScan;
+
+/* ----------------
+ * index scan node
+ *
+ * indexqualorig is an implicitly-ANDed list of index qual expressions, each
+ * in the same form it appeared in the query WHERE condition. Each should
+ * be of the form (indexkey OP comparisonval) or (comparisonval OP indexkey).
+ * The indexkey is a Var or expression referencing column(s) of the index's
+ * base table. The comparisonval might be any expression, but it won't use
+ * any columns of the base table. The expressions are ordered by index
+ * column position (but items referencing the same index column can appear
+ * in any order). indexqualorig is used at runtime only if we have to recheck
+ * a lossy indexqual.
+ *
+ * indexqual has the same form, but the expressions have been commuted if
+ * necessary to put the indexkeys on the left, and the indexkeys are replaced
+ * by Var nodes identifying the index columns (their varno is INDEX_VAR and
+ * their varattno is the index column number).
+ *
+ * indexorderbyorig is similarly the original form of any ORDER BY expressions
+ * that are being implemented by the index, while indexorderby is modified to
+ * have index column Vars on the left-hand side. Here, multiple expressions
+ * must appear in exactly the ORDER BY order, and this is not necessarily the
+ * index column order. Only the expressions are provided, not the auxiliary
+ * sort-order information from the ORDER BY SortGroupClauses; it's assumed
+ * that the sort ordering is fully determinable from the top-level operators.
+ * indexorderbyorig is used at runtime to recheck the ordering, if the index
+ * cannot calculate an accurate ordering. It is also needed for EXPLAIN.
+ *
+ * indexorderbyops is a list of the OIDs of the operators used to sort the
+ * ORDER BY expressions. This is used together with indexorderbyorig to
+ * recheck ordering at run time. (Note that indexorderby, indexorderbyorig,
+ * and indexorderbyops are used for amcanorderbyop cases, not amcanorder.)
+ *
+ * indexorderdir specifies the scan ordering, for indexscans on amcanorder
+ * indexes (for other indexes it should be "don't care").
+ * ----------------
+ */
+typedef struct IndexScan
+{
+ Scan scan;
+ Oid indexid; /* OID of index to scan */
+ List *indexqual; /* list of index quals (usually OpExprs) */
+ List *indexqualorig; /* the same in original form */
+ List *indexorderby; /* list of index ORDER BY exprs */
+ List *indexorderbyorig; /* the same in original form */
+ List *indexorderbyops; /* OIDs of sort ops for ORDER BY exprs */
+ ScanDirection indexorderdir; /* forward or backward or don't care */
+} IndexScan;
+
+/* ----------------
+ * index-only scan node
+ *
+ * IndexOnlyScan is very similar to IndexScan, but it specifies an
+ * index-only scan, in which the data comes from the index not the heap.
+ * Because of this, *all* Vars in the plan node's targetlist, qual, and
+ * index expressions reference index columns and have varno = INDEX_VAR.
+ *
+ * We could almost use indexqual directly against the index's output tuple
+ * when rechecking lossy index operators, but that won't work for quals on
+ * index columns that are not retrievable. Hence, recheckqual is needed
+ * for rechecks: it expresses the same condition as indexqual, but using
+ * only index columns that are retrievable. (We will not generate an
+ * index-only scan if this is not possible. An example is that if an
+ * index has table column "x" in a retrievable index column "ind1", plus
+ * an expression f(x) in a non-retrievable column "ind2", an indexable
+ * query on f(x) will use "ind2" in indexqual and f(ind1) in recheckqual.
+ * Without the "ind1" column, an index-only scan would be disallowed.)
+ *
+ * We don't currently need a recheckable equivalent of indexorderby,
+ * because we don't support lossy operators in index ORDER BY.
+ *
+ * To help EXPLAIN interpret the index Vars for display, we provide
+ * indextlist, which represents the contents of the index as a targetlist
+ * with one TLE per index column. Vars appearing in this list reference
+ * the base table, and this is the only field in the plan node that may
+ * contain such Vars. Also, for the convenience of setrefs.c, TLEs in
+ * indextlist are marked as resjunk if they correspond to columns that
+ * the index AM cannot reconstruct.
+ * ----------------
+ */
+typedef struct IndexOnlyScan
+{
+ Scan scan;
+ Oid indexid; /* OID of index to scan */
+ List *indexqual; /* list of index quals (usually OpExprs) */
+ List *recheckqual; /* index quals in recheckable form */
+ List *indexorderby; /* list of index ORDER BY exprs */
+ List *indextlist; /* TargetEntry list describing index's cols */
+ ScanDirection indexorderdir; /* forward or backward or don't care */
+} IndexOnlyScan;
+
+/* ----------------
+ * bitmap index scan node
+ *
+ * BitmapIndexScan delivers a bitmap of potential tuple locations;
+ * it does not access the heap itself. The bitmap is used by an
+ * ancestor BitmapHeapScan node, possibly after passing through
+ * intermediate BitmapAnd and/or BitmapOr nodes to combine it with
+ * the results of other BitmapIndexScans.
+ *
+ * The fields have the same meanings as for IndexScan, except we don't
+ * store a direction flag because direction is uninteresting.
+ *
+ * In a BitmapIndexScan plan node, the targetlist and qual fields are
+ * not used and are always NIL. The indexqualorig field is unused at
+ * run time too, but is saved for the benefit of EXPLAIN.
+ * ----------------
+ */
+typedef struct BitmapIndexScan
+{
+ Scan scan;
+ Oid indexid; /* OID of index to scan */
+ bool isshared; /* Create shared bitmap if set */
+ List *indexqual; /* list of index quals (OpExprs) */
+ List *indexqualorig; /* the same in original form */
+} BitmapIndexScan;
+
+/* ----------------
+ * bitmap sequential scan node
+ *
+ * This needs a copy of the qual conditions being used by the input index
+ * scans because there are various cases where we need to recheck the quals;
+ * for example, when the bitmap is lossy about the specific rows on a page
+ * that meet the index condition.
+ * ----------------
+ */
+typedef struct BitmapHeapScan
+{
+ Scan scan;
+ List *bitmapqualorig; /* index quals, in standard expr form */
+} BitmapHeapScan;
+
+/* ----------------
+ * tid scan node
+ *
+ * tidquals is an implicitly OR'ed list of qual expressions of the form
+ * "CTID = pseudoconstant", or "CTID = ANY(pseudoconstant_array)",
+ * or a CurrentOfExpr for the relation.
+ * ----------------
+ */
+typedef struct TidScan
+{
+ Scan scan;
+ List *tidquals; /* qual(s) involving CTID = something */
+} TidScan;
+
+/* ----------------
+ * tid range scan node
+ *
+ * tidrangequals is an implicitly AND'ed list of qual expressions of the form
+ * "CTID relop pseudoconstant", where relop is one of >,>=,<,<=.
+ * ----------------
+ */
+typedef struct TidRangeScan
+{
+ Scan scan;
+ List *tidrangequals; /* qual(s) involving CTID op something */
+} TidRangeScan;
+
+/* ----------------
+ * subquery scan node
+ *
+ * SubqueryScan is for scanning the output of a sub-query in the range table.
+ * We often need an extra plan node above the sub-query's plan to perform
+ * expression evaluations (which we can't push into the sub-query without
+ * risking changing its semantics). Although we are not scanning a physical
+ * relation, we make this a descendant of Scan anyway for code-sharing
+ * purposes.
+ *
+ * SubqueryScanStatus caches the trivial_subqueryscan property of the node.
+ * SUBQUERY_SCAN_UNKNOWN means not yet determined. This is only used during
+ * planning.
+ *
+ * Note: we store the sub-plan in the type-specific subplan field, not in
+ * the generic lefttree field as you might expect. This is because we do
+ * not want plan-tree-traversal routines to recurse into the subplan without
+ * knowing that they are changing Query contexts.
+ * ----------------
+ */
+typedef enum SubqueryScanStatus
+{
+ SUBQUERY_SCAN_UNKNOWN,
+ SUBQUERY_SCAN_TRIVIAL,
+ SUBQUERY_SCAN_NONTRIVIAL
+} SubqueryScanStatus;
+
+typedef struct SubqueryScan
+{
+ Scan scan;
+ Plan *subplan;
+ SubqueryScanStatus scanstatus;
+} SubqueryScan;
+
+/* ----------------
+ * FunctionScan node
+ * ----------------
+ */
+typedef struct FunctionScan
+{
+ Scan scan;
+ List *functions; /* list of RangeTblFunction nodes */
+ bool funcordinality; /* WITH ORDINALITY */
+} FunctionScan;
+
+/* ----------------
+ * ValuesScan node
+ * ----------------
+ */
+typedef struct ValuesScan
+{
+ Scan scan;
+ List *values_lists; /* list of expression lists */
+} ValuesScan;
+
+/* ----------------
+ * TableFunc scan node
+ * ----------------
+ */
+typedef struct TableFuncScan
+{
+ Scan scan;
+ TableFunc *tablefunc; /* table function node */
+} TableFuncScan;
+
+/* ----------------
+ * CteScan node
+ * ----------------
+ */
+typedef struct CteScan
+{
+ Scan scan;
+ int ctePlanId; /* ID of init SubPlan for CTE */
+ int cteParam; /* ID of Param representing CTE output */
+} CteScan;
+
+/* ----------------
+ * NamedTuplestoreScan node
+ * ----------------
+ */
+typedef struct NamedTuplestoreScan
+{
+ Scan scan;
+ char *enrname; /* Name given to Ephemeral Named Relation */
+} NamedTuplestoreScan;
+
+/* ----------------
+ * WorkTableScan node
+ * ----------------
+ */
+typedef struct WorkTableScan
+{
+ Scan scan;
+ int wtParam; /* ID of Param representing work table */
+} WorkTableScan;
+
+/* ----------------
+ * ForeignScan node
+ *
+ * fdw_exprs and fdw_private are both under the control of the foreign-data
+ * wrapper, but fdw_exprs is presumed to contain expression trees and will
+ * be post-processed accordingly by the planner; fdw_private won't be.
+ * Note that everything in both lists must be copiable by copyObject().
+ * One way to store an arbitrary blob of bytes is to represent it as a bytea
+ * Const. Usually, though, you'll be better off choosing a representation
+ * that can be dumped usefully by nodeToString().
+ *
+ * fdw_scan_tlist is a targetlist describing the contents of the scan tuple
+ * returned by the FDW; it can be NIL if the scan tuple matches the declared
+ * rowtype of the foreign table, which is the normal case for a simple foreign
+ * table scan. (If the plan node represents a foreign join, fdw_scan_tlist
+ * is required since there is no rowtype available from the system catalogs.)
+ * When fdw_scan_tlist is provided, Vars in the node's tlist and quals must
+ * have varno INDEX_VAR, and their varattnos correspond to resnos in the
+ * fdw_scan_tlist (which are also column numbers in the actual scan tuple).
+ * fdw_scan_tlist is never actually executed; it just holds expression trees
+ * describing what is in the scan tuple's columns.
+ *
+ * fdw_recheck_quals should contain any quals which the core system passed to
+ * the FDW but which were not added to scan.plan.qual; that is, it should
+ * contain the quals being checked remotely. This is needed for correct
+ * behavior during EvalPlanQual rechecks.
+ *
+ * When the plan node represents a foreign join, scan.scanrelid is zero and
+ * fs_relids must be consulted to identify the join relation. (fs_relids
+ * is valid for simple scans as well, but will always match scan.scanrelid.)
+ * fs_relids includes outer joins; fs_base_relids does not.
+ *
+ * If the FDW's PlanDirectModify() callback decides to repurpose a ForeignScan
+ * node to perform the UPDATE or DELETE operation directly in the remote
+ * server, it sets 'operation' and 'resultRelation' to identify the operation
+ * type and target relation. Note that these fields are only set if the
+ * modification is performed *fully* remotely; otherwise, the modification is
+ * driven by a local ModifyTable node and 'operation' is left to CMD_SELECT.
+ * ----------------
+ */
+typedef struct ForeignScan
+{
+ Scan scan;
+ CmdType operation; /* SELECT/INSERT/UPDATE/DELETE */
+ Index resultRelation; /* direct modification target's RT index */
+ Oid checkAsUser; /* user to perform the scan as; 0 means to
+ * check as current user */
+ Oid fs_server; /* OID of foreign server */
+ List *fdw_exprs; /* expressions that FDW may evaluate */
+ List *fdw_private; /* private data for FDW */
+ List *fdw_scan_tlist; /* optional tlist describing scan tuple */
+ List *fdw_recheck_quals; /* original quals not in scan.plan.qual */
+ Bitmapset *fs_relids; /* base+OJ RTIs generated by this scan */
+ Bitmapset *fs_base_relids; /* base RTIs generated by this scan */
+ bool fsSystemCol; /* true if any "system column" is needed */
+} ForeignScan;
+
+/* ----------------
+ * CustomScan node
+ *
+ * The comments for ForeignScan's fdw_exprs, fdw_private, fdw_scan_tlist,
+ * and fs_relids fields apply equally to CustomScan's custom_exprs,
+ * custom_private, custom_scan_tlist, and custom_relids fields. The
+ * convention of setting scan.scanrelid to zero for joins applies as well.
+ *
+ * Note that since Plan trees can be copied, custom scan providers *must*
+ * fit all plan data they need into those fields; embedding CustomScan in
+ * a larger struct will not work.
+ * ----------------
+ */
+struct CustomScanMethods;
+
+typedef struct CustomScan
+{
+ Scan scan;
+ uint32 flags; /* mask of CUSTOMPATH_* flags, see
+ * nodes/extensible.h */
+ List *custom_plans; /* list of Plan nodes, if any */
+ List *custom_exprs; /* expressions that custom code may evaluate */
+ List *custom_private; /* private data for custom code */
+ List *custom_scan_tlist; /* optional tlist describing scan tuple */
+ Bitmapset *custom_relids; /* RTIs generated by this scan */
+
+ /*
+ * NOTE: The method field of CustomScan is required to be a pointer to a
+ * static table of callback functions. So we don't copy the table itself,
+ * just reference the original one.
+ */
+ const struct CustomScanMethods *methods;
+} CustomScan;
+
+/*
+ * ==========
+ * Join nodes
+ * ==========
+ */
+
+/* ----------------
+ * Join node
+ *
+ * jointype: rule for joining tuples from left and right subtrees
+ * inner_unique each outer tuple can match to no more than one inner tuple
+ * joinqual: qual conditions that came from JOIN/ON or JOIN/USING
+ * (plan.qual contains conditions that came from WHERE)
+ *
+ * When jointype is INNER, joinqual and plan.qual are semantically
+ * interchangeable. For OUTER jointypes, the two are *not* interchangeable;
+ * only joinqual is used to determine whether a match has been found for
+ * the purpose of deciding whether to generate null-extended tuples.
+ * (But plan.qual is still applied before actually returning a tuple.)
+ * For an outer join, only joinquals are allowed to be used as the merge
+ * or hash condition of a merge or hash join.
+ *
+ * inner_unique is set if the joinquals are such that no more than one inner
+ * tuple could match any given outer tuple. This allows the executor to
+ * skip searching for additional matches. (This must be provable from just
+ * the joinquals, ignoring plan.qual, due to where the executor tests it.)
+ * ----------------
+ */
+typedef struct Join
+{
+ pg_node_attr(abstract)
+
+ Plan plan;
+ JoinType jointype;
+ bool inner_unique;
+ List *joinqual; /* JOIN quals (in addition to plan.qual) */
+} Join;
+
+/* ----------------
+ * nest loop join node
+ *
+ * The nestParams list identifies any executor Params that must be passed
+ * into execution of the inner subplan carrying values from the current row
+ * of the outer subplan. Currently we restrict these values to be simple
+ * Vars, but perhaps someday that'd be worth relaxing. (Note: during plan
+ * creation, the paramval can actually be a PlaceHolderVar expression; but it
+ * must be a Var with varno OUTER_VAR by the time it gets to the executor.)
+ * ----------------
+ */
+typedef struct NestLoop
+{
+ Join join;
+ List *nestParams; /* list of NestLoopParam nodes */
+} NestLoop;
+
+typedef struct NestLoopParam
+{
+ pg_node_attr(no_equal, no_query_jumble)
+
+ NodeTag type;
+ int paramno; /* number of the PARAM_EXEC Param to set */
+ Var *paramval; /* outer-relation Var to assign to Param */
+} NestLoopParam;
+
+/* ----------------
+ * merge join node
+ *
+ * The expected ordering of each mergeable column is described by a btree
+ * opfamily OID, a collation OID, a direction (BTLessStrategyNumber or
+ * BTGreaterStrategyNumber) and a nulls-first flag. Note that the two sides
+ * of each mergeclause may be of different datatypes, but they are ordered the
+ * same way according to the common opfamily and collation. The operator in
+ * each mergeclause must be an equality operator of the indicated opfamily.
+ * ----------------
+ */
+typedef struct MergeJoin
+{
+ Join join;
+
+ /* Can we skip mark/restore calls? */
+ bool skip_mark_restore;
+
+ /* mergeclauses as expression trees */
+ List *mergeclauses;
+
+ /* these are arrays, but have the same length as the mergeclauses list: */
+
+ /* per-clause OIDs of btree opfamilies */
+ Oid *mergeFamilies pg_node_attr(array_size(mergeclauses));
+
+ /* per-clause OIDs of collations */
+ Oid *mergeCollations pg_node_attr(array_size(mergeclauses));
+
+ /* per-clause ordering (ASC or DESC) */
+ int *mergeStrategies pg_node_attr(array_size(mergeclauses));
+
+ /* per-clause nulls ordering */
+ bool *mergeNullsFirst pg_node_attr(array_size(mergeclauses));
+} MergeJoin;
+
+/* ----------------
+ * hash join node
+ * ----------------
+ */
+typedef struct HashJoin
+{
+ Join join;
+ List *hashclauses;
+ List *hashoperators;
+ List *hashcollations;
+
+ /*
+ * List of expressions to be hashed for tuples from the outer plan, to
+ * perform lookups in the hashtable over the inner plan.
+ */
+ List *hashkeys;
+} HashJoin;
+
+/* ----------------
+ * materialization node
+ * ----------------
+ */
+typedef struct Material
+{
+ Plan plan;
+} Material;
+
+/* ----------------
+ * memoize node
+ * ----------------
+ */
+typedef struct Memoize
+{
+ Plan plan;
+
+ /* size of the two arrays below */
+ int numKeys;
+
+ /* hash operators for each key */
+ Oid *hashOperators pg_node_attr(array_size(numKeys));
+
+ /* collations for each key */
+ Oid *collations pg_node_attr(array_size(numKeys));
+
+ /* cache keys in the form of exprs containing parameters */
+ List *param_exprs;
+
+ /*
+ * true if the cache entry should be marked as complete after we store the
+ * first tuple in it.
+ */
+ bool singlerow;
+
+ /*
+ * true when cache key should be compared bit by bit, false when using
+ * hash equality ops
+ */
+ bool binary_mode;
+
+ /*
+ * The maximum number of entries that the planner expects will fit in the
+ * cache, or 0 if unknown
+ */
+ uint32 est_entries;
+
+ /* paramids from param_exprs */
+ Bitmapset *keyparamids;
+} Memoize;
+
+/* ----------------
+ * sort node
+ * ----------------
+ */
+typedef struct Sort
+{
+ Plan plan;
+
+ /* number of sort-key columns */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *sortColIdx pg_node_attr(array_size(numCols));
+
+ /* OIDs of operators to sort them by */
+ Oid *sortOperators pg_node_attr(array_size(numCols));
+
+ /* OIDs of collations */
+ Oid *collations pg_node_attr(array_size(numCols));
+
+ /* NULLS FIRST/LAST directions */
+ bool *nullsFirst pg_node_attr(array_size(numCols));
+} Sort;
+
+/* ----------------
+ * incremental sort node
+ * ----------------
+ */
+typedef struct IncrementalSort
+{
+ Sort sort;
+ int nPresortedCols; /* number of presorted columns */
+} IncrementalSort;
+
+/* ---------------
+ * group node -
+ * Used for queries with GROUP BY (but no aggregates) specified.
+ * The input must be presorted according to the grouping columns.
+ * ---------------
+ */
+typedef struct Group
+{
+ Plan plan;
+
+ /* number of grouping columns */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *grpColIdx pg_node_attr(array_size(numCols));
+
+ /* equality operators to compare with */
+ Oid *grpOperators pg_node_attr(array_size(numCols));
+ Oid *grpCollations pg_node_attr(array_size(numCols));
+} Group;
+
+/* ---------------
+ * aggregate node
+ *
+ * An Agg node implements plain or grouped aggregation. For grouped
+ * aggregation, we can work with presorted input or unsorted input;
+ * the latter strategy uses an internal hashtable.
+ *
+ * Notice the lack of any direct info about the aggregate functions to be
+ * computed. They are found by scanning the node's tlist and quals during
+ * executor startup. (It is possible that there are no aggregate functions;
+ * this could happen if they get optimized away by constant-folding, or if
+ * we are using the Agg node to implement hash-based grouping.)
+ * ---------------
+ */
+typedef struct Agg
+{
+ Plan plan;
+
+ /* basic strategy, see nodes.h */
+ AggStrategy aggstrategy;
+
+ /* agg-splitting mode, see nodes.h */
+ AggSplit aggsplit;
+
+ /* number of grouping columns */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *grpColIdx pg_node_attr(array_size(numCols));
+
+ /* equality operators to compare with */
+ Oid *grpOperators pg_node_attr(array_size(numCols));
+ Oid *grpCollations pg_node_attr(array_size(numCols));
+
+ /* estimated number of groups in input */
+ long numGroups;
+
+ /* for pass-by-ref transition data */
+ uint64 transitionSpace;
+
+ /* IDs of Params used in Aggref inputs */
+ Bitmapset *aggParams;
+
+ /* Note: planner provides numGroups & aggParams only in HASHED/MIXED case */
+
+ /* grouping sets to use */
+ List *groupingSets;
+
+ /* chained Agg/Sort nodes */
+ List *chain;
+} Agg;
+
+/* ----------------
+ * window aggregate node
+ * ----------------
+ */
+typedef struct WindowAgg
+{
+ Plan plan;
+
+ /* ID referenced by window functions */
+ Index winref;
+
+ /* number of columns in partition clause */
+ int partNumCols;
+
+ /* their indexes in the target list */
+ AttrNumber *partColIdx pg_node_attr(array_size(partNumCols));
+
+ /* equality operators for partition columns */
+ Oid *partOperators pg_node_attr(array_size(partNumCols));
+
+ /* collations for partition columns */
+ Oid *partCollations pg_node_attr(array_size(partNumCols));
+
+ /* number of columns in ordering clause */
+ int ordNumCols;
+
+ /* their indexes in the target list */
+ AttrNumber *ordColIdx pg_node_attr(array_size(ordNumCols));
+
+ /* equality operators for ordering columns */
+ Oid *ordOperators pg_node_attr(array_size(ordNumCols));
+
+ /* collations for ordering columns */
+ Oid *ordCollations pg_node_attr(array_size(ordNumCols));
+
+ /* frame_clause options, see WindowDef */
+ int frameOptions;
+
+ /* expression for starting bound, if any */
+ Node *startOffset;
+
+ /* expression for ending bound, if any */
+ Node *endOffset;
+
+ /* qual to help short-circuit execution */
+ List *runCondition;
+
+ /* runCondition for display in EXPLAIN */
+ List *runConditionOrig;
+
+ /* these fields are used with RANGE offset PRECEDING/FOLLOWING: */
+
+ /* in_range function for startOffset */
+ Oid startInRangeFunc;
+
+ /* in_range function for endOffset */
+ Oid endInRangeFunc;
+
+ /* collation for in_range tests */
+ Oid inRangeColl;
+
+ /* use ASC sort order for in_range tests? */
+ bool inRangeAsc;
+
+ /* nulls sort first for in_range tests? */
+ bool inRangeNullsFirst;
+
+ /*
+ * false for all apart from the WindowAgg that's closest to the root of
+ * the plan
+ */
+ bool topWindow;
+} WindowAgg;
+
+/* ----------------
+ * unique node
+ * ----------------
+ */
+typedef struct Unique
+{
+ Plan plan;
+
+ /* number of columns to check for uniqueness */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *uniqColIdx pg_node_attr(array_size(numCols));
+
+ /* equality operators to compare with */
+ Oid *uniqOperators pg_node_attr(array_size(numCols));
+
+ /* collations for equality comparisons */
+ Oid *uniqCollations pg_node_attr(array_size(numCols));
+} Unique;
+
+/* ------------
+ * gather node
+ *
+ * Note: rescan_param is the ID of a PARAM_EXEC parameter slot. That slot
+ * will never actually contain a value, but the Gather node must flag it as
+ * having changed whenever it is rescanned. The child parallel-aware scan
+ * nodes are marked as depending on that parameter, so that the rescan
+ * machinery is aware that their output is likely to change across rescans.
+ * In some cases we don't need a rescan Param, so rescan_param is set to -1.
+ * ------------
+ */
+typedef struct Gather
+{
+ Plan plan;
+ int num_workers; /* planned number of worker processes */
+ int rescan_param; /* ID of Param that signals a rescan, or -1 */
+ bool single_copy; /* don't execute plan more than once */
+ bool invisible; /* suppress EXPLAIN display (for testing)? */
+ Bitmapset *initParam; /* param id's of initplans which are referred
+ * at gather or one of it's child node */
+} Gather;
+
+/* ------------
+ * gather merge node
+ * ------------
+ */
+typedef struct GatherMerge
+{
+ Plan plan;
+
+ /* planned number of worker processes */
+ int num_workers;
+
+ /* ID of Param that signals a rescan, or -1 */
+ int rescan_param;
+
+ /* remaining fields are just like the sort-key info in struct Sort */
+
+ /* number of sort-key columns */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *sortColIdx pg_node_attr(array_size(numCols));
+
+ /* OIDs of operators to sort them by */
+ Oid *sortOperators pg_node_attr(array_size(numCols));
+
+ /* OIDs of collations */
+ Oid *collations pg_node_attr(array_size(numCols));
+
+ /* NULLS FIRST/LAST directions */
+ bool *nullsFirst pg_node_attr(array_size(numCols));
+
+ /*
+ * param id's of initplans which are referred at gather merge or one of
+ * it's child node
+ */
+ Bitmapset *initParam;
+} GatherMerge;
+
+/* ----------------
+ * hash build node
+ *
+ * If the executor is supposed to try to apply skew join optimization, then
+ * skewTable/skewColumn/skewInherit identify the outer relation's join key
+ * column, from which the relevant MCV statistics can be fetched.
+ * ----------------
+ */
+typedef struct Hash
+{
+ Plan plan;
+
+ /*
+ * List of expressions to be hashed for tuples from Hash's outer plan,
+ * needed to put them into the hashtable.
+ */
+ List *hashkeys; /* hash keys for the hashjoin condition */
+ Oid skewTable; /* outer join key's table OID, or InvalidOid */
+ AttrNumber skewColumn; /* outer join key's column #, or zero */
+ bool skewInherit; /* is outer join rel an inheritance tree? */
+ /* all other info is in the parent HashJoin node */
+ Cardinality rows_total; /* estimate total rows if parallel_aware */
+} Hash;
+
+/* ----------------
+ * setop node
+ * ----------------
+ */
+typedef struct SetOp
+{
+ Plan plan;
+
+ /* what to do, see nodes.h */
+ SetOpCmd cmd;
+
+ /* how to do it, see nodes.h */
+ SetOpStrategy strategy;
+
+ /* number of columns to check for duplicate-ness */
+ int numCols;
+
+ /* their indexes in the target list */
+ AttrNumber *dupColIdx pg_node_attr(array_size(numCols));
+
+ /* equality operators to compare with */
+ Oid *dupOperators pg_node_attr(array_size(numCols));
+ Oid *dupCollations pg_node_attr(array_size(numCols));
+
+ /* where is the flag column, if any */
+ AttrNumber flagColIdx;
+
+ /* flag value for first input relation */
+ int firstFlag;
+
+ /* estimated number of groups in input */
+ long numGroups;
+} SetOp;
+
+/* ----------------
+ * lock-rows node
+ *
+ * rowMarks identifies the rels to be locked by this node; it should be
+ * a subset of the rowMarks listed in the top-level PlannedStmt.
+ * epqParam is a Param that all scan nodes below this one must depend on.
+ * It is used to force re-evaluation of the plan during EvalPlanQual.
+ * ----------------
+ */
+typedef struct LockRows
+{
+ Plan plan;
+ List *rowMarks; /* a list of PlanRowMark's */
+ int epqParam; /* ID of Param for EvalPlanQual re-eval */
+} LockRows;
+
+/* ----------------
+ * limit node
+ *
+ * Note: as of Postgres 8.2, the offset and count expressions are expected
+ * to yield int8, rather than int4 as before.
+ * ----------------
+ */
+typedef struct Limit
+{
+ Plan plan;
+
+ /* OFFSET parameter, or NULL if none */
+ Node *limitOffset;
+
+ /* COUNT parameter, or NULL if none */
+ Node *limitCount;
+
+ /* limit type */
+ LimitOption limitOption;
+
+ /* number of columns to check for similarity */
+ int uniqNumCols;
+
+ /* their indexes in the target list */
+ AttrNumber *uniqColIdx pg_node_attr(array_size(uniqNumCols));
+
+ /* equality operators to compare with */
+ Oid *uniqOperators pg_node_attr(array_size(uniqNumCols));
+
+ /* collations for equality comparisons */
+ Oid *uniqCollations pg_node_attr(array_size(uniqNumCols));
+} Limit;
+
+
+/*
+ * RowMarkType -
+ * enums for types of row-marking operations
+ *
+ * The first four of these values represent different lock strengths that
+ * we can take on tuples according to SELECT FOR [KEY] UPDATE/SHARE requests.
+ * We support these on regular tables, as well as on foreign tables whose FDWs
+ * report support for late locking. For other foreign tables, any locking
+ * that might be done for such requests must happen during the initial row
+ * fetch; their FDWs provide no mechanism for going back to lock a row later.
+ * This means that the semantics will be a bit different than for a local
+ * table; in particular we are likely to lock more rows than would be locked
+ * locally, since remote rows will be locked even if they then fail
+ * locally-checked restriction or join quals. However, the prospect of
+ * doing a separate remote query to lock each selected row is usually pretty
+ * unappealing, so early locking remains a credible design choice for FDWs.
+ *
+ * When doing UPDATE/DELETE/MERGE/SELECT FOR UPDATE/SHARE, we have to uniquely
+ * identify all the source rows, not only those from the target relations, so
+ * that we can perform EvalPlanQual rechecking at need. For plain tables we
+ * can just fetch the TID, much as for a target relation; this case is
+ * represented by ROW_MARK_REFERENCE. Otherwise (for example for VALUES or
+ * FUNCTION scans) we have to copy the whole row value. ROW_MARK_COPY is
+ * pretty inefficient, since most of the time we'll never need the data; but
+ * fortunately the overhead is usually not performance-critical in practice.
+ * By default we use ROW_MARK_COPY for foreign tables, but if the FDW has
+ * a concept of rowid it can request to use ROW_MARK_REFERENCE instead.
+ * (Again, this probably doesn't make sense if a physical remote fetch is
+ * needed, but for FDWs that map to local storage it might be credible.)
+ */
+typedef enum RowMarkType
+{
+ ROW_MARK_EXCLUSIVE, /* obtain exclusive tuple lock */
+ ROW_MARK_NOKEYEXCLUSIVE, /* obtain no-key exclusive tuple lock */
+ ROW_MARK_SHARE, /* obtain shared tuple lock */
+ ROW_MARK_KEYSHARE, /* obtain keyshare tuple lock */
+ ROW_MARK_REFERENCE, /* just fetch the TID, don't lock it */
+ ROW_MARK_COPY /* physically copy the row value */
+} RowMarkType;
+
+#define RowMarkRequiresRowShareLock(marktype) ((marktype) <= ROW_MARK_KEYSHARE)
+
+/*
+ * PlanRowMark -
+ * plan-time representation of FOR [KEY] UPDATE/SHARE clauses
+ *
+ * When doing UPDATE/DELETE/MERGE/SELECT FOR UPDATE/SHARE, we create a separate
+ * PlanRowMark node for each non-target relation in the query. Relations that
+ * are not specified as FOR UPDATE/SHARE are marked ROW_MARK_REFERENCE (if
+ * regular tables or supported foreign tables) or ROW_MARK_COPY (if not).
+ *
+ * Initially all PlanRowMarks have rti == prti and isParent == false.
+ * When the planner discovers that a relation is the root of an inheritance
+ * tree, it sets isParent true, and adds an additional PlanRowMark to the
+ * list for each child relation (including the target rel itself in its role
+ * as a child, if it is not a partitioned table). Any non-leaf partitioned
+ * child relations will also have entries with isParent = true. The child
+ * entries have rti == child rel's RT index and prti == top parent's RT index,
+ * and can therefore be recognized as children by the fact that prti != rti.
+ * The parent's allMarkTypes field gets the OR of (1<0 means N levels up
+ */
+ Index varlevelsup;
+
+ /*
+ * varnosyn/varattnosyn are ignored for equality, because Vars with
+ * different syntactic identifiers are semantically the same as long as
+ * their varno/varattno match.
+ */
+ /* syntactic relation index (0 if unknown) */
+ Index varnosyn pg_node_attr(equal_ignore, query_jumble_ignore);
+ /* syntactic attribute number */
+ AttrNumber varattnosyn pg_node_attr(equal_ignore, query_jumble_ignore);
+
+ /* token location, or -1 if unknown */
+ int location;
+} Var;
+
+/*
+ * Const
+ *
+ * Note: for varlena data types, we make a rule that a Const node's value
+ * must be in non-extended form (4-byte header, no compression or external
+ * references). This ensures that the Const node is self-contained and makes
+ * it more likely that equal() will see logically identical values as equal.
+ *
+ * Only the constant type OID is relevant for the query jumbling.
+ */
+typedef struct Const
+{
+ pg_node_attr(custom_copy_equal, custom_read_write)
+
+ Expr xpr;
+ /* pg_type OID of the constant's datatype */
+ Oid consttype;
+ /* typmod value, if any */
+ int32 consttypmod pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid constcollid pg_node_attr(query_jumble_ignore);
+ /* typlen of the constant's datatype */
+ int constlen pg_node_attr(query_jumble_ignore);
+ /* the constant's value */
+ Datum constvalue pg_node_attr(query_jumble_ignore);
+ /* whether the constant is null (if true, constvalue is undefined) */
+ bool constisnull pg_node_attr(query_jumble_ignore);
+
+ /*
+ * Whether this datatype is passed by value. If true, then all the
+ * information is stored in the Datum. If false, then the Datum contains
+ * a pointer to the information.
+ */
+ bool constbyval pg_node_attr(query_jumble_ignore);
+
+ /*
+ * token location, or -1 if unknown. All constants are tracked as
+ * locations in query jumbling, to be marked as parameters.
+ */
+ int location pg_node_attr(query_jumble_location);
+} Const;
+
+/*
+ * Param
+ *
+ * paramkind specifies the kind of parameter. The possible values
+ * for this field are:
+ *
+ * PARAM_EXTERN: The parameter value is supplied from outside the plan.
+ * Such parameters are numbered from 1 to n.
+ *
+ * PARAM_EXEC: The parameter is an internal executor parameter, used
+ * for passing values into and out of sub-queries or from
+ * nestloop joins to their inner scans.
+ * For historical reasons, such parameters are numbered from 0.
+ * These numbers are independent of PARAM_EXTERN numbers.
+ *
+ * PARAM_SUBLINK: The parameter represents an output column of a SubLink
+ * node's sub-select. The column number is contained in the
+ * `paramid' field. (This type of Param is converted to
+ * PARAM_EXEC during planning.)
+ *
+ * PARAM_MULTIEXPR: Like PARAM_SUBLINK, the parameter represents an
+ * output column of a SubLink node's sub-select, but here, the
+ * SubLink is always a MULTIEXPR SubLink. The high-order 16 bits
+ * of the `paramid' field contain the SubLink's subLinkId, and
+ * the low-order 16 bits contain the column number. (This type
+ * of Param is also converted to PARAM_EXEC during planning.)
+ */
+typedef enum ParamKind
+{
+ PARAM_EXTERN,
+ PARAM_EXEC,
+ PARAM_SUBLINK,
+ PARAM_MULTIEXPR
+} ParamKind;
+
+typedef struct Param
+{
+ Expr xpr;
+ ParamKind paramkind; /* kind of parameter. See above */
+ int paramid; /* numeric ID for parameter */
+ Oid paramtype; /* pg_type OID of parameter's datatype */
+ /* typmod value, if known */
+ int32 paramtypmod pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid paramcollid pg_node_attr(query_jumble_ignore);
+ /* token location, or -1 if unknown */
+ int location;
+} Param;
+
+/*
+ * Aggref
+ *
+ * The aggregate's args list is a targetlist, ie, a list of TargetEntry nodes.
+ *
+ * For a normal (non-ordered-set) aggregate, the non-resjunk TargetEntries
+ * represent the aggregate's regular arguments (if any) and resjunk TLEs can
+ * be added at the end to represent ORDER BY expressions that are not also
+ * arguments. As in a top-level Query, the TLEs can be marked with
+ * ressortgroupref indexes to let them be referenced by SortGroupClause
+ * entries in the aggorder and/or aggdistinct lists. This represents ORDER BY
+ * and DISTINCT operations to be applied to the aggregate input rows before
+ * they are passed to the transition function. The grammar only allows a
+ * simple "DISTINCT" specifier for the arguments, but we use the full
+ * query-level representation to allow more code sharing.
+ *
+ * For an ordered-set aggregate, the args list represents the WITHIN GROUP
+ * (aggregated) arguments, all of which will be listed in the aggorder list.
+ * DISTINCT is not supported in this case, so aggdistinct will be NIL.
+ * The direct arguments appear in aggdirectargs (as a list of plain
+ * expressions, not TargetEntry nodes).
+ *
+ * aggtranstype is the data type of the state transition values for this
+ * aggregate (resolved to an actual type, if agg's transtype is polymorphic).
+ * This is determined during planning and is InvalidOid before that.
+ *
+ * aggargtypes is an OID list of the data types of the direct and regular
+ * arguments. Normally it's redundant with the aggdirectargs and args lists,
+ * but in a combining aggregate, it's not because the args list has been
+ * replaced with a single argument representing the partial-aggregate
+ * transition values.
+ *
+ * aggpresorted is set by the query planner for ORDER BY and DISTINCT
+ * aggregates where the chosen plan provides presorted input for this
+ * aggregate during execution.
+ *
+ * aggsplit indicates the expected partial-aggregation mode for the Aggref's
+ * parent plan node. It's always set to AGGSPLIT_SIMPLE in the parser, but
+ * the planner might change it to something else. We use this mainly as
+ * a crosscheck that the Aggrefs match the plan; but note that when aggsplit
+ * indicates a non-final mode, aggtype reflects the transition data type
+ * not the SQL-level output type of the aggregate.
+ *
+ * aggno and aggtransno are -1 in the parse stage, and are set in planning.
+ * Aggregates with the same 'aggno' represent the same aggregate expression,
+ * and can share the result. Aggregates with same 'transno' but different
+ * 'aggno' can share the same transition state, only the final function needs
+ * to be called separately.
+ *
+ * Information related to collations, transition types and internal states
+ * are irrelevant for the query jumbling.
+ */
+typedef struct Aggref
+{
+ Expr xpr;
+
+ /* pg_proc Oid of the aggregate */
+ Oid aggfnoid;
+
+ /* type Oid of result of the aggregate */
+ Oid aggtype pg_node_attr(query_jumble_ignore);
+
+ /* OID of collation of result */
+ Oid aggcollid pg_node_attr(query_jumble_ignore);
+
+ /* OID of collation that function should use */
+ Oid inputcollid pg_node_attr(query_jumble_ignore);
+
+ /*
+ * type Oid of aggregate's transition value; ignored for equal since it
+ * might not be set yet
+ */
+ Oid aggtranstype pg_node_attr(equal_ignore, query_jumble_ignore);
+
+ /* type Oids of direct and aggregated args */
+ List *aggargtypes pg_node_attr(query_jumble_ignore);
+
+ /* direct arguments, if an ordered-set agg */
+ List *aggdirectargs;
+
+ /* aggregated arguments and sort expressions */
+ List *args;
+
+ /* ORDER BY (list of SortGroupClause) */
+ List *aggorder;
+
+ /* DISTINCT (list of SortGroupClause) */
+ List *aggdistinct;
+
+ /* FILTER expression, if any */
+ Expr *aggfilter;
+
+ /* true if argument list was really '*' */
+ bool aggstar pg_node_attr(query_jumble_ignore);
+
+ /*
+ * true if variadic arguments have been combined into an array last
+ * argument
+ */
+ bool aggvariadic pg_node_attr(query_jumble_ignore);
+
+ /* aggregate kind (see pg_aggregate.h) */
+ char aggkind pg_node_attr(query_jumble_ignore);
+
+ /* aggregate input already sorted */
+ bool aggpresorted pg_node_attr(equal_ignore, query_jumble_ignore);
+
+ /* > 0 if agg belongs to outer query */
+ Index agglevelsup pg_node_attr(query_jumble_ignore);
+
+ /* expected agg-splitting mode of parent Agg */
+ AggSplit aggsplit pg_node_attr(query_jumble_ignore);
+
+ /* unique ID within the Agg node */
+ int aggno pg_node_attr(query_jumble_ignore);
+
+ /* unique ID of transition state in the Agg */
+ int aggtransno pg_node_attr(query_jumble_ignore);
+
+ /* token location, or -1 if unknown */
+ int location;
+} Aggref;
+
+/*
+ * GroupingFunc
+ *
+ * A GroupingFunc is a GROUPING(...) expression, which behaves in many ways
+ * like an aggregate function (e.g. it "belongs" to a specific query level,
+ * which might not be the one immediately containing it), but also differs in
+ * an important respect: it never evaluates its arguments, they merely
+ * designate expressions from the GROUP BY clause of the query level to which
+ * it belongs.
+ *
+ * The spec defines the evaluation of GROUPING() purely by syntactic
+ * replacement, but we make it a real expression for optimization purposes so
+ * that one Agg node can handle multiple grouping sets at once. Evaluating the
+ * result only needs the column positions to check against the grouping set
+ * being projected. However, for EXPLAIN to produce meaningful output, we have
+ * to keep the original expressions around, since expression deparse does not
+ * give us any feasible way to get at the GROUP BY clause.
+ *
+ * Also, we treat two GroupingFunc nodes as equal if they have equal arguments
+ * lists and agglevelsup, without comparing the refs and cols annotations.
+ *
+ * In raw parse output we have only the args list; parse analysis fills in the
+ * refs list, and the planner fills in the cols list.
+ *
+ * All the fields used as information for an internal state are irrelevant
+ * for the query jumbling.
+ */
+typedef struct GroupingFunc
+{
+ Expr xpr;
+
+ /* arguments, not evaluated but kept for benefit of EXPLAIN etc. */
+ List *args pg_node_attr(query_jumble_ignore);
+
+ /* ressortgrouprefs of arguments */
+ List *refs pg_node_attr(equal_ignore);
+
+ /* actual column positions set by planner */
+ List *cols pg_node_attr(equal_ignore, query_jumble_ignore);
+
+ /* same as Aggref.agglevelsup */
+ Index agglevelsup;
+
+ /* token location */
+ int location;
+} GroupingFunc;
+
+/*
+ * WindowFunc
+ *
+ * Collation information is irrelevant for the query jumbling, as is the
+ * internal state information of the node like "winstar" and "winagg".
+ */
+typedef struct WindowFunc
+{
+ Expr xpr;
+ /* pg_proc Oid of the function */
+ Oid winfnoid;
+ /* type Oid of result of the window function */
+ Oid wintype pg_node_attr(query_jumble_ignore);
+ /* OID of collation of result */
+ Oid wincollid pg_node_attr(query_jumble_ignore);
+ /* OID of collation that function should use */
+ Oid inputcollid pg_node_attr(query_jumble_ignore);
+ /* arguments to the window function */
+ List *args;
+ /* FILTER expression, if any */
+ Expr *aggfilter;
+ /* index of associated WindowClause */
+ Index winref;
+ /* true if argument list was really '*' */
+ bool winstar pg_node_attr(query_jumble_ignore);
+ /* is function a simple aggregate? */
+ bool winagg pg_node_attr(query_jumble_ignore);
+ /* token location, or -1 if unknown */
+ int location;
+} WindowFunc;
+
+/*
+ * SubscriptingRef: describes a subscripting operation over a container
+ * (array, etc).
+ *
+ * A SubscriptingRef can describe fetching a single element from a container,
+ * fetching a part of a container (e.g. an array slice), storing a single
+ * element into a container, or storing a slice. The "store" cases work with
+ * an initial container value and a source value that is inserted into the
+ * appropriate part of the container; the result of the operation is an
+ * entire new modified container value.
+ *
+ * If reflowerindexpr = NIL, then we are fetching or storing a single container
+ * element at the subscripts given by refupperindexpr. Otherwise we are
+ * fetching or storing a container slice, that is a rectangular subcontainer
+ * with lower and upper bounds given by the index expressions.
+ * reflowerindexpr must be the same length as refupperindexpr when it
+ * is not NIL.
+ *
+ * In the slice case, individual expressions in the subscript lists can be
+ * NULL, meaning "substitute the array's current lower or upper bound".
+ * (Non-array containers may or may not support this.)
+ *
+ * refcontainertype is the actual container type that determines the
+ * subscripting semantics. (This will generally be either the exposed type of
+ * refexpr, or the base type if that is a domain.) refelemtype is the type of
+ * the container's elements; this is saved for the use of the subscripting
+ * functions, but is not used by the core code. refrestype, reftypmod, and
+ * refcollid describe the type of the SubscriptingRef's result. In a store
+ * expression, refrestype will always match refcontainertype; in a fetch,
+ * it could be refelemtype for an element fetch, or refcontainertype for a
+ * slice fetch, or possibly something else as determined by type-specific
+ * subscripting logic. Likewise, reftypmod and refcollid will match the
+ * container's properties in a store, but could be different in a fetch.
+ *
+ * Any internal state data is ignored for the query jumbling.
+ *
+ * Note: for the cases where a container is returned, if refexpr yields a R/W
+ * expanded container, then the implementation is allowed to modify that
+ * object in-place and return the same object.
+ */
+typedef struct SubscriptingRef
+{
+ Expr xpr;
+ /* type of the container proper */
+ Oid refcontainertype pg_node_attr(query_jumble_ignore);
+ /* the container type's pg_type.typelem */
+ Oid refelemtype pg_node_attr(query_jumble_ignore);
+ /* type of the SubscriptingRef's result */
+ Oid refrestype pg_node_attr(query_jumble_ignore);
+ /* typmod of the result */
+ int32 reftypmod pg_node_attr(query_jumble_ignore);
+ /* collation of result, or InvalidOid if none */
+ Oid refcollid pg_node_attr(query_jumble_ignore);
+ /* expressions that evaluate to upper container indexes */
+ List *refupperindexpr;
+
+ /*
+ * expressions that evaluate to lower container indexes, or NIL for single
+ * container element.
+ */
+ List *reflowerindexpr;
+ /* the expression that evaluates to a container value */
+ Expr *refexpr;
+ /* expression for the source value, or NULL if fetch */
+ Expr *refassgnexpr;
+} SubscriptingRef;
+
+/*
+ * CoercionContext - distinguishes the allowed set of type casts
+ *
+ * NB: ordering of the alternatives is significant; later (larger) values
+ * allow more casts than earlier ones.
+ */
+typedef enum CoercionContext
+{
+ COERCION_IMPLICIT, /* coercion in context of expression */
+ COERCION_ASSIGNMENT, /* coercion in context of assignment */
+ COERCION_PLPGSQL, /* if no assignment cast, use CoerceViaIO */
+ COERCION_EXPLICIT /* explicit cast operation */
+} CoercionContext;
+
+/*
+ * CoercionForm - how to display a FuncExpr or related node
+ *
+ * "Coercion" is a bit of a misnomer, since this value records other
+ * special syntaxes besides casts, but for now we'll keep this naming.
+ *
+ * NB: equal() ignores CoercionForm fields, therefore this *must* not carry
+ * any semantically significant information. We need that behavior so that
+ * the planner will consider equivalent implicit and explicit casts to be
+ * equivalent. In cases where those actually behave differently, the coercion
+ * function's arguments will be different.
+ */
+typedef enum CoercionForm
+{
+ COERCE_EXPLICIT_CALL, /* display as a function call */
+ COERCE_EXPLICIT_CAST, /* display as an explicit cast */
+ COERCE_IMPLICIT_CAST, /* implicit cast, so hide it */
+ COERCE_SQL_SYNTAX /* display with SQL-mandated special syntax */
+} CoercionForm;
+
+/*
+ * FuncExpr - expression node for a function call
+ *
+ * Collation information is irrelevant for the query jumbling, only the
+ * arguments and the function OID matter.
+ */
+typedef struct FuncExpr
+{
+ Expr xpr;
+ /* PG_PROC OID of the function */
+ Oid funcid;
+ /* PG_TYPE OID of result value */
+ Oid funcresulttype pg_node_attr(query_jumble_ignore);
+ /* true if function returns set */
+ bool funcretset pg_node_attr(query_jumble_ignore);
+
+ /*
+ * true if variadic arguments have been combined into an array last
+ * argument
+ */
+ bool funcvariadic pg_node_attr(query_jumble_ignore);
+ /* how to display this function call */
+ CoercionForm funcformat pg_node_attr(query_jumble_ignore);
+ /* OID of collation of result */
+ Oid funccollid pg_node_attr(query_jumble_ignore);
+ /* OID of collation that function should use */
+ Oid inputcollid pg_node_attr(query_jumble_ignore);
+ /* arguments to the function */
+ List *args;
+ /* token location, or -1 if unknown */
+ int location;
+} FuncExpr;
+
+/*
+ * NamedArgExpr - a named argument of a function
+ *
+ * This node type can only appear in the args list of a FuncCall or FuncExpr
+ * node. We support pure positional call notation (no named arguments),
+ * named notation (all arguments are named), and mixed notation (unnamed
+ * arguments followed by named ones).
+ *
+ * Parse analysis sets argnumber to the positional index of the argument,
+ * but doesn't rearrange the argument list.
+ *
+ * The planner will convert argument lists to pure positional notation
+ * during expression preprocessing, so execution never sees a NamedArgExpr.
+ */
+typedef struct NamedArgExpr
+{
+ Expr xpr;
+ /* the argument expression */
+ Expr *arg;
+ /* the name */
+ char *name pg_node_attr(query_jumble_ignore);
+ /* argument's number in positional notation */
+ int argnumber;
+ /* argument name location, or -1 if unknown */
+ int location;
+} NamedArgExpr;
+
+/*
+ * OpExpr - expression node for an operator invocation
+ *
+ * Semantically, this is essentially the same as a function call.
+ *
+ * Note that opfuncid is not necessarily filled in immediately on creation
+ * of the node. The planner makes sure it is valid before passing the node
+ * tree to the executor, but during parsing/planning opfuncid can be 0.
+ * Therefore, equal() will accept a zero value as being equal to other values.
+ *
+ * Internal state information and collation data is irrelevant for the query
+ * jumbling.
+ */
+typedef struct OpExpr
+{
+ Expr xpr;
+
+ /* PG_OPERATOR OID of the operator */
+ Oid opno;
+
+ /* PG_PROC OID of underlying function */
+ Oid opfuncid pg_node_attr(equal_ignore_if_zero, query_jumble_ignore);
+
+ /* PG_TYPE OID of result value */
+ Oid opresulttype pg_node_attr(query_jumble_ignore);
+
+ /* true if operator returns set */
+ bool opretset pg_node_attr(query_jumble_ignore);
+
+ /* OID of collation of result */
+ Oid opcollid pg_node_attr(query_jumble_ignore);
+
+ /* OID of collation that operator should use */
+ Oid inputcollid pg_node_attr(query_jumble_ignore);
+
+ /* arguments to the operator (1 or 2) */
+ List *args;
+
+ /* token location, or -1 if unknown */
+ int location;
+} OpExpr;
+
+/*
+ * DistinctExpr - expression node for "x IS DISTINCT FROM y"
+ *
+ * Except for the nodetag, this is represented identically to an OpExpr
+ * referencing the "=" operator for x and y.
+ * We use "=", not the more obvious "<>", because more datatypes have "="
+ * than "<>". This means the executor must invert the operator result.
+ * Note that the operator function won't be called at all if either input
+ * is NULL, since then the result can be determined directly.
+ */
+typedef OpExpr DistinctExpr;
+
+/*
+ * NullIfExpr - a NULLIF expression
+ *
+ * Like DistinctExpr, this is represented the same as an OpExpr referencing
+ * the "=" operator for x and y.
+ */
+typedef OpExpr NullIfExpr;
+
+/*
+ * ScalarArrayOpExpr - expression node for "scalar op ANY/ALL (array)"
+ *
+ * The operator must yield boolean. It is applied to the left operand
+ * and each element of the righthand array, and the results are combined
+ * with OR or AND (for ANY or ALL respectively). The node representation
+ * is almost the same as for the underlying operator, but we need a useOr
+ * flag to remember whether it's ANY or ALL, and we don't have to store
+ * the result type (or the collation) because it must be boolean.
+ *
+ * A ScalarArrayOpExpr with a valid hashfuncid is evaluated during execution
+ * by building a hash table containing the Const values from the RHS arg.
+ * This table is probed during expression evaluation. The planner will set
+ * hashfuncid to the hash function which must be used to build and probe the
+ * hash table. The executor determines if it should use hash-based checks or
+ * the more traditional means based on if the hashfuncid is set or not.
+ *
+ * When performing hashed NOT IN, the negfuncid will also be set to the
+ * equality function which the hash table must use to build and probe the hash
+ * table. opno and opfuncid will remain set to the <> operator and its
+ * corresponding function and won't be used during execution. For
+ * non-hashtable based NOT INs, negfuncid will be set to InvalidOid. See
+ * convert_saop_to_hashed_saop().
+ *
+ * Similar to OpExpr, opfuncid, hashfuncid, and negfuncid are not necessarily
+ * filled in right away, so will be ignored for equality if they are not set
+ * yet.
+ *
+ * OID entries of the internal function types are irrelevant for the query
+ * jumbling, but the operator OID and the arguments are.
+ */
+typedef struct ScalarArrayOpExpr
+{
+ Expr xpr;
+
+ /* PG_OPERATOR OID of the operator */
+ Oid opno;
+
+ /* PG_PROC OID of comparison function */
+ Oid opfuncid pg_node_attr(equal_ignore_if_zero, query_jumble_ignore);
+
+ /* PG_PROC OID of hash func or InvalidOid */
+ Oid hashfuncid pg_node_attr(equal_ignore_if_zero, query_jumble_ignore);
+
+ /* PG_PROC OID of negator of opfuncid function or InvalidOid. See above */
+ Oid negfuncid pg_node_attr(equal_ignore_if_zero, query_jumble_ignore);
+
+ /* true for ANY, false for ALL */
+ bool useOr;
+
+ /* OID of collation that operator should use */
+ Oid inputcollid pg_node_attr(query_jumble_ignore);
+
+ /* the scalar and array operands */
+ List *args;
+
+ /* token location, or -1 if unknown */
+ int location;
+} ScalarArrayOpExpr;
+
+/*
+ * BoolExpr - expression node for the basic Boolean operators AND, OR, NOT
+ *
+ * Notice the arguments are given as a List. For NOT, of course the list
+ * must always have exactly one element. For AND and OR, there can be two
+ * or more arguments.
+ */
+typedef enum BoolExprType
+{
+ AND_EXPR, OR_EXPR, NOT_EXPR
+} BoolExprType;
+
+typedef struct BoolExpr
+{
+ pg_node_attr(custom_read_write)
+
+ Expr xpr;
+ BoolExprType boolop;
+ List *args; /* arguments to this expression */
+ int location; /* token location, or -1 if unknown */
+} BoolExpr;
+
+/*
+ * SubLink
+ *
+ * A SubLink represents a subselect appearing in an expression, and in some
+ * cases also the combining operator(s) just above it. The subLinkType
+ * indicates the form of the expression represented:
+ * EXISTS_SUBLINK EXISTS(SELECT ...)
+ * ALL_SUBLINK (lefthand) op ALL (SELECT ...)
+ * ANY_SUBLINK (lefthand) op ANY (SELECT ...)
+ * ROWCOMPARE_SUBLINK (lefthand) op (SELECT ...)
+ * EXPR_SUBLINK (SELECT with single targetlist item ...)
+ * MULTIEXPR_SUBLINK (SELECT with multiple targetlist items ...)
+ * ARRAY_SUBLINK ARRAY(SELECT with single targetlist item ...)
+ * CTE_SUBLINK WITH query (never actually part of an expression)
+ * For ALL, ANY, and ROWCOMPARE, the lefthand is a list of expressions of the
+ * same length as the subselect's targetlist. ROWCOMPARE will *always* have
+ * a list with more than one entry; if the subselect has just one target
+ * then the parser will create an EXPR_SUBLINK instead (and any operator
+ * above the subselect will be represented separately).
+ * ROWCOMPARE, EXPR, and MULTIEXPR require the subselect to deliver at most
+ * one row (if it returns no rows, the result is NULL).
+ * ALL, ANY, and ROWCOMPARE require the combining operators to deliver boolean
+ * results. ALL and ANY combine the per-row results using AND and OR
+ * semantics respectively.
+ * ARRAY requires just one target column, and creates an array of the target
+ * column's type using any number of rows resulting from the subselect.
+ *
+ * SubLink is classed as an Expr node, but it is not actually executable;
+ * it must be replaced in the expression tree by a SubPlan node during
+ * planning.
+ *
+ * NOTE: in the raw output of gram.y, testexpr contains just the raw form
+ * of the lefthand expression (if any), and operName is the String name of
+ * the combining operator. Also, subselect is a raw parsetree. During parse
+ * analysis, the parser transforms testexpr into a complete boolean expression
+ * that compares the lefthand value(s) to PARAM_SUBLINK nodes representing the
+ * output columns of the subselect. And subselect is transformed to a Query.
+ * This is the representation seen in saved rules and in the rewriter.
+ *
+ * In EXISTS, EXPR, MULTIEXPR, and ARRAY SubLinks, testexpr and operName
+ * are unused and are always null.
+ *
+ * subLinkId is currently used only for MULTIEXPR SubLinks, and is zero in
+ * other SubLinks. This number identifies different multiple-assignment
+ * subqueries within an UPDATE statement's SET list. It is unique only
+ * within a particular targetlist. The output column(s) of the MULTIEXPR
+ * are referenced by PARAM_MULTIEXPR Params appearing elsewhere in the tlist.
+ *
+ * The CTE_SUBLINK case never occurs in actual SubLink nodes, but it is used
+ * in SubPlans generated for WITH subqueries.
+ */
+typedef enum SubLinkType
+{
+ EXISTS_SUBLINK,
+ ALL_SUBLINK,
+ ANY_SUBLINK,
+ ROWCOMPARE_SUBLINK,
+ EXPR_SUBLINK,
+ MULTIEXPR_SUBLINK,
+ ARRAY_SUBLINK,
+ CTE_SUBLINK /* for SubPlans only */
+} SubLinkType;
+
+
+typedef struct SubLink
+{
+ Expr xpr;
+ SubLinkType subLinkType; /* see above */
+ int subLinkId; /* ID (1..n); 0 if not MULTIEXPR */
+ Node *testexpr; /* outer-query test for ALL/ANY/ROWCOMPARE */
+ /* originally specified operator name */
+ List *operName pg_node_attr(query_jumble_ignore);
+ /* subselect as Query* or raw parsetree */
+ Node *subselect;
+ int location; /* token location, or -1 if unknown */
+} SubLink;
+
+/*
+ * SubPlan - executable expression node for a subplan (sub-SELECT)
+ *
+ * The planner replaces SubLink nodes in expression trees with SubPlan
+ * nodes after it has finished planning the subquery. SubPlan references
+ * a sub-plantree stored in the subplans list of the toplevel PlannedStmt.
+ * (We avoid a direct link to make it easier to copy expression trees
+ * without causing multiple processing of the subplan.)
+ *
+ * In an ordinary subplan, testexpr points to an executable expression
+ * (OpExpr, an AND/OR tree of OpExprs, or RowCompareExpr) for the combining
+ * operator(s); the left-hand arguments are the original lefthand expressions,
+ * and the right-hand arguments are PARAM_EXEC Param nodes representing the
+ * outputs of the sub-select. (NOTE: runtime coercion functions may be
+ * inserted as well.) This is just the same expression tree as testexpr in
+ * the original SubLink node, but the PARAM_SUBLINK nodes are replaced by
+ * suitably numbered PARAM_EXEC nodes.
+ *
+ * If the sub-select becomes an initplan rather than a subplan, the executable
+ * expression is part of the outer plan's expression tree (and the SubPlan
+ * node itself is not, but rather is found in the outer plan's initPlan
+ * list). In this case testexpr is NULL to avoid duplication.
+ *
+ * The planner also derives lists of the values that need to be passed into
+ * and out of the subplan. Input values are represented as a list "args" of
+ * expressions to be evaluated in the outer-query context (currently these
+ * args are always just Vars, but in principle they could be any expression).
+ * The values are assigned to the global PARAM_EXEC params indexed by parParam
+ * (the parParam and args lists must have the same ordering). setParam is a
+ * list of the PARAM_EXEC params that are computed by the sub-select, if it
+ * is an initplan or MULTIEXPR plan; they are listed in order by sub-select
+ * output column position. (parParam and setParam are integer Lists, not
+ * Bitmapsets, because their ordering is significant.)
+ *
+ * Also, the planner computes startup and per-call costs for use of the
+ * SubPlan. Note that these include the cost of the subquery proper,
+ * evaluation of the testexpr if any, and any hashtable management overhead.
+ */
+typedef struct SubPlan
+{
+ pg_node_attr(no_query_jumble)
+
+ Expr xpr;
+ /* Fields copied from original SubLink: */
+ SubLinkType subLinkType; /* see above */
+ /* The combining operators, transformed to an executable expression: */
+ Node *testexpr; /* OpExpr or RowCompareExpr expression tree */
+ List *paramIds; /* IDs of Params embedded in the above */
+ /* Identification of the Plan tree to use: */
+ int plan_id; /* Index (from 1) in PlannedStmt.subplans */
+ /* Identification of the SubPlan for EXPLAIN and debugging purposes: */
+ char *plan_name; /* A name assigned during planning */
+ /* Extra data useful for determining subplan's output type: */
+ Oid firstColType; /* Type of first column of subplan result */
+ int32 firstColTypmod; /* Typmod of first column of subplan result */
+ Oid firstColCollation; /* Collation of first column of subplan
+ * result */
+ /* Information about execution strategy: */
+ bool useHashTable; /* true to store subselect output in a hash
+ * table (implies we are doing "IN") */
+ bool unknownEqFalse; /* true if it's okay to return FALSE when the
+ * spec result is UNKNOWN; this allows much
+ * simpler handling of null values */
+ bool parallel_safe; /* is the subplan parallel-safe? */
+ /* Note: parallel_safe does not consider contents of testexpr or args */
+ /* Information for passing params into and out of the subselect: */
+ /* setParam and parParam are lists of integers (param IDs) */
+ List *setParam; /* initplan and MULTIEXPR subqueries have to
+ * set these Params for parent plan */
+ List *parParam; /* indices of input Params from parent plan */
+ List *args; /* exprs to pass as parParam values */
+ /* Estimated execution costs: */
+ Cost startup_cost; /* one-time setup cost */
+ Cost per_call_cost; /* cost for each subplan evaluation */
+} SubPlan;
+
+/*
+ * AlternativeSubPlan - expression node for a choice among SubPlans
+ *
+ * This is used only transiently during planning: by the time the plan
+ * reaches the executor, all AlternativeSubPlan nodes have been removed.
+ *
+ * The subplans are given as a List so that the node definition need not
+ * change if there's ever more than two alternatives. For the moment,
+ * though, there are always exactly two; and the first one is the fast-start
+ * plan.
+ */
+typedef struct AlternativeSubPlan
+{
+ pg_node_attr(no_query_jumble)
+
+ Expr xpr;
+ List *subplans; /* SubPlan(s) with equivalent results */
+} AlternativeSubPlan;
+
+/* ----------------
+ * FieldSelect
+ *
+ * FieldSelect represents the operation of extracting one field from a tuple
+ * value. At runtime, the input expression is expected to yield a rowtype
+ * Datum. The specified field number is extracted and returned as a Datum.
+ * ----------------
+ */
+
+typedef struct FieldSelect
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ AttrNumber fieldnum; /* attribute number of field to extract */
+ /* type of the field (result type of this node) */
+ Oid resulttype pg_node_attr(query_jumble_ignore);
+ /* output typmod (usually -1) */
+ int32 resulttypmod pg_node_attr(query_jumble_ignore);
+ /* OID of collation of the field */
+ Oid resultcollid pg_node_attr(query_jumble_ignore);
+} FieldSelect;
+
+/* ----------------
+ * FieldStore
+ *
+ * FieldStore represents the operation of modifying one field in a tuple
+ * value, yielding a new tuple value (the input is not touched!). Like
+ * the assign case of SubscriptingRef, this is used to implement UPDATE of a
+ * portion of a column.
+ *
+ * resulttype is always a named composite type (not a domain). To update
+ * a composite domain value, apply CoerceToDomain to the FieldStore.
+ *
+ * A single FieldStore can actually represent updates of several different
+ * fields. The parser only generates FieldStores with single-element lists,
+ * but the planner will collapse multiple updates of the same base column
+ * into one FieldStore.
+ * ----------------
+ */
+
+typedef struct FieldStore
+{
+ Expr xpr;
+ Expr *arg; /* input tuple value */
+ List *newvals; /* new value(s) for field(s) */
+ /* integer list of field attnums */
+ List *fieldnums pg_node_attr(query_jumble_ignore);
+ /* type of result (same as type of arg) */
+ Oid resulttype pg_node_attr(query_jumble_ignore);
+ /* Like RowExpr, we deliberately omit a typmod and collation here */
+} FieldStore;
+
+/* ----------------
+ * RelabelType
+ *
+ * RelabelType represents a "dummy" type coercion between two binary-
+ * compatible datatypes, such as reinterpreting the result of an OID
+ * expression as an int4. It is a no-op at runtime; we only need it
+ * to provide a place to store the correct type to be attributed to
+ * the expression result during type resolution. (We can't get away
+ * with just overwriting the type field of the input expression node,
+ * so we need a separate node to show the coercion's result type.)
+ * ----------------
+ */
+
+typedef struct RelabelType
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ Oid resulttype; /* output type of coercion expression */
+ /* output typmod (usually -1) */
+ int32 resulttypmod pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid resultcollid pg_node_attr(query_jumble_ignore);
+ /* how to display this node */
+ CoercionForm relabelformat pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+} RelabelType;
+
+/* ----------------
+ * CoerceViaIO
+ *
+ * CoerceViaIO represents a type coercion between two types whose textual
+ * representations are compatible, implemented by invoking the source type's
+ * typoutput function then the destination type's typinput function.
+ * ----------------
+ */
+
+typedef struct CoerceViaIO
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ Oid resulttype; /* output type of coercion */
+ /* output typmod is not stored, but is presumed -1 */
+ /* OID of collation, or InvalidOid if none */
+ Oid resultcollid pg_node_attr(query_jumble_ignore);
+ /* how to display this node */
+ CoercionForm coerceformat pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+} CoerceViaIO;
+
+/* ----------------
+ * ArrayCoerceExpr
+ *
+ * ArrayCoerceExpr represents a type coercion from one array type to another,
+ * which is implemented by applying the per-element coercion expression
+ * "elemexpr" to each element of the source array. Within elemexpr, the
+ * source element is represented by a CaseTestExpr node. Note that even if
+ * elemexpr is a no-op (that is, just CaseTestExpr + RelabelType), the
+ * coercion still requires some effort: we have to fix the element type OID
+ * stored in the array header.
+ * ----------------
+ */
+
+typedef struct ArrayCoerceExpr
+{
+ Expr xpr;
+ Expr *arg; /* input expression (yields an array) */
+ Expr *elemexpr; /* expression representing per-element work */
+ Oid resulttype; /* output type of coercion (an array type) */
+ /* output typmod (also element typmod) */
+ int32 resulttypmod pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid resultcollid pg_node_attr(query_jumble_ignore);
+ /* how to display this node */
+ CoercionForm coerceformat pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+} ArrayCoerceExpr;
+
+/* ----------------
+ * ConvertRowtypeExpr
+ *
+ * ConvertRowtypeExpr represents a type coercion from one composite type
+ * to another, where the source type is guaranteed to contain all the columns
+ * needed for the destination type plus possibly others; the columns need not
+ * be in the same positions, but are matched up by name. This is primarily
+ * used to convert a whole-row value of an inheritance child table into a
+ * valid whole-row value of its parent table's rowtype. Both resulttype
+ * and the exposed type of "arg" must be named composite types (not domains).
+ * ----------------
+ */
+
+typedef struct ConvertRowtypeExpr
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ Oid resulttype; /* output type (always a composite type) */
+ /* Like RowExpr, we deliberately omit a typmod and collation here */
+ /* how to display this node */
+ CoercionForm convertformat pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+} ConvertRowtypeExpr;
+
+/*----------
+ * CollateExpr - COLLATE
+ *
+ * The planner replaces CollateExpr with RelabelType during expression
+ * preprocessing, so execution never sees a CollateExpr.
+ *----------
+ */
+typedef struct CollateExpr
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ Oid collOid; /* collation's OID */
+ int location; /* token location, or -1 if unknown */
+} CollateExpr;
+
+/*----------
+ * CaseExpr - a CASE expression
+ *
+ * We support two distinct forms of CASE expression:
+ * CASE WHEN boolexpr THEN expr [ WHEN boolexpr THEN expr ... ]
+ * CASE testexpr WHEN compexpr THEN expr [ WHEN compexpr THEN expr ... ]
+ * These are distinguishable by the "arg" field being NULL in the first case
+ * and the testexpr in the second case.
+ *
+ * In the raw grammar output for the second form, the condition expressions
+ * of the WHEN clauses are just the comparison values. Parse analysis
+ * converts these to valid boolean expressions of the form
+ * CaseTestExpr '=' compexpr
+ * where the CaseTestExpr node is a placeholder that emits the correct
+ * value at runtime. This structure is used so that the testexpr need be
+ * evaluated only once. Note that after parse analysis, the condition
+ * expressions always yield boolean.
+ *
+ * Note: we can test whether a CaseExpr has been through parse analysis
+ * yet by checking whether casetype is InvalidOid or not.
+ *----------
+ */
+typedef struct CaseExpr
+{
+ Expr xpr;
+ /* type of expression result */
+ Oid casetype pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid casecollid pg_node_attr(query_jumble_ignore);
+ Expr *arg; /* implicit equality comparison argument */
+ List *args; /* the arguments (list of WHEN clauses) */
+ Expr *defresult; /* the default result (ELSE clause) */
+ int location; /* token location, or -1 if unknown */
+} CaseExpr;
+
+/*
+ * CaseWhen - one arm of a CASE expression
+ */
+typedef struct CaseWhen
+{
+ Expr xpr;
+ Expr *expr; /* condition expression */
+ Expr *result; /* substitution result */
+ int location; /* token location, or -1 if unknown */
+} CaseWhen;
+
+/*
+ * Placeholder node for the test value to be processed by a CASE expression.
+ * This is effectively like a Param, but can be implemented more simply
+ * since we need only one replacement value at a time.
+ *
+ * We also abuse this node type for some other purposes, including:
+ * * Placeholder for the current array element value in ArrayCoerceExpr;
+ * see build_coercion_expression().
+ * * Nested FieldStore/SubscriptingRef assignment expressions in INSERT/UPDATE;
+ * see transformAssignmentIndirection().
+ * * Placeholder for intermediate results in some SQL/JSON expression nodes,
+ * such as JsonConstructorExpr.
+ *
+ * The uses in CaseExpr and ArrayCoerceExpr are safe only to the extent that
+ * there is not any other CaseExpr or ArrayCoerceExpr between the value source
+ * node and its child CaseTestExpr(s). This is true in the parse analysis
+ * output, but the planner's function-inlining logic has to be careful not to
+ * break it.
+ *
+ * The nested-assignment-expression case is safe because the only node types
+ * that can be above such CaseTestExprs are FieldStore and SubscriptingRef.
+ */
+typedef struct CaseTestExpr
+{
+ Expr xpr;
+ Oid typeId; /* type for substituted value */
+ /* typemod for substituted value */
+ int32 typeMod pg_node_attr(query_jumble_ignore);
+ /* collation for the substituted value */
+ Oid collation pg_node_attr(query_jumble_ignore);
+} CaseTestExpr;
+
+/*
+ * ArrayExpr - an ARRAY[] expression
+ *
+ * Note: if multidims is false, the constituent expressions all yield the
+ * scalar type identified by element_typeid. If multidims is true, the
+ * constituent expressions all yield arrays of element_typeid (ie, the same
+ * type as array_typeid); at runtime we must check for compatible subscripts.
+ */
+typedef struct ArrayExpr
+{
+ Expr xpr;
+ /* type of expression result */
+ Oid array_typeid pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid array_collid pg_node_attr(query_jumble_ignore);
+ /* common type of array elements */
+ Oid element_typeid pg_node_attr(query_jumble_ignore);
+ /* the array elements or sub-arrays */
+ List *elements;
+ /* true if elements are sub-arrays */
+ bool multidims pg_node_attr(query_jumble_ignore);
+ /* token location, or -1 if unknown */
+ int location;
+} ArrayExpr;
+
+/*
+ * RowExpr - a ROW() expression
+ *
+ * Note: the list of fields must have a one-for-one correspondence with
+ * physical fields of the associated rowtype, although it is okay for it
+ * to be shorter than the rowtype. That is, the N'th list element must
+ * match up with the N'th physical field. When the N'th physical field
+ * is a dropped column (attisdropped) then the N'th list element can just
+ * be a NULL constant. (This case can only occur for named composite types,
+ * not RECORD types, since those are built from the RowExpr itself rather
+ * than vice versa.) It is important not to assume that length(args) is
+ * the same as the number of columns logically present in the rowtype.
+ *
+ * colnames provides field names if the ROW() result is of type RECORD.
+ * Names *must* be provided if row_typeid is RECORDOID; but if it is a
+ * named composite type, colnames will be ignored in favor of using the
+ * type's cataloged field names, so colnames should be NIL. Like the
+ * args list, colnames is defined to be one-for-one with physical fields
+ * of the rowtype (although dropped columns shouldn't appear in the
+ * RECORD case, so this fine point is currently moot).
+ */
+typedef struct RowExpr
+{
+ Expr xpr;
+ List *args; /* the fields */
+
+ /* RECORDOID or a composite type's ID */
+ Oid row_typeid pg_node_attr(query_jumble_ignore);
+
+ /*
+ * row_typeid cannot be a domain over composite, only plain composite. To
+ * create a composite domain value, apply CoerceToDomain to the RowExpr.
+ *
+ * Note: we deliberately do NOT store a typmod. Although a typmod will be
+ * associated with specific RECORD types at runtime, it will differ for
+ * different backends, and so cannot safely be stored in stored
+ * parsetrees. We must assume typmod -1 for a RowExpr node.
+ *
+ * We don't need to store a collation either. The result type is
+ * necessarily composite, and composite types never have a collation.
+ */
+
+ /* how to display this node */
+ CoercionForm row_format pg_node_attr(query_jumble_ignore);
+
+ /* list of String, or NIL */
+ List *colnames pg_node_attr(query_jumble_ignore);
+
+ int location; /* token location, or -1 if unknown */
+} RowExpr;
+
+/*
+ * RowCompareExpr - row-wise comparison, such as (a, b) <= (1, 2)
+ *
+ * We support row comparison for any operator that can be determined to
+ * act like =, <>, <, <=, >, or >= (we determine this by looking for the
+ * operator in btree opfamilies). Note that the same operator name might
+ * map to a different operator for each pair of row elements, since the
+ * element datatypes can vary.
+ *
+ * A RowCompareExpr node is only generated for the < <= > >= cases;
+ * the = and <> cases are translated to simple AND or OR combinations
+ * of the pairwise comparisons. However, we include = and <> in the
+ * RowCompareType enum for the convenience of parser logic.
+ */
+typedef enum RowCompareType
+{
+ /* Values of this enum are chosen to match btree strategy numbers */
+ ROWCOMPARE_LT = 1, /* BTLessStrategyNumber */
+ ROWCOMPARE_LE = 2, /* BTLessEqualStrategyNumber */
+ ROWCOMPARE_EQ = 3, /* BTEqualStrategyNumber */
+ ROWCOMPARE_GE = 4, /* BTGreaterEqualStrategyNumber */
+ ROWCOMPARE_GT = 5, /* BTGreaterStrategyNumber */
+ ROWCOMPARE_NE = 6 /* no such btree strategy */
+} RowCompareType;
+
+typedef struct RowCompareExpr
+{
+ Expr xpr;
+
+ /* LT LE GE or GT, never EQ or NE */
+ RowCompareType rctype;
+ /* OID list of pairwise comparison ops */
+ List *opnos pg_node_attr(query_jumble_ignore);
+ /* OID list of containing operator families */
+ List *opfamilies pg_node_attr(query_jumble_ignore);
+ /* OID list of collations for comparisons */
+ List *inputcollids pg_node_attr(query_jumble_ignore);
+ /* the left-hand input arguments */
+ List *largs;
+ /* the right-hand input arguments */
+ List *rargs;
+} RowCompareExpr;
+
+/*
+ * CoalesceExpr - a COALESCE expression
+ */
+typedef struct CoalesceExpr
+{
+ Expr xpr;
+ /* type of expression result */
+ Oid coalescetype pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid coalescecollid pg_node_attr(query_jumble_ignore);
+ /* the arguments */
+ List *args;
+ /* token location, or -1 if unknown */
+ int location;
+} CoalesceExpr;
+
+/*
+ * MinMaxExpr - a GREATEST or LEAST function
+ */
+typedef enum MinMaxOp
+{
+ IS_GREATEST,
+ IS_LEAST
+} MinMaxOp;
+
+typedef struct MinMaxExpr
+{
+ Expr xpr;
+ /* common type of arguments and result */
+ Oid minmaxtype pg_node_attr(query_jumble_ignore);
+ /* OID of collation of result */
+ Oid minmaxcollid pg_node_attr(query_jumble_ignore);
+ /* OID of collation that function should use */
+ Oid inputcollid pg_node_attr(query_jumble_ignore);
+ /* function to execute */
+ MinMaxOp op;
+ /* the arguments */
+ List *args;
+ /* token location, or -1 if unknown */
+ int location;
+} MinMaxExpr;
+
+/*
+ * SQLValueFunction - parameterless functions with special grammar productions
+ *
+ * The SQL standard categorizes some of these as
+ * and others as . We call 'em SQLValueFunctions
+ * for lack of a better term. We store type and typmod of the result so that
+ * some code doesn't need to know each function individually, and because
+ * we would need to store typmod anyway for some of the datetime functions.
+ * Note that currently, all variants return non-collating datatypes, so we do
+ * not need a collation field; also, all these functions are stable.
+ */
+typedef enum SQLValueFunctionOp
+{
+ SVFOP_CURRENT_DATE,
+ SVFOP_CURRENT_TIME,
+ SVFOP_CURRENT_TIME_N,
+ SVFOP_CURRENT_TIMESTAMP,
+ SVFOP_CURRENT_TIMESTAMP_N,
+ SVFOP_LOCALTIME,
+ SVFOP_LOCALTIME_N,
+ SVFOP_LOCALTIMESTAMP,
+ SVFOP_LOCALTIMESTAMP_N,
+ SVFOP_CURRENT_ROLE,
+ SVFOP_CURRENT_USER,
+ SVFOP_USER,
+ SVFOP_SESSION_USER,
+ SVFOP_CURRENT_CATALOG,
+ SVFOP_CURRENT_SCHEMA
+} SQLValueFunctionOp;
+
+typedef struct SQLValueFunction
+{
+ Expr xpr;
+ SQLValueFunctionOp op; /* which function this is */
+
+ /*
+ * Result type/typmod. Type is fully determined by "op", so no need to
+ * include this Oid in the query jumbling.
+ */
+ Oid type pg_node_attr(query_jumble_ignore);
+ int32 typmod;
+ int location; /* token location, or -1 if unknown */
+} SQLValueFunction;
+
+/*
+ * XmlExpr - various SQL/XML functions requiring special grammar productions
+ *
+ * 'name' carries the "NAME foo" argument (already XML-escaped).
+ * 'named_args' and 'arg_names' represent an xml_attribute list.
+ * 'args' carries all other arguments.
+ *
+ * Note: result type/typmod/collation are not stored, but can be deduced
+ * from the XmlExprOp. The type/typmod fields are just used for display
+ * purposes, and are NOT necessarily the true result type of the node.
+ */
+typedef enum XmlExprOp
+{
+ IS_XMLCONCAT, /* XMLCONCAT(args) */
+ IS_XMLELEMENT, /* XMLELEMENT(name, xml_attributes, args) */
+ IS_XMLFOREST, /* XMLFOREST(xml_attributes) */
+ IS_XMLPARSE, /* XMLPARSE(text, is_doc, preserve_ws) */
+ IS_XMLPI, /* XMLPI(name [, args]) */
+ IS_XMLROOT, /* XMLROOT(xml, version, standalone) */
+ IS_XMLSERIALIZE, /* XMLSERIALIZE(is_document, xmlval, indent) */
+ IS_DOCUMENT /* xmlval IS DOCUMENT */
+} XmlExprOp;
+
+typedef enum XmlOptionType
+{
+ XMLOPTION_DOCUMENT,
+ XMLOPTION_CONTENT
+} XmlOptionType;
+
+typedef struct XmlExpr
+{
+ Expr xpr;
+ /* xml function ID */
+ XmlExprOp op;
+ /* name in xml(NAME foo ...) syntaxes */
+ char *name pg_node_attr(query_jumble_ignore);
+ /* non-XML expressions for xml_attributes */
+ List *named_args;
+ /* parallel list of String values */
+ List *arg_names pg_node_attr(query_jumble_ignore);
+ /* list of expressions */
+ List *args;
+ /* DOCUMENT or CONTENT */
+ XmlOptionType xmloption pg_node_attr(query_jumble_ignore);
+ /* INDENT option for XMLSERIALIZE */
+ bool indent;
+ /* target type/typmod for XMLSERIALIZE */
+ Oid type pg_node_attr(query_jumble_ignore);
+ int32 typmod pg_node_attr(query_jumble_ignore);
+ /* token location, or -1 if unknown */
+ int location;
+} XmlExpr;
+
+/*
+ * JsonEncoding -
+ * representation of JSON ENCODING clause
+ */
+typedef enum JsonEncoding
+{
+ JS_ENC_DEFAULT, /* unspecified */
+ JS_ENC_UTF8,
+ JS_ENC_UTF16,
+ JS_ENC_UTF32,
+} JsonEncoding;
+
+/*
+ * JsonFormatType -
+ * enumeration of JSON formats used in JSON FORMAT clause
+ */
+typedef enum JsonFormatType
+{
+ JS_FORMAT_DEFAULT, /* unspecified */
+ JS_FORMAT_JSON, /* FORMAT JSON [ENCODING ...] */
+ JS_FORMAT_JSONB /* implicit internal format for RETURNING
+ * jsonb */
+} JsonFormatType;
+
+/*
+ * JsonFormat -
+ * representation of JSON FORMAT clause
+ */
+typedef struct JsonFormat
+{
+ NodeTag type;
+ JsonFormatType format_type; /* format type */
+ JsonEncoding encoding; /* JSON encoding */
+ int location; /* token location, or -1 if unknown */
+} JsonFormat;
+
+/*
+ * JsonReturning -
+ * transformed representation of JSON RETURNING clause
+ */
+typedef struct JsonReturning
+{
+ NodeTag type;
+ JsonFormat *format; /* output JSON format */
+ Oid typid; /* target type Oid */
+ int32 typmod; /* target type modifier */
+} JsonReturning;
+
+/*
+ * JsonValueExpr -
+ * representation of JSON value expression (expr [FORMAT JsonFormat])
+ *
+ * The actual value is obtained by evaluating formatted_expr. raw_expr is
+ * only there for displaying the original user-written expression and is not
+ * evaluated by ExecInterpExpr() and eval_const_exprs_mutator().
+ */
+typedef struct JsonValueExpr
+{
+ NodeTag type;
+ Expr *raw_expr; /* raw expression */
+ Expr *formatted_expr; /* formatted expression */
+ JsonFormat *format; /* FORMAT clause, if specified */
+} JsonValueExpr;
+
+typedef enum JsonConstructorType
+{
+ JSCTOR_JSON_OBJECT = 1,
+ JSCTOR_JSON_ARRAY = 2,
+ JSCTOR_JSON_OBJECTAGG = 3,
+ JSCTOR_JSON_ARRAYAGG = 4
+} JsonConstructorType;
+
+/*
+ * JsonConstructorExpr -
+ * wrapper over FuncExpr/Aggref/WindowFunc for SQL/JSON constructors
+ */
+typedef struct JsonConstructorExpr
+{
+ Expr xpr;
+ JsonConstructorType type; /* constructor type */
+ List *args;
+ Expr *func; /* underlying json[b]_xxx() function call */
+ Expr *coercion; /* coercion to RETURNING type */
+ JsonReturning *returning; /* RETURNING clause */
+ bool absent_on_null; /* ABSENT ON NULL? */
+ bool unique; /* WITH UNIQUE KEYS? (JSON_OBJECT[AGG] only) */
+ int location;
+} JsonConstructorExpr;
+
+/*
+ * JsonValueType -
+ * representation of JSON item type in IS JSON predicate
+ */
+typedef enum JsonValueType
+{
+ JS_TYPE_ANY, /* IS JSON [VALUE] */
+ JS_TYPE_OBJECT, /* IS JSON OBJECT */
+ JS_TYPE_ARRAY, /* IS JSON ARRAY */
+ JS_TYPE_SCALAR /* IS JSON SCALAR */
+} JsonValueType;
+
+/*
+ * JsonIsPredicate -
+ * representation of IS JSON predicate
+ */
+typedef struct JsonIsPredicate
+{
+ NodeTag type;
+ Node *expr; /* subject expression */
+ JsonFormat *format; /* FORMAT clause, if specified */
+ JsonValueType item_type; /* JSON item type */
+ bool unique_keys; /* check key uniqueness? */
+ int location; /* token location, or -1 if unknown */
+} JsonIsPredicate;
+
+/* ----------------
+ * NullTest
+ *
+ * NullTest represents the operation of testing a value for NULLness.
+ * The appropriate test is performed and returned as a boolean Datum.
+ *
+ * When argisrow is false, this simply represents a test for the null value.
+ *
+ * When argisrow is true, the input expression must yield a rowtype, and
+ * the node implements "row IS [NOT] NULL" per the SQL standard. This
+ * includes checking individual fields for NULLness when the row datum
+ * itself isn't NULL.
+ *
+ * NOTE: the combination of a rowtype input and argisrow==false does NOT
+ * correspond to the SQL notation "row IS [NOT] NULL"; instead, this case
+ * represents the SQL notation "row IS [NOT] DISTINCT FROM NULL".
+ * ----------------
+ */
+
+typedef enum NullTestType
+{
+ IS_NULL, IS_NOT_NULL
+} NullTestType;
+
+typedef struct NullTest
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ NullTestType nulltesttype; /* IS NULL, IS NOT NULL */
+ /* T to perform field-by-field null checks */
+ bool argisrow pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+} NullTest;
+
+/*
+ * BooleanTest
+ *
+ * BooleanTest represents the operation of determining whether a boolean
+ * is TRUE, FALSE, or UNKNOWN (ie, NULL). All six meaningful combinations
+ * are supported. Note that a NULL input does *not* cause a NULL result.
+ * The appropriate test is performed and returned as a boolean Datum.
+ */
+
+typedef enum BoolTestType
+{
+ IS_TRUE, IS_NOT_TRUE, IS_FALSE, IS_NOT_FALSE, IS_UNKNOWN, IS_NOT_UNKNOWN
+} BoolTestType;
+
+typedef struct BooleanTest
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ BoolTestType booltesttype; /* test type */
+ int location; /* token location, or -1 if unknown */
+} BooleanTest;
+
+/*
+ * CoerceToDomain
+ *
+ * CoerceToDomain represents the operation of coercing a value to a domain
+ * type. At runtime (and not before) the precise set of constraints to be
+ * checked will be determined. If the value passes, it is returned as the
+ * result; if not, an error is raised. Note that this is equivalent to
+ * RelabelType in the scenario where no constraints are applied.
+ */
+typedef struct CoerceToDomain
+{
+ Expr xpr;
+ Expr *arg; /* input expression */
+ Oid resulttype; /* domain type ID (result type) */
+ /* output typmod (currently always -1) */
+ int32 resulttypmod pg_node_attr(query_jumble_ignore);
+ /* OID of collation, or InvalidOid if none */
+ Oid resultcollid pg_node_attr(query_jumble_ignore);
+ /* how to display this node */
+ CoercionForm coercionformat pg_node_attr(query_jumble_ignore);
+ int location; /* token location, or -1 if unknown */
+} CoerceToDomain;
+
+/*
+ * Placeholder node for the value to be processed by a domain's check
+ * constraint. This is effectively like a Param, but can be implemented more
+ * simply since we need only one replacement value at a time.
+ *
+ * Note: the typeId/typeMod/collation will be set from the domain's base type,
+ * not the domain itself. This is because we shouldn't consider the value
+ * to be a member of the domain if we haven't yet checked its constraints.
+ */
+typedef struct CoerceToDomainValue
+{
+ Expr xpr;
+ /* type for substituted value */
+ Oid typeId;
+ /* typemod for substituted value */
+ int32 typeMod pg_node_attr(query_jumble_ignore);
+ /* collation for the substituted value */
+ Oid collation pg_node_attr(query_jumble_ignore);
+ /* token location, or -1 if unknown */
+ int location;
+} CoerceToDomainValue;
+
+/*
+ * Placeholder node for a DEFAULT marker in an INSERT or UPDATE command.
+ *
+ * This is not an executable expression: it must be replaced by the actual
+ * column default expression during rewriting. But it is convenient to
+ * treat it as an expression node during parsing and rewriting.
+ */
+typedef struct SetToDefault
+{
+ Expr xpr;
+ /* type for substituted value */
+ Oid typeId;
+ /* typemod for substituted value */
+ int32 typeMod pg_node_attr(query_jumble_ignore);
+ /* collation for the substituted value */
+ Oid collation pg_node_attr(query_jumble_ignore);
+ /* token location, or -1 if unknown */
+ int location;
+} SetToDefault;
+
+/*
+ * Node representing [WHERE] CURRENT OF cursor_name
+ *
+ * CURRENT OF is a bit like a Var, in that it carries the rangetable index
+ * of the target relation being constrained; this aids placing the expression
+ * correctly during planning. We can assume however that its "levelsup" is
+ * always zero, due to the syntactic constraints on where it can appear.
+ * Also, cvarno will always be a true RT index, never INNER_VAR etc.
+ *
+ * The referenced cursor can be represented either as a hardwired string
+ * or as a reference to a run-time parameter of type REFCURSOR. The latter
+ * case is for the convenience of plpgsql.
+ */
+typedef struct CurrentOfExpr
+{
+ Expr xpr;
+ Index cvarno; /* RT index of target relation */
+ char *cursor_name; /* name of referenced cursor, or NULL */
+ int cursor_param; /* refcursor parameter number, or 0 */
+} CurrentOfExpr;
+
+/*
+ * NextValueExpr - get next value from sequence
+ *
+ * This has the same effect as calling the nextval() function, but it does not
+ * check permissions on the sequence. This is used for identity columns,
+ * where the sequence is an implicit dependency without its own permissions.
+ */
+typedef struct NextValueExpr
+{
+ Expr xpr;
+ Oid seqid;
+ Oid typeId;
+} NextValueExpr;
+
+/*
+ * InferenceElem - an element of a unique index inference specification
+ *
+ * This mostly matches the structure of IndexElems, but having a dedicated
+ * primnode allows for a clean separation between the use of index parameters
+ * by utility commands, and this node.
+ */
+typedef struct InferenceElem
+{
+ Expr xpr;
+ Node *expr; /* expression to infer from, or NULL */
+ Oid infercollid; /* OID of collation, or InvalidOid */
+ Oid inferopclass; /* OID of att opclass, or InvalidOid */
+} InferenceElem;
+
+/*--------------------
+ * TargetEntry -
+ * a target entry (used in query target lists)
+ *
+ * Strictly speaking, a TargetEntry isn't an expression node (since it can't
+ * be evaluated by ExecEvalExpr). But we treat it as one anyway, since in
+ * very many places it's convenient to process a whole query targetlist as a
+ * single expression tree.
+ *
+ * In a SELECT's targetlist, resno should always be equal to the item's
+ * ordinal position (counting from 1). However, in an INSERT or UPDATE
+ * targetlist, resno represents the attribute number of the destination
+ * column for the item; so there may be missing or out-of-order resnos.
+ * It is even legal to have duplicated resnos; consider
+ * UPDATE table SET arraycol[1] = ..., arraycol[2] = ..., ...
+ * In an INSERT, the rewriter and planner will normalize the tlist by
+ * reordering it into physical column order and filling in default values
+ * for any columns not assigned values by the original query. In an UPDATE,
+ * after the rewriter merges multiple assignments for the same column, the
+ * planner extracts the target-column numbers into a separate "update_colnos"
+ * list, and then renumbers the tlist elements serially. Thus, tlist resnos
+ * match ordinal position in all tlists seen by the executor; but it is wrong
+ * to assume that before planning has happened.
+ *
+ * resname is required to represent the correct column name in non-resjunk
+ * entries of top-level SELECT targetlists, since it will be used as the
+ * column title sent to the frontend. In most other contexts it is only
+ * a debugging aid, and may be wrong or even NULL. (In particular, it may
+ * be wrong in a tlist from a stored rule, if the referenced column has been
+ * renamed by ALTER TABLE since the rule was made. Also, the planner tends
+ * to store NULL rather than look up a valid name for tlist entries in
+ * non-toplevel plan nodes.) In resjunk entries, resname should be either
+ * a specific system-generated name (such as "ctid") or NULL; anything else
+ * risks confusing ExecGetJunkAttribute!
+ *
+ * ressortgroupref is used in the representation of ORDER BY, GROUP BY, and
+ * DISTINCT items. Targetlist entries with ressortgroupref=0 are not
+ * sort/group items. If ressortgroupref>0, then this item is an ORDER BY,
+ * GROUP BY, and/or DISTINCT target value. No two entries in a targetlist
+ * may have the same nonzero ressortgroupref --- but there is no particular
+ * meaning to the nonzero values, except as tags. (For example, one must
+ * not assume that lower ressortgroupref means a more significant sort key.)
+ * The order of the associated SortGroupClause lists determine the semantics.
+ *
+ * resorigtbl/resorigcol identify the source of the column, if it is a
+ * simple reference to a column of a base table (or view). If it is not
+ * a simple reference, these fields are zeroes.
+ *
+ * If resjunk is true then the column is a working column (such as a sort key)
+ * that should be removed from the final output of the query. Resjunk columns
+ * must have resnos that cannot duplicate any regular column's resno. Also
+ * note that there are places that assume resjunk columns come after non-junk
+ * columns.
+ *--------------------
+ */
+typedef struct TargetEntry
+{
+ Expr xpr;
+ /* expression to evaluate */
+ Expr *expr;
+ /* attribute number (see notes above) */
+ AttrNumber resno;
+ /* name of the column (could be NULL) */
+ char *resname pg_node_attr(query_jumble_ignore);
+ /* nonzero if referenced by a sort/group clause */
+ Index ressortgroupref;
+ /* OID of column's source table */
+ Oid resorigtbl pg_node_attr(query_jumble_ignore);
+ /* column's number in source table */
+ AttrNumber resorigcol pg_node_attr(query_jumble_ignore);
+ /* set to true to eliminate the attribute from final target list */
+ bool resjunk pg_node_attr(query_jumble_ignore);
+} TargetEntry;
+
+
+/* ----------------------------------------------------------------
+ * node types for join trees
+ *
+ * The leaves of a join tree structure are RangeTblRef nodes. Above
+ * these, JoinExpr nodes can appear to denote a specific kind of join
+ * or qualified join. Also, FromExpr nodes can appear to denote an
+ * ordinary cross-product join ("FROM foo, bar, baz WHERE ...").
+ * FromExpr is like a JoinExpr of jointype JOIN_INNER, except that it
+ * may have any number of child nodes, not just two.
+ *
+ * NOTE: the top level of a Query's jointree is always a FromExpr.
+ * Even if the jointree contains no rels, there will be a FromExpr.
+ *
+ * NOTE: the qualification expressions present in JoinExpr nodes are
+ * *in addition to* the query's main WHERE clause, which appears as the
+ * qual of the top-level FromExpr. The reason for associating quals with
+ * specific nodes in the jointree is that the position of a qual is critical
+ * when outer joins are present. (If we enforce a qual too soon or too late,
+ * that may cause the outer join to produce the wrong set of NULL-extended
+ * rows.) If all joins are inner joins then all the qual positions are
+ * semantically interchangeable.
+ *
+ * NOTE: in the raw output of gram.y, a join tree contains RangeVar,
+ * RangeSubselect, and RangeFunction nodes, which are all replaced by
+ * RangeTblRef nodes during the parse analysis phase. Also, the top-level
+ * FromExpr is added during parse analysis; the grammar regards FROM and
+ * WHERE as separate.
+ * ----------------------------------------------------------------
+ */
+
+/*
+ * RangeTblRef - reference to an entry in the query's rangetable
+ *
+ * We could use direct pointers to the RT entries and skip having these
+ * nodes, but multiple pointers to the same node in a querytree cause
+ * lots of headaches, so it seems better to store an index into the RT.
+ */
+typedef struct RangeTblRef
+{
+ NodeTag type;
+ int rtindex;
+} RangeTblRef;
+
+/*----------
+ * JoinExpr - for SQL JOIN expressions
+ *
+ * isNatural, usingClause, and quals are interdependent. The user can write
+ * only one of NATURAL, USING(), or ON() (this is enforced by the grammar).
+ * If he writes NATURAL then parse analysis generates the equivalent USING()
+ * list, and from that fills in "quals" with the right equality comparisons.
+ * If he writes USING() then "quals" is filled with equality comparisons.
+ * If he writes ON() then only "quals" is set. Note that NATURAL/USING
+ * are not equivalent to ON() since they also affect the output column list.
+ *
+ * alias is an Alias node representing the AS alias-clause attached to the
+ * join expression, or NULL if no clause. NB: presence or absence of the
+ * alias has a critical impact on semantics, because a join with an alias
+ * restricts visibility of the tables/columns inside it.
+ *
+ * join_using_alias is an Alias node representing the join correlation
+ * name that SQL:2016 and later allow to be attached to JOIN/USING.
+ * Its column alias list includes only the common column names from USING,
+ * and it does not restrict visibility of the join's input tables.
+ *
+ * During parse analysis, an RTE is created for the Join, and its index
+ * is filled into rtindex. This RTE is present mainly so that Vars can
+ * be created that refer to the outputs of the join. The planner sometimes
+ * generates JoinExprs internally; these can have rtindex = 0 if there are
+ * no join alias variables referencing such joins.
+ *----------
+ */
+typedef struct JoinExpr
+{
+ NodeTag type;
+ JoinType jointype; /* type of join */
+ bool isNatural; /* Natural join? Will need to shape table */
+ Node *larg; /* left subtree */
+ Node *rarg; /* right subtree */
+ /* USING clause, if any (list of String) */
+ List *usingClause pg_node_attr(query_jumble_ignore);
+ /* alias attached to USING clause, if any */
+ Alias *join_using_alias pg_node_attr(query_jumble_ignore);
+ /* qualifiers on join, if any */
+ Node *quals;
+ /* user-written alias clause, if any */
+ Alias *alias pg_node_attr(query_jumble_ignore);
+ /* RT index assigned for join, or 0 */
+ int rtindex;
+} JoinExpr;
+
+/*----------
+ * FromExpr - represents a FROM ... WHERE ... construct
+ *
+ * This is both more flexible than a JoinExpr (it can have any number of
+ * children, including zero) and less so --- we don't need to deal with
+ * aliases and so on. The output column set is implicitly just the union
+ * of the outputs of the children.
+ *----------
+ */
+typedef struct FromExpr
+{
+ NodeTag type;
+ List *fromlist; /* List of join subtrees */
+ Node *quals; /* qualifiers on join, if any */
+} FromExpr;
+
+/*----------
+ * OnConflictExpr - represents an ON CONFLICT DO ... expression
+ *
+ * The optimizer requires a list of inference elements, and optionally a WHERE
+ * clause to infer a unique index. The unique index (or, occasionally,
+ * indexes) inferred are used to arbitrate whether or not the alternative ON
+ * CONFLICT path is taken.
+ *----------
+ */
+typedef struct OnConflictExpr
+{
+ NodeTag type;
+ OnConflictAction action; /* DO NOTHING or UPDATE? */
+
+ /* Arbiter */
+ List *arbiterElems; /* unique index arbiter list (of
+ * InferenceElem's) */
+ Node *arbiterWhere; /* unique index arbiter WHERE clause */
+ Oid constraint; /* pg_constraint OID for arbiter */
+
+ /* ON CONFLICT UPDATE */
+ List *onConflictSet; /* List of ON CONFLICT SET TargetEntrys */
+ Node *onConflictWhere; /* qualifiers to restrict UPDATE to */
+ int exclRelIndex; /* RT index of 'excluded' relation */
+ List *exclRelTlist; /* tlist of the EXCLUDED pseudo relation */
+} OnConflictExpr;
+
+#endif /* PRIMNODES_H */
diff --git a/pgsql/include/server/nodes/print.h b/pgsql/include/server/nodes/print.h
new file mode 100644
index 0000000000000000000000000000000000000000..3c0473fd4c2a5a8fecec86e4aa3936be2e4b7637
--- /dev/null
+++ b/pgsql/include/server/nodes/print.h
@@ -0,0 +1,34 @@
+/*-------------------------------------------------------------------------
+ *
+ * print.h
+ * definitions for nodes/print.c
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/print.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PRINT_H
+#define PRINT_H
+
+#include "executor/tuptable.h"
+
+
+#define nodeDisplay(x) pprint(x)
+
+extern void print(const void *obj);
+extern void pprint(const void *obj);
+extern void elog_node_display(int lev, const char *title,
+ const void *obj, bool pretty);
+extern char *format_node_dump(const char *dump);
+extern char *pretty_format_node_dump(const char *dump);
+extern void print_rt(const List *rtable);
+extern void print_expr(const Node *expr, const List *rtable);
+extern void print_pathkeys(const List *pathkeys, const List *rtable);
+extern void print_tl(const List *tlist, const List *rtable);
+extern void print_slot(TupleTableSlot *slot);
+
+#endif /* PRINT_H */
diff --git a/pgsql/include/server/nodes/queryjumble.h b/pgsql/include/server/nodes/queryjumble.h
new file mode 100644
index 0000000000000000000000000000000000000000..7649e095aa57239a3791fedd96d6b51217686ee9
--- /dev/null
+++ b/pgsql/include/server/nodes/queryjumble.h
@@ -0,0 +1,86 @@
+/*-------------------------------------------------------------------------
+ *
+ * queryjumble.h
+ * Query normalization and fingerprinting.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/nodes/queryjumble.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef QUERYJUMBLE_H
+#define QUERYJUMBLE_H
+
+#include "nodes/parsenodes.h"
+
+/*
+ * Struct for tracking locations/lengths of constants during normalization
+ */
+typedef struct LocationLen
+{
+ int location; /* start offset in query text */
+ int length; /* length in bytes, or -1 to ignore */
+} LocationLen;
+
+/*
+ * Working state for computing a query jumble and producing a normalized
+ * query string
+ */
+typedef struct JumbleState
+{
+ /* Jumble of current query tree */
+ unsigned char *jumble;
+
+ /* Number of bytes used in jumble[] */
+ Size jumble_len;
+
+ /* Array of locations of constants that should be removed */
+ LocationLen *clocations;
+
+ /* Allocated length of clocations array */
+ int clocations_buf_size;
+
+ /* Current number of valid entries in clocations array */
+ int clocations_count;
+
+ /* highest Param id we've seen, in order to start normalization correctly */
+ int highest_extern_param_id;
+} JumbleState;
+
+/* Values for the compute_query_id GUC */
+enum ComputeQueryIdType
+{
+ COMPUTE_QUERY_ID_OFF,
+ COMPUTE_QUERY_ID_ON,
+ COMPUTE_QUERY_ID_AUTO,
+ COMPUTE_QUERY_ID_REGRESS
+};
+
+/* GUC parameters */
+extern PGDLLIMPORT int compute_query_id;
+
+
+extern const char *CleanQuerytext(const char *query, int *location, int *len);
+extern JumbleState *JumbleQuery(Query *query);
+extern void EnableQueryId(void);
+
+extern PGDLLIMPORT bool query_id_enabled;
+
+/*
+ * Returns whether query identifier computation has been enabled, either
+ * directly in the GUC or by a module when the setting is 'auto'.
+ */
+static inline bool
+IsQueryIdEnabled(void)
+{
+ if (compute_query_id == COMPUTE_QUERY_ID_OFF)
+ return false;
+ if (compute_query_id == COMPUTE_QUERY_ID_ON)
+ return true;
+ return query_id_enabled;
+}
+
+#endif /* QUERYJUMBLE_H */
diff --git a/pgsql/include/server/nodes/readfuncs.h b/pgsql/include/server/nodes/readfuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..cba6f0be75a74f9245677f838d573883fb6a9954
--- /dev/null
+++ b/pgsql/include/server/nodes/readfuncs.h
@@ -0,0 +1,38 @@
+/*-------------------------------------------------------------------------
+ *
+ * readfuncs.h
+ * header file for read.c and readfuncs.c. These functions are internal
+ * to the stringToNode interface and should not be used by anyone else.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/readfuncs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef READFUNCS_H
+#define READFUNCS_H
+
+#include "nodes/nodes.h"
+
+/*
+ * variable in read.c that needs to be accessible to readfuncs.c
+ */
+#ifdef WRITE_READ_PARSE_PLAN_TREES
+extern PGDLLIMPORT bool restore_location_fields;
+#endif
+
+/*
+ * prototypes for functions in read.c (the lisp token parser)
+ */
+extern const char *pg_strtok(int *length);
+extern char *debackslash(const char *token, int length);
+extern void *nodeRead(const char *token, int tok_len);
+
+/*
+ * prototypes for functions in readfuncs.c
+ */
+extern Node *parseNodeString(void);
+
+#endif /* READFUNCS_H */
diff --git a/pgsql/include/server/nodes/replnodes.h b/pgsql/include/server/nodes/replnodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..4321ba8f866a34e7d428e4c9a55996efec61f5c0
--- /dev/null
+++ b/pgsql/include/server/nodes/replnodes.h
@@ -0,0 +1,111 @@
+/*-------------------------------------------------------------------------
+ *
+ * replnodes.h
+ * definitions for replication grammar parse nodes
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/replnodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REPLNODES_H
+#define REPLNODES_H
+
+#include "access/xlogdefs.h"
+#include "nodes/pg_list.h"
+
+typedef enum ReplicationKind
+{
+ REPLICATION_KIND_PHYSICAL,
+ REPLICATION_KIND_LOGICAL
+} ReplicationKind;
+
+
+/* ----------------------
+ * IDENTIFY_SYSTEM command
+ * ----------------------
+ */
+typedef struct IdentifySystemCmd
+{
+ NodeTag type;
+} IdentifySystemCmd;
+
+
+/* ----------------------
+ * BASE_BACKUP command
+ * ----------------------
+ */
+typedef struct BaseBackupCmd
+{
+ NodeTag type;
+ List *options;
+} BaseBackupCmd;
+
+
+/* ----------------------
+ * CREATE_REPLICATION_SLOT command
+ * ----------------------
+ */
+typedef struct CreateReplicationSlotCmd
+{
+ NodeTag type;
+ char *slotname;
+ ReplicationKind kind;
+ char *plugin;
+ bool temporary;
+ List *options;
+} CreateReplicationSlotCmd;
+
+
+/* ----------------------
+ * DROP_REPLICATION_SLOT command
+ * ----------------------
+ */
+typedef struct DropReplicationSlotCmd
+{
+ NodeTag type;
+ char *slotname;
+ bool wait;
+} DropReplicationSlotCmd;
+
+
+/* ----------------------
+ * START_REPLICATION command
+ * ----------------------
+ */
+typedef struct StartReplicationCmd
+{
+ NodeTag type;
+ ReplicationKind kind;
+ char *slotname;
+ TimeLineID timeline;
+ XLogRecPtr startpoint;
+ List *options;
+} StartReplicationCmd;
+
+
+/* ----------------------
+ * READ_REPLICATION_SLOT command
+ * ----------------------
+ */
+typedef struct ReadReplicationSlotCmd
+{
+ NodeTag type;
+ char *slotname;
+} ReadReplicationSlotCmd;
+
+
+/* ----------------------
+ * TIMELINE_HISTORY command
+ * ----------------------
+ */
+typedef struct TimeLineHistoryCmd
+{
+ NodeTag type;
+ TimeLineID timeline;
+} TimeLineHistoryCmd;
+
+#endif /* REPLNODES_H */
diff --git a/pgsql/include/server/nodes/subscripting.h b/pgsql/include/server/nodes/subscripting.h
new file mode 100644
index 0000000000000000000000000000000000000000..02d98f2e47fc29b2c1b9721d869637d269240f5a
--- /dev/null
+++ b/pgsql/include/server/nodes/subscripting.h
@@ -0,0 +1,167 @@
+/*-------------------------------------------------------------------------
+ *
+ * subscripting.h
+ * API for generic type subscripting
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/subscripting.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SUBSCRIPTING_H
+#define SUBSCRIPTING_H
+
+#include "nodes/primnodes.h"
+
+/* Forward declarations, to avoid including other headers */
+struct ParseState;
+struct SubscriptingRefState;
+struct SubscriptExecSteps;
+
+/*
+ * The SQL-visible function that defines a subscripting method is declared
+ * subscripting_function(internal) returns internal
+ * but it actually is not passed any parameter. It must return a pointer
+ * to a "struct SubscriptRoutines" that provides pointers to the individual
+ * subscript parsing and execution methods. Typically the pointer will point
+ * to a "static const" variable, but at need it can point to palloc'd space.
+ * The type (after domain-flattening) of the head variable or expression
+ * of a subscripting construct determines which subscripting function is
+ * called for that construct.
+ *
+ * In addition to the method pointers, struct SubscriptRoutines includes
+ * several bool flags that specify properties of the subscripting actions
+ * this data type can perform:
+ *
+ * fetch_strict indicates that a fetch SubscriptRef is strict, i.e., returns
+ * NULL if any input (either the container or any subscript) is NULL.
+ *
+ * fetch_leakproof indicates that a fetch SubscriptRef is leakproof, i.e.,
+ * will not throw any data-value-dependent errors. Typically this requires
+ * silently returning NULL for invalid subscripts.
+ *
+ * store_leakproof similarly indicates whether an assignment SubscriptRef is
+ * leakproof. (It is common to prefer throwing errors for invalid subscripts
+ * in assignments; that's fine, but it makes the operation not leakproof.
+ * In current usage there is no advantage in making assignments leakproof.)
+ *
+ * There is no store_strict flag. Such behavior would generally be
+ * undesirable, since for example a null subscript in an assignment would
+ * cause the entire container to become NULL.
+ *
+ * Regardless of these flags, all SubscriptRefs are expected to be immutable,
+ * that is they must always give the same results for the same inputs.
+ * They are expected to always be parallel-safe, as well.
+ */
+
+/*
+ * The transform method is called during parse analysis of a subscripting
+ * construct. The SubscriptingRef node has been constructed, but some of
+ * its fields still need to be filled in, and the subscript expression(s)
+ * are still in raw form. The transform method is responsible for doing
+ * parse analysis of each subscript expression (using transformExpr),
+ * coercing the subscripts to whatever type it needs, and building the
+ * refupperindexpr and reflowerindexpr lists from those results. The
+ * reflowerindexpr list must be empty for an element operation, or the
+ * same length as refupperindexpr for a slice operation. Insert NULLs
+ * (that is, an empty parse tree, not a null Const node) for any omitted
+ * subscripts in a slice operation. (Of course, if the transform method
+ * does not care to support slicing, it can just throw an error if isSlice.)
+ * See array_subscript_transform() for sample code.
+ *
+ * The transform method is also responsible for identifying the result type
+ * of the subscripting operation. At call, refcontainertype and reftypmod
+ * describe the container type (this will be a base type not a domain), and
+ * refelemtype is set to the container type's pg_type.typelem value. The
+ * transform method must set refrestype and reftypmod to describe the result
+ * of subscripting. For arrays, refrestype is set to refelemtype for an
+ * element operation or refcontainertype for a slice, while reftypmod stays
+ * the same in either case; but other types might use other rules. The
+ * transform method should ignore refcollid, as that's determined later on
+ * during parsing.
+ *
+ * At call, refassgnexpr has not been filled in, so the SubscriptingRef node
+ * always looks like a fetch; refrestype should be set as though for a
+ * fetch, too. (The isAssignment parameter is typically only useful if the
+ * transform method wishes to throw an error for not supporting assignment.)
+ * To complete processing of an assignment, the core parser will coerce the
+ * element/slice source expression to the returned refrestype and reftypmod
+ * before putting it into refassgnexpr. It will then set refrestype and
+ * reftypmod to again describe the container type, since that's what an
+ * assignment must return.
+ */
+typedef void (*SubscriptTransform) (SubscriptingRef *sbsref,
+ List *indirection,
+ struct ParseState *pstate,
+ bool isSlice,
+ bool isAssignment);
+
+/*
+ * The exec_setup method is called during executor-startup compilation of a
+ * SubscriptingRef node in an expression. It must fill *methods with pointers
+ * to functions that can be called for execution of the node. Optionally,
+ * exec_setup can initialize sbsrefstate->workspace to point to some palloc'd
+ * workspace for execution. (Typically, such workspace is used to hold
+ * looked-up catalog data and/or provide space for the check_subscripts step
+ * to pass data forward to the other step functions.) See executor/execExpr.h
+ * for the definitions of these structs and other ones used in expression
+ * execution.
+ *
+ * The methods to be provided are:
+ *
+ * sbs_check_subscripts: examine the just-computed subscript values available
+ * in sbsrefstate's arrays, and possibly convert them into another form
+ * (stored in sbsrefstate->workspace). Return TRUE to continue with
+ * evaluation of the subscripting construct, or FALSE to skip it and return an
+ * overall NULL result. If this is a fetch and the data type's fetch_strict
+ * flag is true, then sbs_check_subscripts must return FALSE if there are any
+ * NULL subscripts. Otherwise it can choose to throw an error, or return
+ * FALSE, or let sbs_fetch or sbs_assign deal with the null subscripts.
+ *
+ * sbs_fetch: perform a subscripting fetch, using the container value in
+ * *op->resvalue and the subscripts from sbs_check_subscripts. If
+ * fetch_strict is true then all these inputs can be assumed non-NULL,
+ * otherwise sbs_fetch must check for null inputs. Place the result in
+ * *op->resvalue / *op->resnull.
+ *
+ * sbs_assign: perform a subscripting assignment, using the original
+ * container value in *op->resvalue / *op->resnull, the subscripts from
+ * sbs_check_subscripts, and the new element/slice value in
+ * sbsrefstate->replacevalue/replacenull. Any of these inputs might be NULL
+ * (unless sbs_check_subscripts rejected null subscripts). Place the result
+ * (an entire new container value) in *op->resvalue / *op->resnull.
+ *
+ * sbs_fetch_old: this is only used in cases where an element or slice
+ * assignment involves an assignment to a sub-field or sub-element
+ * (i.e., nested containers are involved). It must fetch the existing
+ * value of the target element or slice. This is exactly the same as
+ * sbs_fetch except that (a) it must cope with a NULL container, and
+ * with NULL subscripts if sbs_check_subscripts allows them (typically,
+ * returning NULL is good enough); and (b) the result must be placed in
+ * sbsrefstate->prevvalue/prevnull, without overwriting *op->resvalue.
+ *
+ * Subscripting implementations that do not support assignment need not
+ * provide sbs_assign or sbs_fetch_old methods. It might be reasonable
+ * to also omit sbs_check_subscripts, in which case the sbs_fetch method must
+ * combine the functionality of sbs_check_subscripts and sbs_fetch. (The
+ * main reason to have a separate sbs_check_subscripts method is so that
+ * sbs_fetch_old and sbs_assign need not duplicate subscript processing.)
+ * Set the relevant pointers to NULL for any omitted methods.
+ */
+typedef void (*SubscriptExecSetup) (const SubscriptingRef *sbsref,
+ struct SubscriptingRefState *sbsrefstate,
+ struct SubscriptExecSteps *methods);
+
+/* Struct returned by the SQL-visible subscript handler function */
+typedef struct SubscriptRoutines
+{
+ SubscriptTransform transform; /* parse analysis function */
+ SubscriptExecSetup exec_setup; /* expression compilation function */
+ bool fetch_strict; /* is fetch SubscriptRef strict? */
+ bool fetch_leakproof; /* is fetch SubscriptRef leakproof? */
+ bool store_leakproof; /* is assignment SubscriptRef leakproof? */
+} SubscriptRoutines;
+
+#endif /* SUBSCRIPTING_H */
diff --git a/pgsql/include/server/nodes/supportnodes.h b/pgsql/include/server/nodes/supportnodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..4cfa661d882e5d0ede965417364455ece898bb24
--- /dev/null
+++ b/pgsql/include/server/nodes/supportnodes.h
@@ -0,0 +1,346 @@
+/*-------------------------------------------------------------------------
+ *
+ * supportnodes.h
+ * Definitions for planner support functions.
+ *
+ * This file defines the API for "planner support functions", which
+ * are SQL functions (normally written in C) that can be attached to
+ * another "target" function to give the system additional knowledge
+ * about the target function. All the current capabilities have to do
+ * with planning queries that use the target function, though it is
+ * possible that future extensions will add functionality to be invoked
+ * by the parser or executor.
+ *
+ * A support function must have the SQL signature
+ * supportfn(internal) returns internal
+ * The argument is a pointer to one of the Node types defined in this file.
+ * The result is usually also a Node pointer, though its type depends on
+ * which capability is being invoked. In all cases, a NULL pointer result
+ * (that's PG_RETURN_POINTER(NULL), not PG_RETURN_NULL()) indicates that
+ * the support function cannot do anything useful for the given request.
+ * Support functions must return a NULL pointer, not fail, if they do not
+ * recognize the request node type or cannot handle the given case; this
+ * allows for future extensions of the set of request cases.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/nodes/supportnodes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SUPPORTNODES_H
+#define SUPPORTNODES_H
+
+#include "nodes/plannodes.h"
+
+struct PlannerInfo; /* avoid including pathnodes.h here */
+struct IndexOptInfo;
+struct SpecialJoinInfo;
+struct WindowClause;
+
+/*
+ * The Simplify request allows the support function to perform plan-time
+ * simplification of a call to its target function. For example, a varchar
+ * length coercion that does not decrease the allowed length of its argument
+ * could be replaced by a RelabelType node, or "x + 0" could be replaced by
+ * "x". This is invoked during the planner's constant-folding pass, so the
+ * function's arguments can be presumed already simplified.
+ *
+ * The planner's PlannerInfo "root" is typically not needed, but can be
+ * consulted if it's necessary to obtain info about Vars present in
+ * the given node tree. Beware that root could be NULL in some usages.
+ *
+ * "fcall" will be a FuncExpr invoking the support function's target
+ * function. (This is true even if the original parsetree node was an
+ * operator call; a FuncExpr is synthesized for this purpose.)
+ *
+ * The result should be a semantically-equivalent transformed node tree,
+ * or NULL if no simplification could be performed. Do *not* return or
+ * modify *fcall, as it isn't really a separately allocated Node. But
+ * it's okay to use fcall->args, or parts of it, in the result tree.
+ */
+typedef struct SupportRequestSimplify
+{
+ NodeTag type;
+
+ struct PlannerInfo *root; /* Planner's infrastructure */
+ FuncExpr *fcall; /* Function call to be simplified */
+} SupportRequestSimplify;
+
+/*
+ * The Selectivity request allows the support function to provide a
+ * selectivity estimate for a function appearing at top level of a WHERE
+ * clause (so it applies only to functions returning boolean).
+ *
+ * The input arguments are the same as are supplied to operator restriction
+ * and join estimators, except that we unify those two APIs into just one
+ * request type. See clause_selectivity() for the details.
+ *
+ * If an estimate can be made, store it into the "selectivity" field and
+ * return the address of the SupportRequestSelectivity node; the estimate
+ * must be between 0 and 1 inclusive. Return NULL if no estimate can be
+ * made (in which case the planner will fall back to a default estimate,
+ * traditionally 1/3).
+ *
+ * If the target function is being used as the implementation of an operator,
+ * the support function will not be used for this purpose; the operator's
+ * restriction or join estimator is consulted instead.
+ */
+typedef struct SupportRequestSelectivity
+{
+ NodeTag type;
+
+ /* Input fields: */
+ struct PlannerInfo *root; /* Planner's infrastructure */
+ Oid funcid; /* function we are inquiring about */
+ List *args; /* pre-simplified arguments to function */
+ Oid inputcollid; /* function's input collation */
+ bool is_join; /* is this a join or restriction case? */
+ int varRelid; /* if restriction, RTI of target relation */
+ JoinType jointype; /* if join, outer join type */
+ struct SpecialJoinInfo *sjinfo; /* if outer join, info about join */
+
+ /* Output fields: */
+ Selectivity selectivity; /* returned selectivity estimate */
+} SupportRequestSelectivity;
+
+/*
+ * The Cost request allows the support function to provide an execution
+ * cost estimate for its target function. The cost estimate can include
+ * both a one-time (query startup) component and a per-execution component.
+ * The estimate should *not* include the costs of evaluating the target
+ * function's arguments, only the target function itself.
+ *
+ * The "node" argument is normally the parse node that is invoking the
+ * target function. This is a FuncExpr in the simplest case, but it could
+ * also be an OpExpr, DistinctExpr, NullIfExpr, or WindowFunc, or possibly
+ * other cases in future. NULL is passed if the function cannot presume
+ * its arguments to be equivalent to what the calling node presents as
+ * arguments; that happens for, e.g., aggregate support functions and
+ * per-column comparison operators used by RowExprs.
+ *
+ * If an estimate can be made, store it into the cost fields and return the
+ * address of the SupportRequestCost node. Return NULL if no estimate can be
+ * made, in which case the planner will rely on the target function's procost
+ * field. (Note: while procost is automatically scaled by cpu_operator_cost,
+ * this is not the case for the outputs of the Cost request; the support
+ * function must scale its results appropriately on its own.)
+ */
+typedef struct SupportRequestCost
+{
+ NodeTag type;
+
+ /* Input fields: */
+ struct PlannerInfo *root; /* Planner's infrastructure (could be NULL) */
+ Oid funcid; /* function we are inquiring about */
+ Node *node; /* parse node invoking function, or NULL */
+
+ /* Output fields: */
+ Cost startup; /* one-time cost */
+ Cost per_tuple; /* per-evaluation cost */
+} SupportRequestCost;
+
+/*
+ * The Rows request allows the support function to provide an output rowcount
+ * estimate for its target function (so it applies only to set-returning
+ * functions).
+ *
+ * The "node" argument is the parse node that is invoking the target function;
+ * currently this will always be a FuncExpr or OpExpr.
+ *
+ * If an estimate can be made, store it into the rows field and return the
+ * address of the SupportRequestRows node. Return NULL if no estimate can be
+ * made, in which case the planner will rely on the target function's prorows
+ * field.
+ */
+typedef struct SupportRequestRows
+{
+ NodeTag type;
+
+ /* Input fields: */
+ struct PlannerInfo *root; /* Planner's infrastructure (could be NULL) */
+ Oid funcid; /* function we are inquiring about */
+ Node *node; /* parse node invoking function */
+
+ /* Output fields: */
+ double rows; /* number of rows expected to be returned */
+} SupportRequestRows;
+
+/*
+ * The IndexCondition request allows the support function to generate
+ * a directly-indexable condition based on a target function call that is
+ * not itself indexable. The target function call must appear at the top
+ * level of WHERE or JOIN/ON, so this applies only to functions returning
+ * boolean.
+ *
+ * The "node" argument is the parse node that is invoking the target function;
+ * currently this will always be a FuncExpr or OpExpr. The call is made
+ * only if at least one function argument matches an index column's variable
+ * or expression. "indexarg" identifies the matching argument (it's the
+ * argument's zero-based index in the node's args list).
+ *
+ * If the transformation is possible, return a List of directly-indexable
+ * condition expressions, else return NULL. (A List is used because it's
+ * sometimes useful to generate more than one indexable condition, such as
+ * when a LIKE with constant prefix gives rise to both >= and < conditions.)
+ *
+ * "Directly indexable" means that the condition must be directly executable
+ * by the index machinery. Typically this means that it is a binary OpExpr
+ * with the index column value on the left, a pseudo-constant on the right,
+ * and an operator that is in the index column's operator family. Other
+ * possibilities include RowCompareExpr, ScalarArrayOpExpr, and NullTest,
+ * depending on the index type; but those seem less likely to be useful for
+ * derived index conditions. "Pseudo-constant" means that the right-hand
+ * expression must not contain any volatile functions, nor any Vars of the
+ * table the index is for; use is_pseudo_constant_for_index() to check this.
+ * (Note: if the passed "node" is an OpExpr, the core planner already verified
+ * that the non-indexkey operand is pseudo-constant; but when the "node"
+ * is a FuncExpr, it does not check, since it doesn't know which of the
+ * function's arguments you might need to use in an index comparison value.)
+ *
+ * In many cases, an index condition can be generated but it is weaker than
+ * the function condition itself; for example, a LIKE with a constant prefix
+ * can produce an index range check based on the prefix, but we still need
+ * to execute the LIKE operator to verify the rest of the pattern. We say
+ * that such an index condition is "lossy". When returning an index condition,
+ * you should set the "lossy" request field to true if the condition is lossy,
+ * or false if it is an exact equivalent of the function's result. The core
+ * code will initialize that field to true, which is the common case.
+ *
+ * It is important to verify that the index operator family is the correct
+ * one for the condition you want to generate. Core support functions tend
+ * to use the known OID of a built-in opfamily for this, but extensions need
+ * to work harder, since their OIDs aren't fixed. A possibly workable
+ * answer for an index on an extension datatype is to verify the index AM's
+ * OID instead, and then assume that there's only one relevant opclass for
+ * your datatype so the opfamily must be the right one. Generating OpExpr
+ * nodes may also require knowing extension datatype OIDs (often you can
+ * find these out by applying exprType() to a function argument) and
+ * operator OIDs (which you can look up using get_opfamily_member).
+ */
+typedef struct SupportRequestIndexCondition
+{
+ NodeTag type;
+
+ /* Input fields: */
+ struct PlannerInfo *root; /* Planner's infrastructure */
+ Oid funcid; /* function we are inquiring about */
+ Node *node; /* parse node invoking function */
+ int indexarg; /* index of function arg matching indexcol */
+ struct IndexOptInfo *index; /* planner's info about target index */
+ int indexcol; /* index of target index column (0-based) */
+ Oid opfamily; /* index column's operator family */
+ Oid indexcollation; /* index column's collation */
+
+ /* Output fields: */
+ bool lossy; /* set to false if index condition is an exact
+ * equivalent of the function call */
+} SupportRequestIndexCondition;
+
+/* ----------
+ * To support more efficient query execution of any monotonically increasing
+ * and/or monotonically decreasing window functions, we support calling the
+ * window function's prosupport function passing along this struct whenever
+ * the planner sees an OpExpr qual directly reference a window function in a
+ * subquery. When the planner encounters this, we populate this struct and
+ * pass it along to the window function's prosupport function so that it can
+ * evaluate if the given WindowFunc is;
+ *
+ * a) monotonically increasing, or
+ * b) monotonically decreasing, or
+ * c) both monotonically increasing and decreasing, or
+ * d) none of the above.
+ *
+ * A function that is monotonically increasing can never return a value that
+ * is lower than a value returned in a "previous call". A monotonically
+ * decreasing function can never return a value higher than a value returned
+ * in a previous call. A function that is both must return the same value
+ * each time.
+ *
+ * We define "previous call" to mean a previous call to the same WindowFunc
+ * struct in the same window partition.
+ *
+ * row_number() is an example of a monotonically increasing function. The
+ * return value will be reset back to 1 in each new partition. An example of
+ * a monotonically increasing and decreasing function is COUNT(*) OVER ().
+ * Since there is no ORDER BY clause in this example, all rows in the
+ * partition are peers and all rows within the partition will be within the
+ * frame bound. Likewise for COUNT(*) OVER(ORDER BY a ROWS BETWEEN UNBOUNDED
+ * PRECEDING AND UNBOUNDED FOLLOWING).
+ *
+ * COUNT(*) OVER (ORDER BY a ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
+ * is an example of a monotonically decreasing function.
+ *
+ * Implementations must only concern themselves with the given WindowFunc
+ * being monotonic in a single partition.
+ *
+ * Inputs:
+ * 'window_func' is the pointer to the window function being called.
+ *
+ * 'window_clause' pointer to the WindowClause data. Support functions can
+ * use this to check frame bounds, etc.
+ *
+ * Outputs:
+ * 'monotonic' the resulting MonotonicFunction value for the given input
+ * window function and window clause.
+ * ----------
+ */
+typedef struct SupportRequestWFuncMonotonic
+{
+ NodeTag type;
+
+ /* Input fields: */
+ WindowFunc *window_func; /* Pointer to the window function data */
+ struct WindowClause *window_clause; /* Pointer to the window clause data */
+
+ /* Output fields: */
+ MonotonicFunction monotonic;
+} SupportRequestWFuncMonotonic;
+
+/*
+ * Some WindowFunc behavior might not be affected by certain variations in
+ * the WindowClause's frameOptions. For example, row_number() is coded in
+ * such a way that the frame options don't change the returned row number.
+ * nodeWindowAgg.c will have less work to do if the ROWS option is used
+ * instead of the RANGE option as no check needs to be done for peer rows.
+ * Since RANGE is included in the default frame options, window functions
+ * such as row_number() might want to change that to ROW.
+ *
+ * Here we allow a WindowFunc's support function to determine which, if
+ * anything, can be changed about the WindowClause which the WindowFunc
+ * belongs to. Currently only the frameOptions can be modified. However,
+ * we may want to allow more optimizations in the future.
+ *
+ * The support function is responsible for ensuring the optimized version of
+ * the frameOptions doesn't affect the result of the window function. The
+ * planner is responsible for only changing the frame options when all
+ * WindowFuncs using this particular WindowClause agree on what the optimized
+ * version of the frameOptions are. If a particular WindowFunc being used
+ * does not have a support function then the planner will not make any changes
+ * to the WindowClause's frameOptions.
+ *
+ * 'window_func' and 'window_clause' are set by the planner before calling the
+ * support function so that the support function has these fields available.
+ * These may be required in order to determine which optimizations are
+ * possible.
+ *
+ * 'frameOptions' is set by the planner to WindowClause.frameOptions. The
+ * support function must only adjust this if optimizations are possible for
+ * the given WindowFunc.
+ */
+typedef struct SupportRequestOptimizeWindowClause
+{
+ NodeTag type;
+
+ /* Input fields: */
+ WindowFunc *window_func; /* Pointer to the window function data */
+ struct WindowClause *window_clause; /* Pointer to the window clause data */
+
+ /* Input/Output fields: */
+ int frameOptions; /* New frameOptions, or left untouched if no
+ * optimizations are possible. */
+} SupportRequestOptimizeWindowClause;
+
+#endif /* SUPPORTNODES_H */
diff --git a/pgsql/include/server/nodes/tidbitmap.h b/pgsql/include/server/nodes/tidbitmap.h
new file mode 100644
index 0000000000000000000000000000000000000000..b64e36437a0668d4b46ba91f0fdbd23c73c1c8a4
--- /dev/null
+++ b/pgsql/include/server/nodes/tidbitmap.h
@@ -0,0 +1,75 @@
+/*-------------------------------------------------------------------------
+ *
+ * tidbitmap.h
+ * PostgreSQL tuple-id (TID) bitmap package
+ *
+ * This module provides bitmap data structures that are spiritually
+ * similar to Bitmapsets, but are specially adapted to store sets of
+ * tuple identifiers (TIDs), or ItemPointers. In particular, the division
+ * of an ItemPointer into BlockNumber and OffsetNumber is catered for.
+ * Also, since we wish to be able to store very large tuple sets in
+ * memory with this data structure, we support "lossy" storage, in which
+ * we no longer remember individual tuple offsets on a page but only the
+ * fact that a particular page needs to be visited.
+ *
+ *
+ * Copyright (c) 2003-2023, PostgreSQL Global Development Group
+ *
+ * src/include/nodes/tidbitmap.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TIDBITMAP_H
+#define TIDBITMAP_H
+
+#include "storage/itemptr.h"
+#include "utils/dsa.h"
+
+
+/*
+ * Actual bitmap representation is private to tidbitmap.c. Callers can
+ * do IsA(x, TIDBitmap) on it, but nothing else.
+ */
+typedef struct TIDBitmap TIDBitmap;
+
+/* Likewise, TBMIterator is private */
+typedef struct TBMIterator TBMIterator;
+typedef struct TBMSharedIterator TBMSharedIterator;
+
+/* Result structure for tbm_iterate */
+typedef struct TBMIterateResult
+{
+ BlockNumber blockno; /* page number containing tuples */
+ int ntuples; /* -1 indicates lossy result */
+ bool recheck; /* should the tuples be rechecked? */
+ /* Note: recheck is always true if ntuples < 0 */
+ OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER];
+} TBMIterateResult;
+
+/* function prototypes in nodes/tidbitmap.c */
+
+extern TIDBitmap *tbm_create(long maxbytes, dsa_area *dsa);
+extern void tbm_free(TIDBitmap *tbm);
+extern void tbm_free_shared_area(dsa_area *dsa, dsa_pointer dp);
+
+extern void tbm_add_tuples(TIDBitmap *tbm,
+ const ItemPointer tids, int ntids,
+ bool recheck);
+extern void tbm_add_page(TIDBitmap *tbm, BlockNumber pageno);
+
+extern void tbm_union(TIDBitmap *a, const TIDBitmap *b);
+extern void tbm_intersect(TIDBitmap *a, const TIDBitmap *b);
+
+extern bool tbm_is_empty(const TIDBitmap *tbm);
+
+extern TBMIterator *tbm_begin_iterate(TIDBitmap *tbm);
+extern dsa_pointer tbm_prepare_shared_iterate(TIDBitmap *tbm);
+extern TBMIterateResult *tbm_iterate(TBMIterator *iterator);
+extern TBMIterateResult *tbm_shared_iterate(TBMSharedIterator *iterator);
+extern void tbm_end_iterate(TBMIterator *iterator);
+extern void tbm_end_shared_iterate(TBMSharedIterator *iterator);
+extern TBMSharedIterator *tbm_attach_shared_iterate(dsa_area *dsa,
+ dsa_pointer dp);
+extern long tbm_calculate_entries(double maxbytes);
+
+#endif /* TIDBITMAP_H */
diff --git a/pgsql/include/server/nodes/value.h b/pgsql/include/server/nodes/value.h
new file mode 100644
index 0000000000000000000000000000000000000000..b24c4c1afef41b7d144cd20076e7e36f35af41a1
--- /dev/null
+++ b/pgsql/include/server/nodes/value.h
@@ -0,0 +1,90 @@
+/*-------------------------------------------------------------------------
+ *
+ * value.h
+ * interface for value nodes
+ *
+ *
+ * Copyright (c) 2003-2023, PostgreSQL Global Development Group
+ *
+ * src/include/nodes/value.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef VALUE_H
+#define VALUE_H
+
+#include "nodes/nodes.h"
+
+/*
+ * The node types Integer, Float, String, and BitString are used to represent
+ * literals in the lexer and are also used to pass constants around in the
+ * parser. One difference between these node types and, say, a plain int or
+ * char * is that the nodes can be put into a List.
+ *
+ * (There used to be a Value node, which encompassed all these different node types. Hence the name of this file.)
+ */
+
+typedef struct Integer
+{
+ pg_node_attr(special_read_write)
+
+ NodeTag type;
+ int ival;
+} Integer;
+
+/*
+ * Float is internally represented as string. Using T_Float as the node type
+ * simply indicates that the contents of the string look like a valid numeric
+ * literal. The value might end up being converted to NUMERIC, so we can't
+ * store it internally as a C double, since that could lose precision. Since
+ * these nodes are generally only used in the parsing process, not for runtime
+ * data, it's better to use the more general representation.
+ *
+ * Note that an integer-looking string will get lexed as T_Float if the value
+ * is too large to fit in an 'int'.
+ */
+typedef struct Float
+{
+ pg_node_attr(special_read_write)
+
+ NodeTag type;
+ char *fval;
+} Float;
+
+typedef struct Boolean
+{
+ pg_node_attr(special_read_write)
+
+ NodeTag type;
+ bool boolval;
+} Boolean;
+
+typedef struct String
+{
+ pg_node_attr(special_read_write)
+
+ NodeTag type;
+ char *sval;
+} String;
+
+typedef struct BitString
+{
+ pg_node_attr(special_read_write)
+
+ NodeTag type;
+ char *bsval;
+} BitString;
+
+#define intVal(v) (castNode(Integer, v)->ival)
+#define floatVal(v) atof(castNode(Float, v)->fval)
+#define boolVal(v) (castNode(Boolean, v)->boolval)
+#define strVal(v) (castNode(String, v)->sval)
+
+extern Integer *makeInteger(int i);
+extern Float *makeFloat(char *numericStr);
+extern Boolean *makeBoolean(bool val);
+extern String *makeString(char *str);
+extern BitString *makeBitString(char *str);
+
+#endif /* VALUE_H */
diff --git a/pgsql/include/server/optimizer/appendinfo.h b/pgsql/include/server/optimizer/appendinfo.h
new file mode 100644
index 0000000000000000000000000000000000000000..a05f91f77d005f0b01a9279ce7251c87491d5293
--- /dev/null
+++ b/pgsql/include/server/optimizer/appendinfo.h
@@ -0,0 +1,50 @@
+/*-------------------------------------------------------------------------
+ *
+ * appendinfo.h
+ * Routines for mapping expressions between append rel parent(s) and
+ * children
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/appendinfo.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef APPENDINFO_H
+#define APPENDINFO_H
+
+#include "nodes/pathnodes.h"
+#include "utils/relcache.h"
+
+extern AppendRelInfo *make_append_rel_info(Relation parentrel,
+ Relation childrel,
+ Index parentRTindex, Index childRTindex);
+extern Node *adjust_appendrel_attrs(PlannerInfo *root, Node *node,
+ int nappinfos, AppendRelInfo **appinfos);
+extern Node *adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node,
+ RelOptInfo *childrel,
+ RelOptInfo *parentrel);
+extern Relids adjust_child_relids(Relids relids, int nappinfos,
+ AppendRelInfo **appinfos);
+extern Relids adjust_child_relids_multilevel(PlannerInfo *root, Relids relids,
+ RelOptInfo *childrel,
+ RelOptInfo *parentrel);
+extern List *adjust_inherited_attnums(List *attnums, AppendRelInfo *context);
+extern List *adjust_inherited_attnums_multilevel(PlannerInfo *root,
+ List *attnums,
+ Index child_relid,
+ Index top_parent_relid);
+extern void get_translated_update_targetlist(PlannerInfo *root, Index relid,
+ List **processed_tlist,
+ List **update_colnos);
+extern AppendRelInfo **find_appinfos_by_relids(PlannerInfo *root,
+ Relids relids, int *nappinfos);
+extern void add_row_identity_var(PlannerInfo *root, Var *orig_var,
+ Index rtindex, const char *rowid_name);
+extern void add_row_identity_columns(PlannerInfo *root, Index rtindex,
+ RangeTblEntry *target_rte,
+ Relation target_relation);
+extern void distribute_row_identity_vars(PlannerInfo *root);
+
+#endif /* APPENDINFO_H */
diff --git a/pgsql/include/server/optimizer/clauses.h b/pgsql/include/server/optimizer/clauses.h
new file mode 100644
index 0000000000000000000000000000000000000000..cbe0607e85ac3ea0c2cee18691c28561f9c2e458
--- /dev/null
+++ b/pgsql/include/server/optimizer/clauses.h
@@ -0,0 +1,58 @@
+/*-------------------------------------------------------------------------
+ *
+ * clauses.h
+ * prototypes for clauses.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/clauses.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef CLAUSES_H
+#define CLAUSES_H
+
+#include "nodes/pathnodes.h"
+
+typedef struct
+{
+ int numWindowFuncs; /* total number of WindowFuncs found */
+ Index maxWinRef; /* windowFuncs[] is indexed 0 .. maxWinRef */
+ List **windowFuncs; /* lists of WindowFuncs for each winref */
+} WindowFuncLists;
+
+extern bool contain_agg_clause(Node *clause);
+
+extern bool contain_window_function(Node *clause);
+extern WindowFuncLists *find_window_functions(Node *clause, Index maxWinRef);
+
+extern double expression_returns_set_rows(PlannerInfo *root, Node *clause);
+
+extern bool contain_subplans(Node *clause);
+
+extern char max_parallel_hazard(Query *parse);
+extern bool is_parallel_safe(PlannerInfo *root, Node *node);
+extern bool contain_nonstrict_functions(Node *clause);
+extern bool contain_exec_param(Node *clause, List *param_ids);
+extern bool contain_leaked_vars(Node *clause);
+
+extern Relids find_nonnullable_rels(Node *clause);
+extern List *find_nonnullable_vars(Node *clause);
+extern List *find_forced_null_vars(Node *node);
+extern Var *find_forced_null_var(Node *node);
+
+extern bool is_pseudo_constant_clause(Node *clause);
+extern bool is_pseudo_constant_clause_relids(Node *clause, Relids relids);
+
+extern int NumRelids(PlannerInfo *root, Node *clause);
+
+extern void CommuteOpExpr(OpExpr *clause);
+
+extern Query *inline_set_returning_function(PlannerInfo *root,
+ RangeTblEntry *rte);
+
+extern Bitmapset *pull_paramids(Expr *expr);
+
+#endif /* CLAUSES_H */
diff --git a/pgsql/include/server/optimizer/cost.h b/pgsql/include/server/optimizer/cost.h
new file mode 100644
index 0000000000000000000000000000000000000000..6cf49705d3afdaae9e5e7267795e584b15d5eb4e
--- /dev/null
+++ b/pgsql/include/server/optimizer/cost.h
@@ -0,0 +1,215 @@
+/*-------------------------------------------------------------------------
+ *
+ * cost.h
+ * prototypes for costsize.c and clausesel.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/cost.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef COST_H
+#define COST_H
+
+#include "nodes/pathnodes.h"
+#include "nodes/plannodes.h"
+
+
+/* defaults for costsize.c's Cost parameters */
+/* NB: cost-estimation code should use the variables, not these constants! */
+/* If you change these, update backend/utils/misc/postgresql.conf.sample */
+#define DEFAULT_SEQ_PAGE_COST 1.0
+#define DEFAULT_RANDOM_PAGE_COST 4.0
+#define DEFAULT_CPU_TUPLE_COST 0.01
+#define DEFAULT_CPU_INDEX_TUPLE_COST 0.005
+#define DEFAULT_CPU_OPERATOR_COST 0.0025
+#define DEFAULT_PARALLEL_TUPLE_COST 0.1
+#define DEFAULT_PARALLEL_SETUP_COST 1000.0
+
+/* defaults for non-Cost parameters */
+#define DEFAULT_RECURSIVE_WORKTABLE_FACTOR 10.0
+#define DEFAULT_EFFECTIVE_CACHE_SIZE 524288 /* measured in pages */
+
+typedef enum
+{
+ CONSTRAINT_EXCLUSION_OFF, /* do not use c_e */
+ CONSTRAINT_EXCLUSION_ON, /* apply c_e to all rels */
+ CONSTRAINT_EXCLUSION_PARTITION /* apply c_e to otherrels only */
+} ConstraintExclusionType;
+
+
+/*
+ * prototypes for costsize.c
+ * routines to compute costs and sizes
+ */
+
+/* parameter variables and flags (see also optimizer.h) */
+extern PGDLLIMPORT Cost disable_cost;
+extern PGDLLIMPORT int max_parallel_workers_per_gather;
+extern PGDLLIMPORT bool enable_seqscan;
+extern PGDLLIMPORT bool enable_indexscan;
+extern PGDLLIMPORT bool enable_indexonlyscan;
+extern PGDLLIMPORT bool enable_bitmapscan;
+extern PGDLLIMPORT bool enable_tidscan;
+extern PGDLLIMPORT bool enable_sort;
+extern PGDLLIMPORT bool enable_incremental_sort;
+extern PGDLLIMPORT bool enable_hashagg;
+extern PGDLLIMPORT bool enable_nestloop;
+extern PGDLLIMPORT bool enable_material;
+extern PGDLLIMPORT bool enable_memoize;
+extern PGDLLIMPORT bool enable_mergejoin;
+extern PGDLLIMPORT bool enable_hashjoin;
+extern PGDLLIMPORT bool enable_gathermerge;
+extern PGDLLIMPORT bool enable_partitionwise_join;
+extern PGDLLIMPORT bool enable_partitionwise_aggregate;
+extern PGDLLIMPORT bool enable_parallel_append;
+extern PGDLLIMPORT bool enable_parallel_hash;
+extern PGDLLIMPORT bool enable_partition_pruning;
+extern PGDLLIMPORT bool enable_presorted_aggregate;
+extern PGDLLIMPORT bool enable_async_append;
+extern PGDLLIMPORT int constraint_exclusion;
+
+extern double index_pages_fetched(double tuples_fetched, BlockNumber pages,
+ double index_pages, PlannerInfo *root);
+extern void cost_seqscan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
+ ParamPathInfo *param_info);
+extern void cost_samplescan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
+ ParamPathInfo *param_info);
+extern void cost_index(IndexPath *path, PlannerInfo *root,
+ double loop_count, bool partial_path);
+extern void cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
+ ParamPathInfo *param_info,
+ Path *bitmapqual, double loop_count);
+extern void cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root);
+extern void cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root);
+extern void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec);
+extern void cost_tidscan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info);
+extern void cost_tidrangescan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, List *tidrangequals,
+ ParamPathInfo *param_info);
+extern void cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info,
+ bool trivial_pathtarget);
+extern void cost_functionscan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info);
+extern void cost_valuesscan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info);
+extern void cost_tablefuncscan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info);
+extern void cost_ctescan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info);
+extern void cost_namedtuplestorescan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info);
+extern void cost_resultscan(Path *path, PlannerInfo *root,
+ RelOptInfo *baserel, ParamPathInfo *param_info);
+extern void cost_recursive_union(Path *runion, Path *nrterm, Path *rterm);
+extern void cost_sort(Path *path, PlannerInfo *root,
+ List *pathkeys, Cost input_cost, double tuples, int width,
+ Cost comparison_cost, int sort_mem,
+ double limit_tuples);
+extern void cost_incremental_sort(Path *path,
+ PlannerInfo *root, List *pathkeys, int presorted_keys,
+ Cost input_startup_cost, Cost input_total_cost,
+ double input_tuples, int width, Cost comparison_cost, int sort_mem,
+ double limit_tuples);
+extern void cost_append(AppendPath *apath);
+extern void cost_merge_append(Path *path, PlannerInfo *root,
+ List *pathkeys, int n_streams,
+ Cost input_startup_cost, Cost input_total_cost,
+ double tuples);
+extern void cost_material(Path *path,
+ Cost input_startup_cost, Cost input_total_cost,
+ double tuples, int width);
+extern void cost_agg(Path *path, PlannerInfo *root,
+ AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
+ int numGroupCols, double numGroups,
+ List *quals,
+ Cost input_startup_cost, Cost input_total_cost,
+ double input_tuples, double input_width);
+extern void cost_windowagg(Path *path, PlannerInfo *root,
+ List *windowFuncs, int numPartCols, int numOrderCols,
+ Cost input_startup_cost, Cost input_total_cost,
+ double input_tuples);
+extern void cost_group(Path *path, PlannerInfo *root,
+ int numGroupCols, double numGroups,
+ List *quals,
+ Cost input_startup_cost, Cost input_total_cost,
+ double input_tuples);
+extern void initial_cost_nestloop(PlannerInfo *root,
+ JoinCostWorkspace *workspace,
+ JoinType jointype,
+ Path *outer_path, Path *inner_path,
+ JoinPathExtraData *extra);
+extern void final_cost_nestloop(PlannerInfo *root, NestPath *path,
+ JoinCostWorkspace *workspace,
+ JoinPathExtraData *extra);
+extern void initial_cost_mergejoin(PlannerInfo *root,
+ JoinCostWorkspace *workspace,
+ JoinType jointype,
+ List *mergeclauses,
+ Path *outer_path, Path *inner_path,
+ List *outersortkeys, List *innersortkeys,
+ JoinPathExtraData *extra);
+extern void final_cost_mergejoin(PlannerInfo *root, MergePath *path,
+ JoinCostWorkspace *workspace,
+ JoinPathExtraData *extra);
+extern void initial_cost_hashjoin(PlannerInfo *root,
+ JoinCostWorkspace *workspace,
+ JoinType jointype,
+ List *hashclauses,
+ Path *outer_path, Path *inner_path,
+ JoinPathExtraData *extra,
+ bool parallel_hash);
+extern void final_cost_hashjoin(PlannerInfo *root, HashPath *path,
+ JoinCostWorkspace *workspace,
+ JoinPathExtraData *extra);
+extern void cost_gather(GatherPath *path, PlannerInfo *root,
+ RelOptInfo *rel, ParamPathInfo *param_info, double *rows);
+extern void cost_gather_merge(GatherMergePath *path, PlannerInfo *root,
+ RelOptInfo *rel, ParamPathInfo *param_info,
+ Cost input_startup_cost, Cost input_total_cost,
+ double *rows);
+extern void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan);
+extern void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root);
+extern void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root);
+extern void compute_semi_anti_join_factors(PlannerInfo *root,
+ RelOptInfo *joinrel,
+ RelOptInfo *outerrel,
+ RelOptInfo *innerrel,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo,
+ List *restrictlist,
+ SemiAntiJoinFactors *semifactors);
+extern void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern double get_parameterized_baserel_size(PlannerInfo *root,
+ RelOptInfo *rel,
+ List *param_clauses);
+extern double get_parameterized_joinrel_size(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *outer_path,
+ Path *inner_path,
+ SpecialJoinInfo *sjinfo,
+ List *restrict_clauses);
+extern void set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
+ RelOptInfo *outer_rel,
+ RelOptInfo *inner_rel,
+ SpecialJoinInfo *sjinfo,
+ List *restrictlist);
+extern void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern void set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern void set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel,
+ double cte_rows);
+extern void set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel);
+extern PathTarget *set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target);
+extern double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel,
+ Path *bitmapqual, int loop_count, Cost *cost, double *tuple);
+
+#endif /* COST_H */
diff --git a/pgsql/include/server/optimizer/geqo.h b/pgsql/include/server/optimizer/geqo.h
new file mode 100644
index 0000000000000000000000000000000000000000..c7981973bc7a1fb361004783f4dab6f07db0dcc8
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo.h
@@ -0,0 +1,90 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo.h
+ * prototypes for various files in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+#ifndef GEQO_H
+#define GEQO_H
+
+#include "common/pg_prng.h"
+#include "nodes/pathnodes.h"
+#include "optimizer/geqo_gene.h"
+
+
+/* GEQO debug flag */
+/*
+ #define GEQO_DEBUG
+ */
+
+/* choose one recombination mechanism here */
+/*
+ #define ERX
+ #define PMX
+ #define CX
+ #define PX
+ #define OX1
+ #define OX2
+ */
+#define ERX
+
+
+/*
+ * Configuration options
+ *
+ * If you change these, update backend/utils/misc/postgresql.conf.sample
+ */
+extern PGDLLIMPORT int Geqo_effort; /* 1 .. 10, knob for adjustment of
+ * defaults */
+
+#define DEFAULT_GEQO_EFFORT 5
+#define MIN_GEQO_EFFORT 1
+#define MAX_GEQO_EFFORT 10
+
+extern PGDLLIMPORT int Geqo_pool_size; /* 2 .. inf, or 0 to use default */
+
+extern PGDLLIMPORT int Geqo_generations; /* 1 .. inf, or 0 to use default */
+
+extern PGDLLIMPORT double Geqo_selection_bias;
+
+#define DEFAULT_GEQO_SELECTION_BIAS 2.0
+#define MIN_GEQO_SELECTION_BIAS 1.5
+#define MAX_GEQO_SELECTION_BIAS 2.0
+
+extern PGDLLIMPORT double Geqo_seed; /* 0 .. 1 */
+
+
+/*
+ * Private state for a GEQO run --- accessible via root->join_search_private
+ */
+typedef struct
+{
+ List *initial_rels; /* the base relations we are joining */
+ pg_prng_state random_state; /* PRNG state */
+} GeqoPrivateData;
+
+
+/* routines in geqo_main.c */
+extern RelOptInfo *geqo(PlannerInfo *root,
+ int number_of_rels, List *initial_rels);
+
+/* routines in geqo_eval.c */
+extern Cost geqo_eval(PlannerInfo *root, Gene *tour, int num_gene);
+extern RelOptInfo *gimme_tree(PlannerInfo *root, Gene *tour, int num_gene);
+
+#endif /* GEQO_H */
diff --git a/pgsql/include/server/optimizer/geqo_copy.h b/pgsql/include/server/optimizer/geqo_copy.h
new file mode 100644
index 0000000000000000000000000000000000000000..9a78de65c97e128ce425278700412d74ae19cb42
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_copy.h
@@ -0,0 +1,30 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_copy.h
+ * prototypes for copy functions in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_copy.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+#ifndef GEQO_COPY_H
+#define GEQO_COPY_H
+
+#include "optimizer/geqo.h"
+
+
+extern void geqo_copy(PlannerInfo *root, Chromosome *chromo1, Chromosome *chromo2, int string_length);
+
+#endif /* GEQO_COPY_H */
diff --git a/pgsql/include/server/optimizer/geqo_gene.h b/pgsql/include/server/optimizer/geqo_gene.h
new file mode 100644
index 0000000000000000000000000000000000000000..40256a4cde646cc132b5361bb005110bf5449ffc
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_gene.h
@@ -0,0 +1,45 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_gene.h
+ * genome representation in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_gene.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+
+#ifndef GEQO_GENE_H
+#define GEQO_GENE_H
+
+#include "nodes/nodes.h"
+
+/* we presume that int instead of Relid
+ is o.k. for Gene; so don't change it! */
+typedef int Gene;
+
+typedef struct Chromosome
+{
+ Gene *string;
+ Cost worth;
+} Chromosome;
+
+typedef struct Pool
+{
+ Chromosome *data;
+ int size;
+ int string_length;
+} Pool;
+
+#endif /* GEQO_GENE_H */
diff --git a/pgsql/include/server/optimizer/geqo_misc.h b/pgsql/include/server/optimizer/geqo_misc.h
new file mode 100644
index 0000000000000000000000000000000000000000..25e168127395086a90061f78461017449026a380
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_misc.h
@@ -0,0 +1,34 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_misc.h
+ * prototypes for printout routines in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_misc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+#ifndef GEQO_MISC_H
+#define GEQO_MISC_H
+
+#include "optimizer/geqo_recombination.h"
+
+#ifdef GEQO_DEBUG
+
+extern void print_pool(FILE *fp, Pool *pool, int start, int stop);
+extern void print_gen(FILE *fp, Pool *pool, int generation);
+extern void print_edge_table(FILE *fp, Edge *edge_table, int num_gene);
+#endif /* GEQO_DEBUG */
+
+#endif /* GEQO_MISC_H */
diff --git a/pgsql/include/server/optimizer/geqo_mutation.h b/pgsql/include/server/optimizer/geqo_mutation.h
new file mode 100644
index 0000000000000000000000000000000000000000..d0f7ed94206eeccfe9e5ec3d489d393ba1cdfa22
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_mutation.h
@@ -0,0 +1,30 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_mutation.h
+ * prototypes for mutation functions in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_mutation.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+#ifndef GEQO_MUTATION_H
+#define GEQO_MUTATION_H
+
+#include "optimizer/geqo.h"
+
+
+extern void geqo_mutation(PlannerInfo *root, Gene *tour, int num_gene);
+
+#endif /* GEQO_MUTATION_H */
diff --git a/pgsql/include/server/optimizer/geqo_pool.h b/pgsql/include/server/optimizer/geqo_pool.h
new file mode 100644
index 0000000000000000000000000000000000000000..d1464f70aa8625248d76ac6523e479fbe87f4de4
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_pool.h
@@ -0,0 +1,40 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_pool.h
+ * pool representation in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_pool.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+
+#ifndef GEQO_POOL_H
+#define GEQO_POOL_H
+
+#include "optimizer/geqo.h"
+
+
+extern Pool *alloc_pool(PlannerInfo *root, int pool_size, int string_length);
+extern void free_pool(PlannerInfo *root, Pool *pool);
+
+extern void random_init_pool(PlannerInfo *root, Pool *pool);
+extern Chromosome *alloc_chromo(PlannerInfo *root, int string_length);
+extern void free_chromo(PlannerInfo *root, Chromosome *chromo);
+
+extern void spread_chromo(PlannerInfo *root, Chromosome *chromo, Pool *pool);
+
+extern void sort_pool(PlannerInfo *root, Pool *pool);
+
+#endif /* GEQO_POOL_H */
diff --git a/pgsql/include/server/optimizer/geqo_random.h b/pgsql/include/server/optimizer/geqo_random.h
new file mode 100644
index 0000000000000000000000000000000000000000..08b0c08d85f94562b77ca9668cfad446e417ebb8
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_random.h
@@ -0,0 +1,40 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_random.h
+ * random number generator
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_random.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+/* -- parts of this are adapted from D. Whitley's Genitor algorithm -- */
+
+#ifndef GEQO_RANDOM_H
+#define GEQO_RANDOM_H
+
+#include
+
+#include "optimizer/geqo.h"
+
+
+extern void geqo_set_seed(PlannerInfo *root, double seed);
+
+/* geqo_rand returns a random float value in the range [0.0, 1.0) */
+extern double geqo_rand(PlannerInfo *root);
+
+/* geqo_randint returns integer value between lower and upper inclusive */
+extern int geqo_randint(PlannerInfo *root, int upper, int lower);
+
+#endif /* GEQO_RANDOM_H */
diff --git a/pgsql/include/server/optimizer/geqo_recombination.h b/pgsql/include/server/optimizer/geqo_recombination.h
new file mode 100644
index 0000000000000000000000000000000000000000..1c3c7d5f646552067b05bcb73b67fdc4cf6c1cf0
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_recombination.h
@@ -0,0 +1,89 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_recombination.h
+ * prototypes for recombination in the genetic query optimizer
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_recombination.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+/* -- parts of this are adapted from D. Whitley's Genitor algorithm -- */
+
+#ifndef GEQO_RECOMBINATION_H
+#define GEQO_RECOMBINATION_H
+
+#include "optimizer/geqo.h"
+
+
+extern void init_tour(PlannerInfo *root, Gene *tour, int num_gene);
+
+
+/* edge recombination crossover [ERX] */
+
+typedef struct Edge
+{
+ Gene edge_list[4]; /* list of edges */
+ int total_edges;
+ int unused_edges;
+} Edge;
+
+extern Edge *alloc_edge_table(PlannerInfo *root, int num_gene);
+extern void free_edge_table(PlannerInfo *root, Edge *edge_table);
+
+extern float gimme_edge_table(PlannerInfo *root, Gene *tour1, Gene *tour2,
+ int num_gene, Edge *edge_table);
+
+extern int gimme_tour(PlannerInfo *root, Edge *edge_table, Gene *new_gene,
+ int num_gene);
+
+
+/* partially matched crossover [PMX] */
+
+#define DAD 1 /* indicator for gene from dad */
+#define MOM 0 /* indicator for gene from mom */
+
+extern void pmx(PlannerInfo *root,
+ Gene *tour1, Gene *tour2,
+ Gene *offspring, int num_gene);
+
+
+typedef struct City
+{
+ int tour2_position;
+ int tour1_position;
+ int used;
+ int select_list;
+} City;
+
+extern City * alloc_city_table(PlannerInfo *root, int num_gene);
+extern void free_city_table(PlannerInfo *root, City * city_table);
+
+/* cycle crossover [CX] */
+extern int cx(PlannerInfo *root, Gene *tour1, Gene *tour2,
+ Gene *offspring, int num_gene, City * city_table);
+
+/* position crossover [PX] */
+extern void px(PlannerInfo *root, Gene *tour1, Gene *tour2, Gene *offspring,
+ int num_gene, City * city_table);
+
+/* order crossover [OX1] according to Davis */
+extern void ox1(PlannerInfo *root, Gene *mom, Gene *dad, Gene *offspring,
+ int num_gene, City * city_table);
+
+/* order crossover [OX2] according to Syswerda */
+extern void ox2(PlannerInfo *root, Gene *mom, Gene *dad, Gene *offspring,
+ int num_gene, City * city_table);
+
+#endif /* GEQO_RECOMBINATION_H */
diff --git a/pgsql/include/server/optimizer/geqo_selection.h b/pgsql/include/server/optimizer/geqo_selection.h
new file mode 100644
index 0000000000000000000000000000000000000000..45d1078e696e5e44f0031d224d606c03f77db6e3
--- /dev/null
+++ b/pgsql/include/server/optimizer/geqo_selection.h
@@ -0,0 +1,33 @@
+/*-------------------------------------------------------------------------
+ *
+ * geqo_selection.h
+ * prototypes for selection routines in optimizer/geqo
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/geqo_selection.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* contributed by:
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ * Martin Utesch * Institute of Automatic Control *
+ = = University of Mining and Technology =
+ * utesch@aut.tu-freiberg.de * Freiberg, Germany *
+ =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
+ */
+
+
+#ifndef GEQO_SELECTION_H
+#define GEQO_SELECTION_H
+
+#include "optimizer/geqo.h"
+
+
+extern void geqo_selection(PlannerInfo *root,
+ Chromosome *momma, Chromosome *daddy,
+ Pool *pool, double bias);
+
+#endif /* GEQO_SELECTION_H */
diff --git a/pgsql/include/server/optimizer/inherit.h b/pgsql/include/server/optimizer/inherit.h
new file mode 100644
index 0000000000000000000000000000000000000000..76e958d639ebac645290efa2a7018086385aaaa9
--- /dev/null
+++ b/pgsql/include/server/optimizer/inherit.h
@@ -0,0 +1,29 @@
+/*-------------------------------------------------------------------------
+ *
+ * inherit.h
+ * prototypes for inherit.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/inherit.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef INHERIT_H
+#define INHERIT_H
+
+#include "nodes/pathnodes.h"
+
+
+extern void expand_inherited_rtentry(PlannerInfo *root, RelOptInfo *rel,
+ RangeTblEntry *rte, Index rti);
+
+extern Bitmapset *get_rel_all_updated_cols(PlannerInfo *root, RelOptInfo *rel);
+
+extern bool apply_child_basequals(PlannerInfo *root, RelOptInfo *parentrel,
+ RelOptInfo *childrel, RangeTblEntry *childRTE,
+ AppendRelInfo *appinfo);
+
+#endif /* INHERIT_H */
diff --git a/pgsql/include/server/optimizer/joininfo.h b/pgsql/include/server/optimizer/joininfo.h
new file mode 100644
index 0000000000000000000000000000000000000000..2cd6a132234057bfe51cc524f892c2cb5140b439
--- /dev/null
+++ b/pgsql/include/server/optimizer/joininfo.h
@@ -0,0 +1,30 @@
+/*-------------------------------------------------------------------------
+ *
+ * joininfo.h
+ * prototypes for joininfo.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/joininfo.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef JOININFO_H
+#define JOININFO_H
+
+#include "nodes/pathnodes.h"
+
+
+extern bool have_relevant_joinclause(PlannerInfo *root,
+ RelOptInfo *rel1, RelOptInfo *rel2);
+
+extern void add_join_clause_to_rels(PlannerInfo *root,
+ RestrictInfo *restrictinfo,
+ Relids join_relids);
+extern void remove_join_clause_from_rels(PlannerInfo *root,
+ RestrictInfo *restrictinfo,
+ Relids join_relids);
+
+#endif /* JOININFO_H */
diff --git a/pgsql/include/server/optimizer/optimizer.h b/pgsql/include/server/optimizer/optimizer.h
new file mode 100644
index 0000000000000000000000000000000000000000..e7a557ef7b040f2ffe21551e33a5d952a4815cb0
--- /dev/null
+++ b/pgsql/include/server/optimizer/optimizer.h
@@ -0,0 +1,204 @@
+/*-------------------------------------------------------------------------
+ *
+ * optimizer.h
+ * External API for the Postgres planner.
+ *
+ * This header is meant to define everything that the core planner
+ * exposes for use by non-planner modules.
+ *
+ * Note that there are files outside src/backend/optimizer/ that are
+ * considered planner modules, because they're too much in bed with
+ * planner operations to be treated otherwise. FDW planning code is an
+ * example. For the most part, however, code outside the core planner
+ * should not need to include any optimizer/ header except this one.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/optimizer.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef OPTIMIZER_H
+#define OPTIMIZER_H
+
+#include "nodes/parsenodes.h"
+
+/*
+ * We don't want to include nodes/pathnodes.h here, because non-planner
+ * code should generally treat PlannerInfo as an opaque typedef.
+ * But we'd like such code to use that typedef name, so define the
+ * typedef either here or in pathnodes.h, whichever is read first.
+ */
+#ifndef HAVE_PLANNERINFO_TYPEDEF
+typedef struct PlannerInfo PlannerInfo;
+#define HAVE_PLANNERINFO_TYPEDEF 1
+#endif
+
+/* Likewise for IndexOptInfo and SpecialJoinInfo. */
+#ifndef HAVE_INDEXOPTINFO_TYPEDEF
+typedef struct IndexOptInfo IndexOptInfo;
+#define HAVE_INDEXOPTINFO_TYPEDEF 1
+#endif
+#ifndef HAVE_SPECIALJOININFO_TYPEDEF
+typedef struct SpecialJoinInfo SpecialJoinInfo;
+#define HAVE_SPECIALJOININFO_TYPEDEF 1
+#endif
+
+/* It also seems best not to include plannodes.h, params.h, or htup.h here */
+struct PlannedStmt;
+struct ParamListInfoData;
+struct HeapTupleData;
+
+
+/* in path/clausesel.c: */
+
+extern Selectivity clause_selectivity(PlannerInfo *root,
+ Node *clause,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo);
+extern Selectivity clause_selectivity_ext(PlannerInfo *root,
+ Node *clause,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo,
+ bool use_extended_stats);
+extern Selectivity clauselist_selectivity(PlannerInfo *root,
+ List *clauses,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo);
+extern Selectivity clauselist_selectivity_ext(PlannerInfo *root,
+ List *clauses,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo,
+ bool use_extended_stats);
+
+/* in path/costsize.c: */
+
+/* widely used cost parameters */
+extern PGDLLIMPORT double seq_page_cost;
+extern PGDLLIMPORT double random_page_cost;
+extern PGDLLIMPORT double cpu_tuple_cost;
+extern PGDLLIMPORT double cpu_index_tuple_cost;
+extern PGDLLIMPORT double cpu_operator_cost;
+extern PGDLLIMPORT double parallel_tuple_cost;
+extern PGDLLIMPORT double parallel_setup_cost;
+extern PGDLLIMPORT double recursive_worktable_factor;
+extern PGDLLIMPORT int effective_cache_size;
+
+extern double clamp_row_est(double nrows);
+extern long clamp_cardinality_to_long(Cardinality x);
+
+/* in path/indxpath.c: */
+
+extern bool is_pseudo_constant_for_index(PlannerInfo *root, Node *expr,
+ IndexOptInfo *index);
+
+/* in plan/planner.c: */
+
+/* possible values for debug_parallel_query */
+typedef enum
+{
+ DEBUG_PARALLEL_OFF,
+ DEBUG_PARALLEL_ON,
+ DEBUG_PARALLEL_REGRESS
+} DebugParallelMode;
+
+/* GUC parameters */
+extern PGDLLIMPORT int debug_parallel_query;
+extern PGDLLIMPORT bool parallel_leader_participation;
+
+extern struct PlannedStmt *planner(Query *parse, const char *query_string,
+ int cursorOptions,
+ struct ParamListInfoData *boundParams);
+
+extern Expr *expression_planner(Expr *expr);
+extern Expr *expression_planner_with_deps(Expr *expr,
+ List **relationOids,
+ List **invalItems);
+
+extern bool plan_cluster_use_sort(Oid tableOid, Oid indexOid);
+extern int plan_create_index_workers(Oid tableOid, Oid indexOid);
+
+/* in plan/setrefs.c: */
+
+extern void extract_query_dependencies(Node *query,
+ List **relationOids,
+ List **invalItems,
+ bool *hasRowSecurity);
+
+/* in prep/prepqual.c: */
+
+extern Node *negate_clause(Node *node);
+extern Expr *canonicalize_qual(Expr *qual, bool is_check);
+
+/* in util/clauses.c: */
+
+extern bool contain_mutable_functions(Node *clause);
+extern bool contain_mutable_functions_after_planning(Expr *expr);
+extern bool contain_volatile_functions(Node *clause);
+extern bool contain_volatile_functions_after_planning(Expr *expr);
+extern bool contain_volatile_functions_not_nextval(Node *clause);
+
+extern Node *eval_const_expressions(PlannerInfo *root, Node *node);
+
+extern void convert_saop_to_hashed_saop(Node *node);
+
+extern Node *estimate_expression_value(PlannerInfo *root, Node *node);
+
+extern Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
+ Oid result_collation);
+
+extern List *expand_function_arguments(List *args, bool include_out_arguments,
+ Oid result_type,
+ struct HeapTupleData *func_tuple);
+
+/* in util/predtest.c: */
+
+extern bool predicate_implied_by(List *predicate_list, List *clause_list,
+ bool weak);
+extern bool predicate_refuted_by(List *predicate_list, List *clause_list,
+ bool weak);
+
+/* in util/tlist.c: */
+
+extern int count_nonjunk_tlist_entries(List *tlist);
+extern TargetEntry *get_sortgroupref_tle(Index sortref,
+ List *targetList);
+extern TargetEntry *get_sortgroupclause_tle(SortGroupClause *sgClause,
+ List *targetList);
+extern Node *get_sortgroupclause_expr(SortGroupClause *sgClause,
+ List *targetList);
+extern List *get_sortgrouplist_exprs(List *sgClauses,
+ List *targetList);
+extern SortGroupClause *get_sortgroupref_clause(Index sortref,
+ List *clauses);
+extern SortGroupClause *get_sortgroupref_clause_noerr(Index sortref,
+ List *clauses);
+
+/* in util/var.c: */
+
+/* Bits that can be OR'd into the flags argument of pull_var_clause() */
+#define PVC_INCLUDE_AGGREGATES 0x0001 /* include Aggrefs in output list */
+#define PVC_RECURSE_AGGREGATES 0x0002 /* recurse into Aggref arguments */
+#define PVC_INCLUDE_WINDOWFUNCS 0x0004 /* include WindowFuncs in output list */
+#define PVC_RECURSE_WINDOWFUNCS 0x0008 /* recurse into WindowFunc arguments */
+#define PVC_INCLUDE_PLACEHOLDERS 0x0010 /* include PlaceHolderVars in
+ * output list */
+#define PVC_RECURSE_PLACEHOLDERS 0x0020 /* recurse into PlaceHolderVar
+ * arguments */
+
+extern Bitmapset *pull_varnos(PlannerInfo *root, Node *node);
+extern Bitmapset *pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup);
+extern void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos);
+extern List *pull_vars_of_level(Node *node, int levelsup);
+extern bool contain_var_clause(Node *node);
+extern bool contain_vars_of_level(Node *node, int levelsup);
+extern int locate_var_of_level(Node *node, int levelsup);
+extern List *pull_var_clause(Node *node, int flags);
+extern Node *flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node);
+
+#endif /* OPTIMIZER_H */
diff --git a/pgsql/include/server/optimizer/orclauses.h b/pgsql/include/server/optimizer/orclauses.h
new file mode 100644
index 0000000000000000000000000000000000000000..f9dbe6a29721c9b1205debfce2a30b74c6647b35
--- /dev/null
+++ b/pgsql/include/server/optimizer/orclauses.h
@@ -0,0 +1,21 @@
+/*-------------------------------------------------------------------------
+ *
+ * orclauses.h
+ * prototypes for orclauses.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/orclauses.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ORCLAUSES_H
+#define ORCLAUSES_H
+
+#include "nodes/pathnodes.h"
+
+extern void extract_restriction_or_clauses(PlannerInfo *root);
+
+#endif /* ORCLAUSES_H */
diff --git a/pgsql/include/server/optimizer/paramassign.h b/pgsql/include/server/optimizer/paramassign.h
new file mode 100644
index 0000000000000000000000000000000000000000..55c27a62e57846953f60e3b6a017efc861195156
--- /dev/null
+++ b/pgsql/include/server/optimizer/paramassign.h
@@ -0,0 +1,34 @@
+/*-------------------------------------------------------------------------
+ *
+ * paramassign.h
+ * Functions for assigning PARAM_EXEC slots during planning.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/paramassign.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARAMASSIGN_H
+#define PARAMASSIGN_H
+
+#include "nodes/pathnodes.h"
+
+extern Param *replace_outer_var(PlannerInfo *root, Var *var);
+extern Param *replace_outer_placeholdervar(PlannerInfo *root,
+ PlaceHolderVar *phv);
+extern Param *replace_outer_agg(PlannerInfo *root, Aggref *agg);
+extern Param *replace_outer_grouping(PlannerInfo *root, GroupingFunc *grp);
+extern Param *replace_nestloop_param_var(PlannerInfo *root, Var *var);
+extern Param *replace_nestloop_param_placeholdervar(PlannerInfo *root,
+ PlaceHolderVar *phv);
+extern void process_subquery_nestloop_params(PlannerInfo *root,
+ List *subplan_params);
+extern List *identify_current_nestloop_params(PlannerInfo *root,
+ Relids leftrelids);
+extern Param *generate_new_exec_param(PlannerInfo *root, Oid paramtype,
+ int32 paramtypmod, Oid paramcollation);
+extern int assign_special_exec_param(PlannerInfo *root);
+
+#endif /* PARAMASSIGN_H */
diff --git a/pgsql/include/server/optimizer/pathnode.h b/pgsql/include/server/optimizer/pathnode.h
new file mode 100644
index 0000000000000000000000000000000000000000..001e75b5b769557a5da13b56b0edd3af9cc5b83f
--- /dev/null
+++ b/pgsql/include/server/optimizer/pathnode.h
@@ -0,0 +1,343 @@
+/*-------------------------------------------------------------------------
+ *
+ * pathnode.h
+ * prototypes for pathnode.c, relnode.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/pathnode.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PATHNODE_H
+#define PATHNODE_H
+
+#include "nodes/bitmapset.h"
+#include "nodes/pathnodes.h"
+
+
+/*
+ * prototypes for pathnode.c
+ */
+extern int compare_path_costs(Path *path1, Path *path2,
+ CostSelector criterion);
+extern int compare_fractional_path_costs(Path *path1, Path *path2,
+ double fraction);
+extern void set_cheapest(RelOptInfo *parent_rel);
+extern void add_path(RelOptInfo *parent_rel, Path *new_path);
+extern bool add_path_precheck(RelOptInfo *parent_rel,
+ Cost startup_cost, Cost total_cost,
+ List *pathkeys, Relids required_outer);
+extern void add_partial_path(RelOptInfo *parent_rel, Path *new_path);
+extern bool add_partial_path_precheck(RelOptInfo *parent_rel,
+ Cost total_cost, List *pathkeys);
+
+extern Path *create_seqscan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer, int parallel_workers);
+extern Path *create_samplescan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern IndexPath *create_index_path(PlannerInfo *root,
+ IndexOptInfo *index,
+ List *indexclauses,
+ List *indexorderbys,
+ List *indexorderbycols,
+ List *pathkeys,
+ ScanDirection indexscandir,
+ bool indexonly,
+ Relids required_outer,
+ double loop_count,
+ bool partial_path);
+extern BitmapHeapPath *create_bitmap_heap_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *bitmapqual,
+ Relids required_outer,
+ double loop_count,
+ int parallel_degree);
+extern BitmapAndPath *create_bitmap_and_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ List *bitmapquals);
+extern BitmapOrPath *create_bitmap_or_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ List *bitmapquals);
+extern TidPath *create_tidscan_path(PlannerInfo *root, RelOptInfo *rel,
+ List *tidquals, Relids required_outer);
+extern TidRangePath *create_tidrangescan_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ List *tidrangequals,
+ Relids required_outer);
+extern AppendPath *create_append_path(PlannerInfo *root, RelOptInfo *rel,
+ List *subpaths, List *partial_subpaths,
+ List *pathkeys, Relids required_outer,
+ int parallel_workers, bool parallel_aware,
+ double rows);
+extern MergeAppendPath *create_merge_append_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ List *subpaths,
+ List *pathkeys,
+ Relids required_outer);
+extern GroupResultPath *create_group_result_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ PathTarget *target,
+ List *havingqual);
+extern MaterialPath *create_material_path(RelOptInfo *rel, Path *subpath);
+extern MemoizePath *create_memoize_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ List *param_exprs,
+ List *hash_operators,
+ bool singlerow,
+ bool binary_mode,
+ double calls);
+extern UniquePath *create_unique_path(PlannerInfo *root, RelOptInfo *rel,
+ Path *subpath, SpecialJoinInfo *sjinfo);
+extern GatherPath *create_gather_path(PlannerInfo *root,
+ RelOptInfo *rel, Path *subpath, PathTarget *target,
+ Relids required_outer, double *rows);
+extern GatherMergePath *create_gather_merge_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ PathTarget *target,
+ List *pathkeys,
+ Relids required_outer,
+ double *rows);
+extern SubqueryScanPath *create_subqueryscan_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ bool trivial_pathtarget,
+ List *pathkeys,
+ Relids required_outer);
+extern Path *create_functionscan_path(PlannerInfo *root, RelOptInfo *rel,
+ List *pathkeys, Relids required_outer);
+extern Path *create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern Path *create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern Path *create_ctescan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern Path *create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern Path *create_resultscan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern Path *create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel,
+ Relids required_outer);
+extern ForeignPath *create_foreignscan_path(PlannerInfo *root, RelOptInfo *rel,
+ PathTarget *target,
+ double rows, Cost startup_cost, Cost total_cost,
+ List *pathkeys,
+ Relids required_outer,
+ Path *fdw_outerpath,
+ List *fdw_private);
+extern ForeignPath *create_foreign_join_path(PlannerInfo *root, RelOptInfo *rel,
+ PathTarget *target,
+ double rows, Cost startup_cost, Cost total_cost,
+ List *pathkeys,
+ Relids required_outer,
+ Path *fdw_outerpath,
+ List *fdw_private);
+extern ForeignPath *create_foreign_upper_path(PlannerInfo *root, RelOptInfo *rel,
+ PathTarget *target,
+ double rows, Cost startup_cost, Cost total_cost,
+ List *pathkeys,
+ Path *fdw_outerpath,
+ List *fdw_private);
+
+extern Relids calc_nestloop_required_outer(Relids outerrelids,
+ Relids outer_paramrels,
+ Relids innerrelids,
+ Relids inner_paramrels);
+extern Relids calc_non_nestloop_required_outer(Path *outer_path, Path *inner_path);
+
+extern NestPath *create_nestloop_path(PlannerInfo *root,
+ RelOptInfo *joinrel,
+ JoinType jointype,
+ JoinCostWorkspace *workspace,
+ JoinPathExtraData *extra,
+ Path *outer_path,
+ Path *inner_path,
+ List *restrict_clauses,
+ List *pathkeys,
+ Relids required_outer);
+
+extern MergePath *create_mergejoin_path(PlannerInfo *root,
+ RelOptInfo *joinrel,
+ JoinType jointype,
+ JoinCostWorkspace *workspace,
+ JoinPathExtraData *extra,
+ Path *outer_path,
+ Path *inner_path,
+ List *restrict_clauses,
+ List *pathkeys,
+ Relids required_outer,
+ List *mergeclauses,
+ List *outersortkeys,
+ List *innersortkeys);
+
+extern HashPath *create_hashjoin_path(PlannerInfo *root,
+ RelOptInfo *joinrel,
+ JoinType jointype,
+ JoinCostWorkspace *workspace,
+ JoinPathExtraData *extra,
+ Path *outer_path,
+ Path *inner_path,
+ bool parallel_hash,
+ List *restrict_clauses,
+ Relids required_outer,
+ List *hashclauses);
+
+extern ProjectionPath *create_projection_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ PathTarget *target);
+extern Path *apply_projection_to_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *path,
+ PathTarget *target);
+extern ProjectSetPath *create_set_projection_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ PathTarget *target);
+extern SortPath *create_sort_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ List *pathkeys,
+ double limit_tuples);
+extern IncrementalSortPath *create_incremental_sort_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ List *pathkeys,
+ int presorted_keys,
+ double limit_tuples);
+extern GroupPath *create_group_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ List *groupClause,
+ List *qual,
+ double numGroups);
+extern UpperUniquePath *create_upper_unique_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ int numCols,
+ double numGroups);
+extern AggPath *create_agg_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ PathTarget *target,
+ AggStrategy aggstrategy,
+ AggSplit aggsplit,
+ List *groupClause,
+ List *qual,
+ const AggClauseCosts *aggcosts,
+ double numGroups);
+extern GroupingSetsPath *create_groupingsets_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ List *having_qual,
+ AggStrategy aggstrategy,
+ List *rollups,
+ const AggClauseCosts *agg_costs);
+extern MinMaxAggPath *create_minmaxagg_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ PathTarget *target,
+ List *mmaggregates,
+ List *quals);
+extern WindowAggPath *create_windowagg_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ PathTarget *target,
+ List *windowFuncs,
+ WindowClause *winclause,
+ List *qual,
+ bool topwindow);
+extern SetOpPath *create_setop_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ SetOpCmd cmd,
+ SetOpStrategy strategy,
+ List *distinctList,
+ AttrNumber flagColIdx,
+ int firstFlag,
+ double numGroups,
+ double outputRows);
+extern RecursiveUnionPath *create_recursiveunion_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *leftpath,
+ Path *rightpath,
+ PathTarget *target,
+ List *distinctList,
+ int wtParam,
+ double numGroups);
+extern LockRowsPath *create_lockrows_path(PlannerInfo *root, RelOptInfo *rel,
+ Path *subpath, List *rowMarks, int epqParam);
+extern ModifyTablePath *create_modifytable_path(PlannerInfo *root,
+ RelOptInfo *rel,
+ Path *subpath,
+ CmdType operation, bool canSetTag,
+ Index nominalRelation, Index rootRelation,
+ bool partColsUpdated,
+ List *resultRelations,
+ List *updateColnosLists,
+ List *withCheckOptionLists, List *returningLists,
+ List *rowMarks, OnConflictExpr *onconflict,
+ List *mergeActionLists, int epqParam);
+extern LimitPath *create_limit_path(PlannerInfo *root, RelOptInfo *rel,
+ Path *subpath,
+ Node *limitOffset, Node *limitCount,
+ LimitOption limitOption,
+ int64 offset_est, int64 count_est);
+extern void adjust_limit_rows_costs(double *rows,
+ Cost *startup_cost, Cost *total_cost,
+ int64 offset_est, int64 count_est);
+
+extern Path *reparameterize_path(PlannerInfo *root, Path *path,
+ Relids required_outer,
+ double loop_count);
+extern Path *reparameterize_path_by_child(PlannerInfo *root, Path *path,
+ RelOptInfo *child_rel);
+
+/*
+ * prototypes for relnode.c
+ */
+extern void setup_simple_rel_arrays(PlannerInfo *root);
+extern void expand_planner_arrays(PlannerInfo *root, int add_size);
+extern RelOptInfo *build_simple_rel(PlannerInfo *root, int relid,
+ RelOptInfo *parent);
+extern RelOptInfo *find_base_rel(PlannerInfo *root, int relid);
+extern RelOptInfo *find_base_rel_ignore_join(PlannerInfo *root, int relid);
+extern RelOptInfo *find_join_rel(PlannerInfo *root, Relids relids);
+extern RelOptInfo *build_join_rel(PlannerInfo *root,
+ Relids joinrelids,
+ RelOptInfo *outer_rel,
+ RelOptInfo *inner_rel,
+ SpecialJoinInfo *sjinfo,
+ List *pushed_down_joins,
+ List **restrictlist_ptr);
+extern Relids min_join_parameterization(PlannerInfo *root,
+ Relids joinrelids,
+ RelOptInfo *outer_rel,
+ RelOptInfo *inner_rel);
+extern RelOptInfo *fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind,
+ Relids relids);
+extern Relids find_childrel_parents(PlannerInfo *root, RelOptInfo *rel);
+extern ParamPathInfo *get_baserel_parampathinfo(PlannerInfo *root,
+ RelOptInfo *baserel,
+ Relids required_outer);
+extern ParamPathInfo *get_joinrel_parampathinfo(PlannerInfo *root,
+ RelOptInfo *joinrel,
+ Path *outer_path,
+ Path *inner_path,
+ SpecialJoinInfo *sjinfo,
+ Relids required_outer,
+ List **restrict_clauses);
+extern ParamPathInfo *get_appendrel_parampathinfo(RelOptInfo *appendrel,
+ Relids required_outer);
+extern ParamPathInfo *find_param_path_info(RelOptInfo *rel,
+ Relids required_outer);
+extern Bitmapset *get_param_path_clause_serials(Path *path);
+extern RelOptInfo *build_child_join_rel(PlannerInfo *root,
+ RelOptInfo *outer_rel, RelOptInfo *inner_rel,
+ RelOptInfo *parent_joinrel, List *restrictlist,
+ SpecialJoinInfo *sjinfo);
+
+#endif /* PATHNODE_H */
diff --git a/pgsql/include/server/optimizer/paths.h b/pgsql/include/server/optimizer/paths.h
new file mode 100644
index 0000000000000000000000000000000000000000..50bc3b503a65b1bb42fb0c28654882e307f88795
--- /dev/null
+++ b/pgsql/include/server/optimizer/paths.h
@@ -0,0 +1,266 @@
+/*-------------------------------------------------------------------------
+ *
+ * paths.h
+ * prototypes for various files in optimizer/path
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/paths.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PATHS_H
+#define PATHS_H
+
+#include "nodes/pathnodes.h"
+
+
+/*
+ * allpaths.c
+ */
+extern PGDLLIMPORT bool enable_geqo;
+extern PGDLLIMPORT int geqo_threshold;
+extern PGDLLIMPORT int min_parallel_table_scan_size;
+extern PGDLLIMPORT int min_parallel_index_scan_size;
+
+/* Hook for plugins to get control in set_rel_pathlist() */
+typedef void (*set_rel_pathlist_hook_type) (PlannerInfo *root,
+ RelOptInfo *rel,
+ Index rti,
+ RangeTblEntry *rte);
+extern PGDLLIMPORT set_rel_pathlist_hook_type set_rel_pathlist_hook;
+
+/* Hook for plugins to get control in add_paths_to_joinrel() */
+typedef void (*set_join_pathlist_hook_type) (PlannerInfo *root,
+ RelOptInfo *joinrel,
+ RelOptInfo *outerrel,
+ RelOptInfo *innerrel,
+ JoinType jointype,
+ JoinPathExtraData *extra);
+extern PGDLLIMPORT set_join_pathlist_hook_type set_join_pathlist_hook;
+
+/* Hook for plugins to replace standard_join_search() */
+typedef RelOptInfo *(*join_search_hook_type) (PlannerInfo *root,
+ int levels_needed,
+ List *initial_rels);
+extern PGDLLIMPORT join_search_hook_type join_search_hook;
+
+
+extern RelOptInfo *make_one_rel(PlannerInfo *root, List *joinlist);
+extern RelOptInfo *standard_join_search(PlannerInfo *root, int levels_needed,
+ List *initial_rels);
+
+extern void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel,
+ bool override_rows);
+extern void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel,
+ bool override_rows);
+extern int compute_parallel_worker(RelOptInfo *rel, double heap_pages,
+ double index_pages, int max_workers);
+extern void create_partial_bitmap_paths(PlannerInfo *root, RelOptInfo *rel,
+ Path *bitmapqual);
+extern void generate_partitionwise_join_paths(PlannerInfo *root,
+ RelOptInfo *rel);
+
+#ifdef OPTIMIZER_DEBUG
+extern void debug_print_rel(PlannerInfo *root, RelOptInfo *rel);
+#endif
+
+/*
+ * indxpath.c
+ * routines to generate index paths
+ */
+extern void create_index_paths(PlannerInfo *root, RelOptInfo *rel);
+extern bool relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel,
+ List *restrictlist,
+ List *exprlist, List *oprlist);
+extern bool indexcol_is_bool_constant_for_query(PlannerInfo *root,
+ IndexOptInfo *index,
+ int indexcol);
+extern bool match_index_to_operand(Node *operand, int indexcol,
+ IndexOptInfo *index);
+extern void check_index_predicates(PlannerInfo *root, RelOptInfo *rel);
+
+/*
+ * tidpath.h
+ * routines to generate tid paths
+ */
+extern void create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel);
+
+/*
+ * joinpath.c
+ * routines to create join paths
+ */
+extern void add_paths_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel,
+ RelOptInfo *outerrel, RelOptInfo *innerrel,
+ JoinType jointype, SpecialJoinInfo *sjinfo,
+ List *restrictlist);
+
+/*
+ * joinrels.c
+ * routines to determine which relations to join
+ */
+extern void join_search_one_level(PlannerInfo *root, int level);
+extern RelOptInfo *make_join_rel(PlannerInfo *root,
+ RelOptInfo *rel1, RelOptInfo *rel2);
+extern Relids add_outer_joins_to_relids(PlannerInfo *root, Relids input_relids,
+ SpecialJoinInfo *sjinfo,
+ List **pushed_down_joins);
+extern bool have_join_order_restriction(PlannerInfo *root,
+ RelOptInfo *rel1, RelOptInfo *rel2);
+extern bool have_dangerous_phv(PlannerInfo *root,
+ Relids outer_relids, Relids inner_params);
+extern void mark_dummy_rel(RelOptInfo *rel);
+
+/*
+ * equivclass.c
+ * routines for managing EquivalenceClasses
+ */
+typedef bool (*ec_matches_callback_type) (PlannerInfo *root,
+ RelOptInfo *rel,
+ EquivalenceClass *ec,
+ EquivalenceMember *em,
+ void *arg);
+
+extern bool process_equivalence(PlannerInfo *root,
+ RestrictInfo **p_restrictinfo,
+ JoinDomain *jdomain);
+extern Expr *canonicalize_ec_expression(Expr *expr,
+ Oid req_type, Oid req_collation);
+extern void reconsider_outer_join_clauses(PlannerInfo *root);
+extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root,
+ Expr *expr,
+ List *opfamilies,
+ Oid opcintype,
+ Oid collation,
+ Index sortref,
+ Relids rel,
+ bool create_it);
+extern EquivalenceMember *find_ec_member_matching_expr(EquivalenceClass *ec,
+ Expr *expr,
+ Relids relids);
+extern EquivalenceMember *find_computable_ec_member(PlannerInfo *root,
+ EquivalenceClass *ec,
+ List *exprs,
+ Relids relids,
+ bool require_parallel_safe);
+extern bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel,
+ EquivalenceClass *ec,
+ bool require_parallel_safe);
+extern void generate_base_implied_equalities(PlannerInfo *root);
+extern List *generate_join_implied_equalities(PlannerInfo *root,
+ Relids join_relids,
+ Relids outer_relids,
+ RelOptInfo *inner_rel,
+ SpecialJoinInfo *sjinfo);
+extern List *generate_join_implied_equalities_for_ecs(PlannerInfo *root,
+ List *eclasses,
+ Relids join_relids,
+ Relids outer_relids,
+ RelOptInfo *inner_rel);
+extern bool exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2);
+extern EquivalenceClass *match_eclasses_to_foreign_key_col(PlannerInfo *root,
+ ForeignKeyOptInfo *fkinfo,
+ int colno);
+extern RestrictInfo *find_derived_clause_for_ec_member(EquivalenceClass *ec,
+ EquivalenceMember *em);
+extern void add_child_rel_equivalences(PlannerInfo *root,
+ AppendRelInfo *appinfo,
+ RelOptInfo *parent_rel,
+ RelOptInfo *child_rel);
+extern void add_child_join_rel_equivalences(PlannerInfo *root,
+ int nappinfos,
+ AppendRelInfo **appinfos,
+ RelOptInfo *parent_joinrel,
+ RelOptInfo *child_joinrel);
+extern List *generate_implied_equalities_for_column(PlannerInfo *root,
+ RelOptInfo *rel,
+ ec_matches_callback_type callback,
+ void *callback_arg,
+ Relids prohibited_rels);
+extern bool have_relevant_eclass_joinclause(PlannerInfo *root,
+ RelOptInfo *rel1, RelOptInfo *rel2);
+extern bool has_relevant_eclass_joinclause(PlannerInfo *root,
+ RelOptInfo *rel1);
+extern bool eclass_useful_for_merging(PlannerInfo *root,
+ EquivalenceClass *eclass,
+ RelOptInfo *rel);
+extern bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist);
+extern bool is_redundant_with_indexclauses(RestrictInfo *rinfo,
+ List *indexclauses);
+
+/*
+ * pathkeys.c
+ * utilities for matching and building path keys
+ */
+typedef enum
+{
+ PATHKEYS_EQUAL, /* pathkeys are identical */
+ PATHKEYS_BETTER1, /* pathkey 1 is a superset of pathkey 2 */
+ PATHKEYS_BETTER2, /* vice versa */
+ PATHKEYS_DIFFERENT /* neither pathkey includes the other */
+} PathKeysComparison;
+
+extern PathKeysComparison compare_pathkeys(List *keys1, List *keys2);
+extern bool pathkeys_contained_in(List *keys1, List *keys2);
+extern bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common);
+extern Path *get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
+ Relids required_outer,
+ CostSelector cost_criterion,
+ bool require_parallel_safe);
+extern Path *get_cheapest_fractional_path_for_pathkeys(List *paths,
+ List *pathkeys,
+ Relids required_outer,
+ double fraction);
+extern Path *get_cheapest_parallel_safe_total_inner(List *paths);
+extern List *build_index_pathkeys(PlannerInfo *root, IndexOptInfo *index,
+ ScanDirection scandir);
+extern List *build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel,
+ ScanDirection scandir, bool *partialkeys);
+extern List *build_expression_pathkey(PlannerInfo *root, Expr *expr,
+ Oid opno,
+ Relids rel, bool create_it);
+extern List *convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel,
+ List *subquery_pathkeys,
+ List *subquery_tlist);
+extern List *build_join_pathkeys(PlannerInfo *root,
+ RelOptInfo *joinrel,
+ JoinType jointype,
+ List *outer_pathkeys);
+extern List *make_pathkeys_for_sortclauses(PlannerInfo *root,
+ List *sortclauses,
+ List *tlist);
+extern List *make_pathkeys_for_sortclauses_extended(PlannerInfo *root,
+ List **sortclauses,
+ List *tlist,
+ bool remove_redundant,
+ bool *sortable);
+extern void initialize_mergeclause_eclasses(PlannerInfo *root,
+ RestrictInfo *restrictinfo);
+extern void update_mergeclause_eclasses(PlannerInfo *root,
+ RestrictInfo *restrictinfo);
+extern List *find_mergeclauses_for_outer_pathkeys(PlannerInfo *root,
+ List *pathkeys,
+ List *restrictinfos);
+extern List *select_outer_pathkeys_for_merge(PlannerInfo *root,
+ List *mergeclauses,
+ RelOptInfo *joinrel);
+extern List *make_inner_pathkeys_for_merge(PlannerInfo *root,
+ List *mergeclauses,
+ List *outer_pathkeys);
+extern List *trim_mergeclauses_for_inner_pathkeys(PlannerInfo *root,
+ List *mergeclauses,
+ List *pathkeys);
+extern List *truncate_useless_pathkeys(PlannerInfo *root,
+ RelOptInfo *rel,
+ List *pathkeys);
+extern bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel);
+extern List *append_pathkeys(List *target, List *source);
+extern PathKey *make_canonical_pathkey(PlannerInfo *root,
+ EquivalenceClass *eclass, Oid opfamily,
+ int strategy, bool nulls_first);
+extern void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel,
+ List *live_childrels);
+
+#endif /* PATHS_H */
diff --git a/pgsql/include/server/optimizer/placeholder.h b/pgsql/include/server/optimizer/placeholder.h
new file mode 100644
index 0000000000000000000000000000000000000000..acb9cf9f05cc015bae95abd0889dc532c04fb4c7
--- /dev/null
+++ b/pgsql/include/server/optimizer/placeholder.h
@@ -0,0 +1,33 @@
+/*-------------------------------------------------------------------------
+ *
+ * placeholder.h
+ * prototypes for optimizer/util/placeholder.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/placeholder.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PLACEHOLDER_H
+#define PLACEHOLDER_H
+
+#include "nodes/pathnodes.h"
+
+
+extern PlaceHolderVar *make_placeholder_expr(PlannerInfo *root, Expr *expr,
+ Relids phrels);
+extern PlaceHolderInfo *find_placeholder_info(PlannerInfo *root,
+ PlaceHolderVar *phv);
+extern void find_placeholders_in_jointree(PlannerInfo *root);
+extern void fix_placeholder_input_needed_levels(PlannerInfo *root);
+extern void add_placeholders_to_base_rels(PlannerInfo *root);
+extern void add_placeholders_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel,
+ RelOptInfo *outer_rel, RelOptInfo *inner_rel,
+ SpecialJoinInfo *sjinfo);
+extern bool contain_placeholder_references_to(PlannerInfo *root, Node *clause,
+ int relid);
+
+#endif /* PLACEHOLDER_H */
diff --git a/pgsql/include/server/optimizer/plancat.h b/pgsql/include/server/optimizer/plancat.h
new file mode 100644
index 0000000000000000000000000000000000000000..eb1c3ccc4bfb2d4ed08db2541490310b157fd9b7
--- /dev/null
+++ b/pgsql/include/server/optimizer/plancat.h
@@ -0,0 +1,80 @@
+/*-------------------------------------------------------------------------
+ *
+ * plancat.h
+ * prototypes for plancat.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/plancat.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PLANCAT_H
+#define PLANCAT_H
+
+#include "nodes/pathnodes.h"
+#include "utils/relcache.h"
+
+/* Hook for plugins to get control in get_relation_info() */
+typedef void (*get_relation_info_hook_type) (PlannerInfo *root,
+ Oid relationObjectId,
+ bool inhparent,
+ RelOptInfo *rel);
+extern PGDLLIMPORT get_relation_info_hook_type get_relation_info_hook;
+
+
+extern void get_relation_info(PlannerInfo *root, Oid relationObjectId,
+ bool inhparent, RelOptInfo *rel);
+
+extern List *infer_arbiter_indexes(PlannerInfo *root);
+
+extern void estimate_rel_size(Relation rel, int32 *attr_widths,
+ BlockNumber *pages, double *tuples, double *allvisfrac);
+
+extern int32 get_rel_data_width(Relation rel, int32 *attr_widths);
+extern int32 get_relation_data_width(Oid relid, int32 *attr_widths);
+
+extern bool relation_excluded_by_constraints(PlannerInfo *root,
+ RelOptInfo *rel, RangeTblEntry *rte);
+
+extern List *build_physical_tlist(PlannerInfo *root, RelOptInfo *rel);
+
+extern bool has_unique_index(RelOptInfo *rel, AttrNumber attno);
+
+extern Selectivity restriction_selectivity(PlannerInfo *root,
+ Oid operatorid,
+ List *args,
+ Oid inputcollid,
+ int varRelid);
+
+extern Selectivity join_selectivity(PlannerInfo *root,
+ Oid operatorid,
+ List *args,
+ Oid inputcollid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo);
+
+extern Selectivity function_selectivity(PlannerInfo *root,
+ Oid funcid,
+ List *args,
+ Oid inputcollid,
+ bool is_join,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo);
+
+extern void add_function_cost(PlannerInfo *root, Oid funcid, Node *node,
+ QualCost *cost);
+
+extern double get_function_rows(PlannerInfo *root, Oid funcid, Node *node);
+
+extern bool has_row_triggers(PlannerInfo *root, Index rti, CmdType event);
+
+extern bool has_stored_generated_columns(PlannerInfo *root, Index rti);
+
+extern Bitmapset *get_dependent_generated_columns(PlannerInfo *root, Index rti,
+ Bitmapset *target_cols);
+
+#endif /* PLANCAT_H */
diff --git a/pgsql/include/server/optimizer/planmain.h b/pgsql/include/server/optimizer/planmain.h
new file mode 100644
index 0000000000000000000000000000000000000000..5fc900737d8ff946f9290df2670bba1d0db27718
--- /dev/null
+++ b/pgsql/include/server/optimizer/planmain.h
@@ -0,0 +1,117 @@
+/*-------------------------------------------------------------------------
+ *
+ * planmain.h
+ * prototypes for various files in optimizer/plan
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/planmain.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PLANMAIN_H
+#define PLANMAIN_H
+
+#include "nodes/pathnodes.h"
+#include "nodes/plannodes.h"
+
+/* GUC parameters */
+#define DEFAULT_CURSOR_TUPLE_FRACTION 0.1
+extern PGDLLIMPORT double cursor_tuple_fraction;
+
+/* query_planner callback to compute query_pathkeys */
+typedef void (*query_pathkeys_callback) (PlannerInfo *root, void *extra);
+
+/*
+ * prototypes for plan/planmain.c
+ */
+extern RelOptInfo *query_planner(PlannerInfo *root,
+ query_pathkeys_callback qp_callback, void *qp_extra);
+
+/*
+ * prototypes for plan/planagg.c
+ */
+extern void preprocess_minmax_aggregates(PlannerInfo *root);
+
+/*
+ * prototypes for plan/createplan.c
+ */
+extern Plan *create_plan(PlannerInfo *root, Path *best_path);
+extern ForeignScan *make_foreignscan(List *qptlist, List *qpqual,
+ Index scanrelid, List *fdw_exprs, List *fdw_private,
+ List *fdw_scan_tlist, List *fdw_recheck_quals,
+ Plan *outer_plan);
+extern Plan *change_plan_targetlist(Plan *subplan, List *tlist,
+ bool tlist_parallel_safe);
+extern Plan *materialize_finished_plan(Plan *subplan);
+extern bool is_projection_capable_path(Path *path);
+extern bool is_projection_capable_plan(Plan *plan);
+
+/* External use of these functions is deprecated: */
+extern Sort *make_sort_from_sortclauses(List *sortcls, Plan *lefttree);
+extern Agg *make_agg(List *tlist, List *qual,
+ AggStrategy aggstrategy, AggSplit aggsplit,
+ int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations,
+ List *groupingSets, List *chain, double dNumGroups,
+ Size transitionSpace, Plan *lefttree);
+extern Limit *make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
+ LimitOption limitOption, int uniqNumCols,
+ AttrNumber *uniqColIdx, Oid *uniqOperators,
+ Oid *uniqCollations);
+
+/*
+ * prototypes for plan/initsplan.c
+ */
+extern PGDLLIMPORT int from_collapse_limit;
+extern PGDLLIMPORT int join_collapse_limit;
+
+extern void add_base_rels_to_query(PlannerInfo *root, Node *jtnode);
+extern void add_other_rels_to_query(PlannerInfo *root);
+extern void build_base_rel_tlists(PlannerInfo *root, List *final_tlist);
+extern void add_vars_to_targetlist(PlannerInfo *root, List *vars,
+ Relids where_needed);
+extern void find_lateral_references(PlannerInfo *root);
+extern void create_lateral_join_info(PlannerInfo *root);
+extern List *deconstruct_jointree(PlannerInfo *root);
+extern void distribute_restrictinfo_to_rels(PlannerInfo *root,
+ RestrictInfo *restrictinfo);
+extern RestrictInfo *process_implied_equality(PlannerInfo *root,
+ Oid opno,
+ Oid collation,
+ Expr *item1,
+ Expr *item2,
+ Relids qualscope,
+ Index security_level,
+ bool both_const);
+extern RestrictInfo *build_implied_join_equality(PlannerInfo *root,
+ Oid opno,
+ Oid collation,
+ Expr *item1,
+ Expr *item2,
+ Relids qualscope,
+ Index security_level);
+extern void match_foreign_keys_to_quals(PlannerInfo *root);
+
+/*
+ * prototypes for plan/analyzejoins.c
+ */
+extern List *remove_useless_joins(PlannerInfo *root, List *joinlist);
+extern void reduce_unique_semijoins(PlannerInfo *root);
+extern bool query_supports_distinctness(Query *query);
+extern bool query_is_distinct_for(Query *query, List *colnos, List *opids);
+extern bool innerrel_is_unique(PlannerInfo *root,
+ Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel,
+ JoinType jointype, List *restrictlist, bool force_cache);
+
+/*
+ * prototypes for plan/setrefs.c
+ */
+extern Plan *set_plan_references(PlannerInfo *root, Plan *plan);
+extern bool trivial_subqueryscan(SubqueryScan *plan);
+extern void record_plan_function_dependency(PlannerInfo *root, Oid funcid);
+extern void record_plan_type_dependency(PlannerInfo *root, Oid typid);
+extern bool extract_query_dependencies_walker(Node *node, PlannerInfo *context);
+
+#endif /* PLANMAIN_H */
diff --git a/pgsql/include/server/optimizer/planner.h b/pgsql/include/server/optimizer/planner.h
new file mode 100644
index 0000000000000000000000000000000000000000..fc2e15496ddfc7a1d840fffab517dd7d1c5684fa
--- /dev/null
+++ b/pgsql/include/server/optimizer/planner.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * planner.h
+ * prototypes for planner.c.
+ *
+ * Note that the primary entry points for planner.c are declared in
+ * optimizer/optimizer.h, because they're intended to be called from
+ * non-planner code. Declarations here are meant for use by other
+ * planner modules.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/planner.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PLANNER_H
+#define PLANNER_H
+
+#include "nodes/pathnodes.h"
+#include "nodes/plannodes.h"
+
+
+/* Hook for plugins to get control in planner() */
+typedef PlannedStmt *(*planner_hook_type) (Query *parse,
+ const char *query_string,
+ int cursorOptions,
+ ParamListInfo boundParams);
+extern PGDLLIMPORT planner_hook_type planner_hook;
+
+/* Hook for plugins to get control when grouping_planner() plans upper rels */
+typedef void (*create_upper_paths_hook_type) (PlannerInfo *root,
+ UpperRelationKind stage,
+ RelOptInfo *input_rel,
+ RelOptInfo *output_rel,
+ void *extra);
+extern PGDLLIMPORT create_upper_paths_hook_type create_upper_paths_hook;
+
+
+extern PlannedStmt *standard_planner(Query *parse, const char *query_string,
+ int cursorOptions,
+ ParamListInfo boundParams);
+
+extern PlannerInfo *subquery_planner(PlannerGlobal *glob, Query *parse,
+ PlannerInfo *parent_root,
+ bool hasRecursion, double tuple_fraction);
+
+extern RowMarkType select_rowmark_type(RangeTblEntry *rte,
+ LockClauseStrength strength);
+
+extern bool limit_needed(Query *parse);
+
+extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit);
+
+extern Path *get_cheapest_fractional_path(RelOptInfo *rel,
+ double tuple_fraction);
+
+extern Expr *preprocess_phv_expression(PlannerInfo *root, Expr *expr);
+
+#endif /* PLANNER_H */
diff --git a/pgsql/include/server/optimizer/prep.h b/pgsql/include/server/optimizer/prep.h
new file mode 100644
index 0000000000000000000000000000000000000000..54fd61c9c3ee20a246108306e043ca62948db85e
--- /dev/null
+++ b/pgsql/include/server/optimizer/prep.h
@@ -0,0 +1,58 @@
+/*-------------------------------------------------------------------------
+ *
+ * prep.h
+ * prototypes for files in optimizer/prep/
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/prep.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PREP_H
+#define PREP_H
+
+#include "nodes/pathnodes.h"
+#include "nodes/plannodes.h"
+
+
+/*
+ * prototypes for prepjointree.c
+ */
+extern void transform_MERGE_to_join(Query *parse);
+extern void replace_empty_jointree(Query *parse);
+extern void pull_up_sublinks(PlannerInfo *root);
+extern void preprocess_function_rtes(PlannerInfo *root);
+extern void pull_up_subqueries(PlannerInfo *root);
+extern void flatten_simple_union_all(PlannerInfo *root);
+extern void reduce_outer_joins(PlannerInfo *root);
+extern void remove_useless_result_rtes(PlannerInfo *root);
+extern Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins,
+ bool include_inner_joins);
+extern Relids get_relids_for_join(Query *query, int joinrelid);
+
+/*
+ * prototypes for preptlist.c
+ */
+extern void preprocess_targetlist(PlannerInfo *root);
+
+extern List *extract_update_targetlist_colnos(List *tlist);
+
+extern PlanRowMark *get_plan_rowmark(List *rowmarks, Index rtindex);
+
+/*
+ * prototypes for prepagg.c
+ */
+extern void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit,
+ AggClauseCosts *costs);
+extern void preprocess_aggrefs(PlannerInfo *root, Node *clause);
+
+/*
+ * prototypes for prepunion.c
+ */
+extern RelOptInfo *plan_set_operations(PlannerInfo *root);
+
+
+#endif /* PREP_H */
diff --git a/pgsql/include/server/optimizer/restrictinfo.h b/pgsql/include/server/optimizer/restrictinfo.h
new file mode 100644
index 0000000000000000000000000000000000000000..14cdce750cb7fd5f085303f83d25cfe17981e895
--- /dev/null
+++ b/pgsql/include/server/optimizer/restrictinfo.h
@@ -0,0 +1,53 @@
+/*-------------------------------------------------------------------------
+ *
+ * restrictinfo.h
+ * prototypes for restrictinfo.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/restrictinfo.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RESTRICTINFO_H
+#define RESTRICTINFO_H
+
+#include "nodes/pathnodes.h"
+
+
+/* Convenience macro for the common case of a valid-everywhere qual */
+#define make_simple_restrictinfo(root, clause) \
+ make_restrictinfo(root, clause, true, false, false, false, 0, \
+ NULL, NULL, NULL)
+
+extern RestrictInfo *make_restrictinfo(PlannerInfo *root,
+ Expr *clause,
+ bool is_pushed_down,
+ bool has_clone,
+ bool is_clone,
+ bool pseudoconstant,
+ Index security_level,
+ Relids required_relids,
+ Relids incompatible_relids,
+ Relids outer_relids);
+extern RestrictInfo *commute_restrictinfo(RestrictInfo *rinfo, Oid comm_op);
+extern bool restriction_is_or_clause(RestrictInfo *restrictinfo);
+extern bool restriction_is_securely_promotable(RestrictInfo *restrictinfo,
+ RelOptInfo *rel);
+extern List *get_actual_clauses(List *restrictinfo_list);
+extern List *extract_actual_clauses(List *restrictinfo_list,
+ bool pseudoconstant);
+extern void extract_actual_join_clauses(List *restrictinfo_list,
+ Relids joinrelids,
+ List **joinquals,
+ List **otherquals);
+extern bool has_pseudoconstant_clauses(PlannerInfo *root,
+ List *restrictinfo_list);
+extern bool join_clause_is_movable_to(RestrictInfo *rinfo, RelOptInfo *baserel);
+extern bool join_clause_is_movable_into(RestrictInfo *rinfo,
+ Relids currentrelids,
+ Relids current_and_outer);
+
+#endif /* RESTRICTINFO_H */
diff --git a/pgsql/include/server/optimizer/subselect.h b/pgsql/include/server/optimizer/subselect.h
new file mode 100644
index 0000000000000000000000000000000000000000..c03ffc56bf61d777f8560ab6796756c8a0e833ae
--- /dev/null
+++ b/pgsql/include/server/optimizer/subselect.h
@@ -0,0 +1,40 @@
+/*-------------------------------------------------------------------------
+ *
+ * subselect.h
+ * Planning routines for subselects.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/subselect.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SUBSELECT_H
+#define SUBSELECT_H
+
+#include "nodes/pathnodes.h"
+#include "nodes/plannodes.h"
+
+extern void SS_process_ctes(PlannerInfo *root);
+extern JoinExpr *convert_ANY_sublink_to_join(PlannerInfo *root,
+ SubLink *sublink,
+ Relids available_rels);
+extern JoinExpr *convert_EXISTS_sublink_to_join(PlannerInfo *root,
+ SubLink *sublink,
+ bool under_not,
+ Relids available_rels);
+extern Node *SS_replace_correlation_vars(PlannerInfo *root, Node *expr);
+extern Node *SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual);
+extern void SS_identify_outer_params(PlannerInfo *root);
+extern void SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel);
+extern void SS_attach_initplans(PlannerInfo *root, Plan *plan);
+extern void SS_finalize_plan(PlannerInfo *root, Plan *plan);
+extern Param *SS_make_initplan_output_param(PlannerInfo *root,
+ Oid resulttype, int32 resulttypmod,
+ Oid resultcollation);
+extern void SS_make_initplan_from_plan(PlannerInfo *root,
+ PlannerInfo *subroot, Plan *plan,
+ Param *prm);
+
+#endif /* SUBSELECT_H */
diff --git a/pgsql/include/server/optimizer/tlist.h b/pgsql/include/server/optimizer/tlist.h
new file mode 100644
index 0000000000000000000000000000000000000000..ca64309c32945ea0f1ba29336d7feecad4455ad2
--- /dev/null
+++ b/pgsql/include/server/optimizer/tlist.h
@@ -0,0 +1,56 @@
+/*-------------------------------------------------------------------------
+ *
+ * tlist.h
+ * prototypes for tlist.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/optimizer/tlist.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TLIST_H
+#define TLIST_H
+
+#include "nodes/pathnodes.h"
+
+
+extern TargetEntry *tlist_member(Expr *node, List *targetlist);
+
+extern List *add_to_flat_tlist(List *tlist, List *exprs);
+
+extern List *get_tlist_exprs(List *tlist, bool includeJunk);
+
+extern bool tlist_same_exprs(List *tlist1, List *tlist2);
+
+extern bool tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK);
+extern bool tlist_same_collations(List *tlist, List *colCollations, bool junkOK);
+
+extern void apply_tlist_labeling(List *dest_tlist, List *src_tlist);
+
+extern Oid *extract_grouping_ops(List *groupClause);
+extern Oid *extract_grouping_collations(List *groupClause, List *tlist);
+extern AttrNumber *extract_grouping_cols(List *groupClause, List *tlist);
+extern bool grouping_is_sortable(List *groupClause);
+extern bool grouping_is_hashable(List *groupClause);
+
+extern PathTarget *make_pathtarget_from_tlist(List *tlist);
+extern List *make_tlist_from_pathtarget(PathTarget *target);
+extern PathTarget *copy_pathtarget(PathTarget *src);
+extern PathTarget *create_empty_pathtarget(void);
+extern void add_column_to_pathtarget(PathTarget *target,
+ Expr *expr, Index sortgroupref);
+extern void add_new_column_to_pathtarget(PathTarget *target, Expr *expr);
+extern void add_new_columns_to_pathtarget(PathTarget *target, List *exprs);
+extern void apply_pathtarget_labeling_to_tlist(List *tlist, PathTarget *target);
+extern void split_pathtarget_at_srfs(PlannerInfo *root,
+ PathTarget *target, PathTarget *input_target,
+ List **targets, List **targets_contain_srfs);
+
+/* Convenience macro to get a PathTarget with valid cost/width fields */
+#define create_pathtarget(root, tlist) \
+ set_pathtarget_cost_width(root, make_pathtarget_from_tlist(tlist))
+
+#endif /* TLIST_H */
diff --git a/pgsql/include/server/parser/analyze.h b/pgsql/include/server/parser/analyze.h
new file mode 100644
index 0000000000000000000000000000000000000000..c96483ae78486a15095b069557523c7d03b0c5b5
--- /dev/null
+++ b/pgsql/include/server/parser/analyze.h
@@ -0,0 +1,64 @@
+/*-------------------------------------------------------------------------
+ *
+ * analyze.h
+ * parse analysis for optimizable statements
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/analyze.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ANALYZE_H
+#define ANALYZE_H
+
+#include "nodes/params.h"
+#include "nodes/queryjumble.h"
+#include "parser/parse_node.h"
+
+/* Hook for plugins to get control at end of parse analysis */
+typedef void (*post_parse_analyze_hook_type) (ParseState *pstate,
+ Query *query,
+ JumbleState *jstate);
+extern PGDLLIMPORT post_parse_analyze_hook_type post_parse_analyze_hook;
+
+
+extern Query *parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText,
+ const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv);
+extern Query *parse_analyze_varparams(RawStmt *parseTree, const char *sourceText,
+ Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv);
+extern Query *parse_analyze_withcb(RawStmt *parseTree, const char *sourceText,
+ ParserSetupHook parserSetup,
+ void *parserSetupArg,
+ QueryEnvironment *queryEnv);
+
+extern Query *parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
+ CommonTableExpr *parentCTE,
+ bool locked_from_parent,
+ bool resolve_unknowns);
+
+extern List *transformInsertRow(ParseState *pstate, List *exprlist,
+ List *stmtcols, List *icolumns, List *attrnos,
+ bool strip_indirection);
+extern List *transformUpdateTargetList(ParseState *pstate,
+ List *origTlist);
+extern Query *transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree);
+extern Query *transformStmt(ParseState *pstate, Node *parseTree);
+
+extern bool stmt_requires_parse_analysis(RawStmt *parseTree);
+extern bool analyze_requires_snapshot(RawStmt *parseTree);
+
+extern const char *LCS_asString(LockClauseStrength strength);
+extern void CheckSelectLocking(Query *qry, LockClauseStrength strength);
+extern void applyLockingClause(Query *qry, Index rtindex,
+ LockClauseStrength strength,
+ LockWaitPolicy waitPolicy, bool pushedDown);
+
+extern List *BuildOnConflictExcludedTargetlist(Relation targetrel,
+ Index exclRelIndex);
+
+extern SortGroupClause *makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash);
+
+#endif /* ANALYZE_H */
diff --git a/pgsql/include/server/parser/kwlist.h b/pgsql/include/server/parser/kwlist.h
new file mode 100644
index 0000000000000000000000000000000000000000..f5b2e61ca527bb16556400975aee85913ef10a0e
--- /dev/null
+++ b/pgsql/include/server/parser/kwlist.h
@@ -0,0 +1,498 @@
+/*-------------------------------------------------------------------------
+ *
+ * kwlist.h
+ *
+ * The keyword lists are kept in their own source files for use by
+ * automatic tools. The exact representation of a keyword is determined
+ * by the PG_KEYWORD macro, which is not defined in this file; it can
+ * be defined by the caller for special purposes.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/parser/kwlist.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* there is deliberately not an #ifndef KWLIST_H here */
+
+/*
+ * List of keyword (name, token-value, category, bare-label-status) entries.
+ *
+ * Note: gen_keywordlist.pl requires the entries to appear in ASCII order.
+ */
+
+/* name, value, category, is-bare-label */
+PG_KEYWORD("abort", ABORT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("absent", ABSENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("absolute", ABSOLUTE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("access", ACCESS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("action", ACTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("add", ADD_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("admin", ADMIN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("after", AFTER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("aggregate", AGGREGATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("all", ALL, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("also", ALSO, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("alter", ALTER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("always", ALWAYS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("analyse", ANALYSE, RESERVED_KEYWORD, BARE_LABEL) /* British spelling */
+PG_KEYWORD("analyze", ANALYZE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("and", AND, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("any", ANY, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("array", ARRAY, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("as", AS, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("asc", ASC, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("asensitive", ASENSITIVE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("assertion", ASSERTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("assignment", ASSIGNMENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("asymmetric", ASYMMETRIC, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("at", AT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("atomic", ATOMIC, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("attach", ATTACH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("attribute", ATTRIBUTE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("authorization", AUTHORIZATION, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("backward", BACKWARD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("before", BEFORE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("begin", BEGIN_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("between", BETWEEN, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("bigint", BIGINT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("binary", BINARY, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("bit", BIT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("boolean", BOOLEAN_P, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("both", BOTH, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("breadth", BREADTH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("by", BY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cache", CACHE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("call", CALL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("called", CALLED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cascade", CASCADE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cascaded", CASCADED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("case", CASE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cast", CAST, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("catalog", CATALOG_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("chain", CHAIN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("char", CHAR_P, COL_NAME_KEYWORD, AS_LABEL)
+PG_KEYWORD("character", CHARACTER, COL_NAME_KEYWORD, AS_LABEL)
+PG_KEYWORD("characteristics", CHARACTERISTICS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("check", CHECK, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("checkpoint", CHECKPOINT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("class", CLASS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("close", CLOSE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cluster", CLUSTER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("coalesce", COALESCE, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("collate", COLLATE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("collation", COLLATION, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("column", COLUMN, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("columns", COLUMNS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("comment", COMMENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("comments", COMMENTS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("commit", COMMIT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("committed", COMMITTED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("compression", COMPRESSION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("concurrently", CONCURRENTLY, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("configuration", CONFIGURATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("conflict", CONFLICT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("connection", CONNECTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("constraint", CONSTRAINT, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("constraints", CONSTRAINTS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("content", CONTENT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("continue", CONTINUE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("conversion", CONVERSION_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("copy", COPY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cost", COST, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("create", CREATE, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("cross", CROSS, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("csv", CSV, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cube", CUBE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current", CURRENT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_catalog", CURRENT_CATALOG, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_date", CURRENT_DATE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_role", CURRENT_ROLE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_schema", CURRENT_SCHEMA, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_time", CURRENT_TIME, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_timestamp", CURRENT_TIMESTAMP, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("current_user", CURRENT_USER, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cursor", CURSOR, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("cycle", CYCLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("data", DATA_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("database", DATABASE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("day", DAY_P, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("deallocate", DEALLOCATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("dec", DEC, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("decimal", DECIMAL_P, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("declare", DECLARE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("default", DEFAULT, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("defaults", DEFAULTS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("deferrable", DEFERRABLE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("deferred", DEFERRED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("definer", DEFINER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("delete", DELETE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("delimiter", DELIMITER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("delimiters", DELIMITERS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("depends", DEPENDS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("depth", DEPTH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("desc", DESC, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("detach", DETACH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("dictionary", DICTIONARY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("disable", DISABLE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("discard", DISCARD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("distinct", DISTINCT, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("do", DO, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("document", DOCUMENT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("domain", DOMAIN_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("double", DOUBLE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("drop", DROP, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("each", EACH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("else", ELSE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("enable", ENABLE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("encoding", ENCODING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("encrypted", ENCRYPTED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("end", END_P, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("enum", ENUM_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("escape", ESCAPE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("event", EVENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("except", EXCEPT, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("exclude", EXCLUDE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("excluding", EXCLUDING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("exclusive", EXCLUSIVE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("execute", EXECUTE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("exists", EXISTS, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("explain", EXPLAIN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("expression", EXPRESSION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("extension", EXTENSION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("external", EXTERNAL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("extract", EXTRACT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("false", FALSE_P, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("family", FAMILY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("fetch", FETCH, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("filter", FILTER, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("finalize", FINALIZE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("first", FIRST_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("float", FLOAT_P, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("following", FOLLOWING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("for", FOR, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("force", FORCE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("foreign", FOREIGN, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("format", FORMAT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("forward", FORWARD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("freeze", FREEZE, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("from", FROM, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("full", FULL, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("function", FUNCTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("functions", FUNCTIONS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("generated", GENERATED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("global", GLOBAL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("grant", GRANT, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("granted", GRANTED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("greatest", GREATEST, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("group", GROUP_P, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("grouping", GROUPING, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("groups", GROUPS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("handler", HANDLER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("having", HAVING, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("header", HEADER_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("hold", HOLD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("hour", HOUR_P, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("identity", IDENTITY_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("if", IF_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("ilike", ILIKE, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("immediate", IMMEDIATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("immutable", IMMUTABLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("implicit", IMPLICIT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("import", IMPORT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("in", IN_P, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("include", INCLUDE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("including", INCLUDING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("increment", INCREMENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("indent", INDENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("index", INDEX, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("indexes", INDEXES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("inherit", INHERIT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("inherits", INHERITS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("initially", INITIALLY, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("inline", INLINE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("inner", INNER_P, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("inout", INOUT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("input", INPUT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("insensitive", INSENSITIVE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("insert", INSERT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("instead", INSTEAD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("int", INT_P, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("integer", INTEGER, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("intersect", INTERSECT, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("interval", INTERVAL, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("into", INTO, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("invoker", INVOKER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("is", IS, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("isnull", ISNULL, TYPE_FUNC_NAME_KEYWORD, AS_LABEL)
+PG_KEYWORD("isolation", ISOLATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("join", JOIN, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("json", JSON, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("json_array", JSON_ARRAY, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("json_arrayagg", JSON_ARRAYAGG, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("json_object", JSON_OBJECT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("json_objectagg", JSON_OBJECTAGG, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("key", KEY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("keys", KEYS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("label", LABEL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("language", LANGUAGE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("large", LARGE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("last", LAST_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("lateral", LATERAL_P, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("leading", LEADING, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("leakproof", LEAKPROOF, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("least", LEAST, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("left", LEFT, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("level", LEVEL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("like", LIKE, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("limit", LIMIT, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("listen", LISTEN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("load", LOAD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("local", LOCAL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("localtime", LOCALTIME, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("localtimestamp", LOCALTIMESTAMP, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("location", LOCATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("lock", LOCK_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("locked", LOCKED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("logged", LOGGED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("mapping", MAPPING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("match", MATCH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("matched", MATCHED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("materialized", MATERIALIZED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("maxvalue", MAXVALUE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("merge", MERGE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("method", METHOD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("minute", MINUTE_P, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("minvalue", MINVALUE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("mode", MODE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("month", MONTH_P, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("move", MOVE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("name", NAME_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("names", NAMES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("national", NATIONAL, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("natural", NATURAL, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nchar", NCHAR, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("new", NEW, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("next", NEXT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nfc", NFC, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nfd", NFD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nfkc", NFKC, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nfkd", NFKD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("no", NO, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("none", NONE, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("normalize", NORMALIZE, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("normalized", NORMALIZED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("not", NOT, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nothing", NOTHING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("notify", NOTIFY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("notnull", NOTNULL, TYPE_FUNC_NAME_KEYWORD, AS_LABEL)
+PG_KEYWORD("nowait", NOWAIT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("null", NULL_P, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nullif", NULLIF, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("nulls", NULLS_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("numeric", NUMERIC, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("object", OBJECT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("of", OF, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("off", OFF, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("offset", OFFSET, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("oids", OIDS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("old", OLD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("on", ON, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("only", ONLY, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("operator", OPERATOR, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("option", OPTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("options", OPTIONS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("or", OR, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("order", ORDER, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("ordinality", ORDINALITY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("others", OTHERS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("out", OUT_P, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("outer", OUTER_P, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("over", OVER, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("overlaps", OVERLAPS, TYPE_FUNC_NAME_KEYWORD, AS_LABEL)
+PG_KEYWORD("overlay", OVERLAY, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("overriding", OVERRIDING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("owned", OWNED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("owner", OWNER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("parallel", PARALLEL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("parameter", PARAMETER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("parser", PARSER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("partial", PARTIAL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("partition", PARTITION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("passing", PASSING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("password", PASSWORD, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("placing", PLACING, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("plans", PLANS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("policy", POLICY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("position", POSITION, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("preceding", PRECEDING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("precision", PRECISION, COL_NAME_KEYWORD, AS_LABEL)
+PG_KEYWORD("prepare", PREPARE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("prepared", PREPARED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("preserve", PRESERVE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("primary", PRIMARY, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("prior", PRIOR, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("privileges", PRIVILEGES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("procedural", PROCEDURAL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("procedure", PROCEDURE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("procedures", PROCEDURES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("program", PROGRAM, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("publication", PUBLICATION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("quote", QUOTE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("range", RANGE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("read", READ, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("real", REAL, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("reassign", REASSIGN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("recheck", RECHECK, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("recursive", RECURSIVE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("ref", REF_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("references", REFERENCES, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("referencing", REFERENCING, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("refresh", REFRESH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("reindex", REINDEX, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("relative", RELATIVE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("release", RELEASE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("rename", RENAME, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("repeatable", REPEATABLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("replace", REPLACE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("replica", REPLICA, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("reset", RESET, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("restart", RESTART, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("restrict", RESTRICT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("return", RETURN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("returning", RETURNING, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("returns", RETURNS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("revoke", REVOKE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("right", RIGHT, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("role", ROLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("rollback", ROLLBACK, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("rollup", ROLLUP, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("routine", ROUTINE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("routines", ROUTINES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("row", ROW, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("rows", ROWS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("rule", RULE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("savepoint", SAVEPOINT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("scalar", SCALAR, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("schema", SCHEMA, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("schemas", SCHEMAS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("scroll", SCROLL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("search", SEARCH, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("second", SECOND_P, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("security", SECURITY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("select", SELECT, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("sequence", SEQUENCE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("sequences", SEQUENCES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("serializable", SERIALIZABLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("server", SERVER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("session", SESSION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("session_user", SESSION_USER, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("set", SET, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("setof", SETOF, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("sets", SETS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("share", SHARE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("show", SHOW, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("similar", SIMILAR, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("simple", SIMPLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("skip", SKIP, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("smallint", SMALLINT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("snapshot", SNAPSHOT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("some", SOME, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("sql", SQL_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("stable", STABLE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("standalone", STANDALONE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("start", START, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("statement", STATEMENT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("statistics", STATISTICS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("stdin", STDIN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("stdout", STDOUT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("storage", STORAGE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("stored", STORED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("strict", STRICT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("strip", STRIP_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("subscription", SUBSCRIPTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("substring", SUBSTRING, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("support", SUPPORT, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("symmetric", SYMMETRIC, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("sysid", SYSID, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("system", SYSTEM_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("system_user", SYSTEM_USER, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("table", TABLE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("tables", TABLES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("tablesample", TABLESAMPLE, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("tablespace", TABLESPACE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("temp", TEMP, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("template", TEMPLATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("temporary", TEMPORARY, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("text", TEXT_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("then", THEN, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("ties", TIES, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("time", TIME, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("timestamp", TIMESTAMP, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("to", TO, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("trailing", TRAILING, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("transaction", TRANSACTION, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("transform", TRANSFORM, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("treat", TREAT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("trigger", TRIGGER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("trim", TRIM, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("true", TRUE_P, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("truncate", TRUNCATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("trusted", TRUSTED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("type", TYPE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("types", TYPES_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("uescape", UESCAPE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("unbounded", UNBOUNDED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("uncommitted", UNCOMMITTED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("unencrypted", UNENCRYPTED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("union", UNION, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("unique", UNIQUE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("unknown", UNKNOWN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("unlisten", UNLISTEN, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("unlogged", UNLOGGED, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("until", UNTIL, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("update", UPDATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("user", USER, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("using", USING, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("vacuum", VACUUM, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("valid", VALID, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("validate", VALIDATE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("validator", VALIDATOR, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("value", VALUE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("values", VALUES, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("varchar", VARCHAR, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("variadic", VARIADIC, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("varying", VARYING, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("verbose", VERBOSE, TYPE_FUNC_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("version", VERSION_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("view", VIEW, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("views", VIEWS, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("volatile", VOLATILE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("when", WHEN, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("where", WHERE, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("whitespace", WHITESPACE_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("window", WINDOW, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("with", WITH, RESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("within", WITHIN, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("without", WITHOUT, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("work", WORK, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("wrapper", WRAPPER, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("write", WRITE, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xml", XML_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlattributes", XMLATTRIBUTES, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlconcat", XMLCONCAT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlelement", XMLELEMENT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlexists", XMLEXISTS, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlforest", XMLFOREST, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlnamespaces", XMLNAMESPACES, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlparse", XMLPARSE, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlpi", XMLPI, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlroot", XMLROOT, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmlserialize", XMLSERIALIZE, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("xmltable", XMLTABLE, COL_NAME_KEYWORD, BARE_LABEL)
+PG_KEYWORD("year", YEAR_P, UNRESERVED_KEYWORD, AS_LABEL)
+PG_KEYWORD("yes", YES_P, UNRESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("zone", ZONE, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/pgsql/include/server/parser/parse_agg.h b/pgsql/include/server/parser/parse_agg.h
new file mode 100644
index 0000000000000000000000000000000000000000..e9afd99d11fc54bd2c009954fa85b692a10f081a
--- /dev/null
+++ b/pgsql/include/server/parser/parse_agg.h
@@ -0,0 +1,65 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_agg.h
+ * handle aggregates and window functions in parser
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_agg.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_AGG_H
+#define PARSE_AGG_H
+
+#include "parser/parse_node.h"
+
+extern void transformAggregateCall(ParseState *pstate, Aggref *agg,
+ List *args, List *aggorder,
+ bool agg_distinct);
+
+extern Node *transformGroupingFunc(ParseState *pstate, GroupingFunc *p);
+
+extern void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
+ WindowDef *windef);
+
+extern void parseCheckAggregates(ParseState *pstate, Query *qry);
+
+extern List *expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit);
+
+extern int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes);
+
+extern Oid resolve_aggregate_transtype(Oid aggfuncid,
+ Oid aggtranstype,
+ Oid *inputTypes,
+ int numArguments);
+
+extern bool agg_args_support_sendreceive(Aggref *aggref);
+
+extern void build_aggregate_transfn_expr(Oid *agg_input_types,
+ int agg_num_inputs,
+ int agg_num_direct_inputs,
+ bool agg_variadic,
+ Oid agg_state_type,
+ Oid agg_input_collation,
+ Oid transfn_oid,
+ Oid invtransfn_oid,
+ Expr **transfnexpr,
+ Expr **invtransfnexpr);
+
+extern void build_aggregate_serialfn_expr(Oid serialfn_oid,
+ Expr **serialfnexpr);
+
+extern void build_aggregate_deserialfn_expr(Oid deserialfn_oid,
+ Expr **deserialfnexpr);
+
+extern void build_aggregate_finalfn_expr(Oid *agg_input_types,
+ int num_finalfn_inputs,
+ Oid agg_state_type,
+ Oid agg_result_type,
+ Oid agg_input_collation,
+ Oid finalfn_oid,
+ Expr **finalfnexpr);
+
+#endif /* PARSE_AGG_H */
diff --git a/pgsql/include/server/parser/parse_clause.h b/pgsql/include/server/parser/parse_clause.h
new file mode 100644
index 0000000000000000000000000000000000000000..8e26482db4200b43b0850cde823f10bb3ce82211
--- /dev/null
+++ b/pgsql/include/server/parser/parse_clause.h
@@ -0,0 +1,54 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_clause.h
+ * handle clauses in parser
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_clause.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_CLAUSE_H
+#define PARSE_CLAUSE_H
+
+#include "parser/parse_node.h"
+
+extern void transformFromClause(ParseState *pstate, List *frmList);
+extern int setTargetTable(ParseState *pstate, RangeVar *relation,
+ bool inh, bool alsoSource, AclMode requiredPerms);
+
+extern Node *transformWhereClause(ParseState *pstate, Node *clause,
+ ParseExprKind exprKind, const char *constructName);
+extern Node *transformLimitClause(ParseState *pstate, Node *clause,
+ ParseExprKind exprKind, const char *constructName,
+ LimitOption limitOption);
+extern List *transformGroupClause(ParseState *pstate, List *grouplist,
+ List **groupingSets,
+ List **targetlist, List *sortClause,
+ ParseExprKind exprKind, bool useSQL99);
+extern List *transformSortClause(ParseState *pstate, List *orderlist,
+ List **targetlist, ParseExprKind exprKind,
+ bool useSQL99);
+
+extern List *transformWindowDefinitions(ParseState *pstate,
+ List *windowdefs,
+ List **targetlist);
+
+extern List *transformDistinctClause(ParseState *pstate,
+ List **targetlist, List *sortClause, bool is_agg);
+extern List *transformDistinctOnClause(ParseState *pstate, List *distinctlist,
+ List **targetlist, List *sortClause);
+extern void transformOnConflictArbiter(ParseState *pstate,
+ OnConflictClause *onConflictClause,
+ List **arbiterExpr, Node **arbiterWhere,
+ Oid *constraint);
+
+extern List *addTargetToSortList(ParseState *pstate, TargetEntry *tle,
+ List *sortlist, List *targetlist, SortBy *sortby);
+extern Index assignSortGroupRef(TargetEntry *tle, List *tlist);
+extern bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList);
+
+#endif /* PARSE_CLAUSE_H */
diff --git a/pgsql/include/server/parser/parse_coerce.h b/pgsql/include/server/parser/parse_coerce.h
new file mode 100644
index 0000000000000000000000000000000000000000..35ce4a3547a15d8e5ead673e5f65f6e1f007ae8e
--- /dev/null
+++ b/pgsql/include/server/parser/parse_coerce.h
@@ -0,0 +1,102 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_coerce.h
+ * Routines for type coercion.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_coerce.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_COERCE_H
+#define PARSE_COERCE_H
+
+#include "parser/parse_node.h"
+
+
+/* Type categories (see TYPCATEGORY_xxx symbols in catalog/pg_type.h) */
+typedef char TYPCATEGORY;
+
+/* Result codes for find_coercion_pathway */
+typedef enum CoercionPathType
+{
+ COERCION_PATH_NONE, /* failed to find any coercion pathway */
+ COERCION_PATH_FUNC, /* apply the specified coercion function */
+ COERCION_PATH_RELABELTYPE, /* binary-compatible cast, no function */
+ COERCION_PATH_ARRAYCOERCE, /* need an ArrayCoerceExpr node */
+ COERCION_PATH_COERCEVIAIO /* need a CoerceViaIO node */
+} CoercionPathType;
+
+
+extern bool IsBinaryCoercible(Oid srctype, Oid targettype);
+extern bool IsBinaryCoercibleWithCast(Oid srctype, Oid targettype,
+ Oid *castoid);
+extern bool IsPreferredType(TYPCATEGORY category, Oid type);
+extern TYPCATEGORY TypeCategory(Oid type);
+
+extern Node *coerce_to_target_type(ParseState *pstate,
+ Node *expr, Oid exprtype,
+ Oid targettype, int32 targettypmod,
+ CoercionContext ccontext,
+ CoercionForm cformat,
+ int location);
+extern bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids,
+ CoercionContext ccontext);
+extern Node *coerce_type(ParseState *pstate, Node *node,
+ Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
+ CoercionContext ccontext, CoercionForm cformat, int location);
+extern Node *coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod,
+ Oid typeId,
+ CoercionContext ccontext, CoercionForm cformat, int location,
+ bool hideInputCoercion);
+
+extern Node *coerce_to_boolean(ParseState *pstate, Node *node,
+ const char *constructName);
+extern Node *coerce_to_specific_type(ParseState *pstate, Node *node,
+ Oid targetTypeId,
+ const char *constructName);
+
+extern Node *coerce_to_specific_type_typmod(ParseState *pstate, Node *node,
+ Oid targetTypeId, int32 targetTypmod,
+ const char *constructName);
+
+extern int parser_coercion_errposition(ParseState *pstate,
+ int coerce_location,
+ Node *input_expr);
+
+extern Oid select_common_type(ParseState *pstate, List *exprs,
+ const char *context, Node **which_expr);
+extern Node *coerce_to_common_type(ParseState *pstate, Node *node,
+ Oid targetTypeId,
+ const char *context);
+extern bool verify_common_type(Oid common_type, List *exprs);
+
+extern int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type);
+
+extern bool check_generic_type_consistency(const Oid *actual_arg_types,
+ const Oid *declared_arg_types,
+ int nargs);
+extern Oid enforce_generic_type_consistency(const Oid *actual_arg_types,
+ Oid *declared_arg_types,
+ int nargs,
+ Oid rettype,
+ bool allow_poly);
+
+extern char *check_valid_polymorphic_signature(Oid ret_type,
+ const Oid *declared_arg_types,
+ int nargs);
+extern char *check_valid_internal_signature(Oid ret_type,
+ const Oid *declared_arg_types,
+ int nargs);
+
+extern CoercionPathType find_coercion_pathway(Oid targetTypeId,
+ Oid sourceTypeId,
+ CoercionContext ccontext,
+ Oid *funcid);
+extern CoercionPathType find_typmod_coercion_function(Oid typeId,
+ Oid *funcid);
+
+#endif /* PARSE_COERCE_H */
diff --git a/pgsql/include/server/parser/parse_collate.h b/pgsql/include/server/parser/parse_collate.h
new file mode 100644
index 0000000000000000000000000000000000000000..a858deb0bce74274609ec95e2cfaa00b40eeb570
--- /dev/null
+++ b/pgsql/include/server/parser/parse_collate.h
@@ -0,0 +1,27 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_collate.h
+ * Routines for assigning collation information.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_collate.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_COLLATE_H
+#define PARSE_COLLATE_H
+
+#include "parser/parse_node.h"
+
+extern void assign_query_collations(ParseState *pstate, Query *query);
+
+extern void assign_list_collations(ParseState *pstate, List *exprs);
+
+extern void assign_expr_collations(ParseState *pstate, Node *expr);
+
+extern Oid select_common_collation(ParseState *pstate, List *exprs, bool none_ok);
+
+#endif /* PARSE_COLLATE_H */
diff --git a/pgsql/include/server/parser/parse_cte.h b/pgsql/include/server/parser/parse_cte.h
new file mode 100644
index 0000000000000000000000000000000000000000..3eebc770565a63df194e15a48bf3afbe419aa23e
--- /dev/null
+++ b/pgsql/include/server/parser/parse_cte.h
@@ -0,0 +1,24 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_cte.h
+ * handle CTEs (common table expressions) in parser
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_cte.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_CTE_H
+#define PARSE_CTE_H
+
+#include "parser/parse_node.h"
+
+extern List *transformWithClause(ParseState *pstate, WithClause *withClause);
+
+extern void analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte,
+ List *tlist);
+
+#endif /* PARSE_CTE_H */
diff --git a/pgsql/include/server/parser/parse_enr.h b/pgsql/include/server/parser/parse_enr.h
new file mode 100644
index 0000000000000000000000000000000000000000..edb2ee0d03e1ba61aa5fc5b8eceec539100fb456
--- /dev/null
+++ b/pgsql/include/server/parser/parse_enr.h
@@ -0,0 +1,22 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_enr.h
+ * Internal definitions for parser
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_enr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_ENR_H
+#define PARSE_ENR_H
+
+#include "parser/parse_node.h"
+
+extern bool name_matches_visible_ENR(ParseState *pstate, const char *refname);
+extern EphemeralNamedRelationMetadata get_visible_ENR(ParseState *pstate, const char *refname);
+
+#endif /* PARSE_ENR_H */
diff --git a/pgsql/include/server/parser/parse_expr.h b/pgsql/include/server/parser/parse_expr.h
new file mode 100644
index 0000000000000000000000000000000000000000..7d38ca75f7bd616a622b8c9a1918cf2dea37b0a7
--- /dev/null
+++ b/pgsql/include/server/parser/parse_expr.h
@@ -0,0 +1,25 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_expr.h
+ * handle expressions in parser
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_expr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_EXPR_H
+#define PARSE_EXPR_H
+
+#include "parser/parse_node.h"
+
+/* GUC parameters */
+extern PGDLLIMPORT bool Transform_null_equals;
+
+extern Node *transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind);
+
+extern const char *ParseExprKindName(ParseExprKind exprKind);
+
+#endif /* PARSE_EXPR_H */
diff --git a/pgsql/include/server/parser/parse_func.h b/pgsql/include/server/parser/parse_func.h
new file mode 100644
index 0000000000000000000000000000000000000000..e316f5da498532531aef5f1d531d615b8426e001
--- /dev/null
+++ b/pgsql/include/server/parser/parse_func.h
@@ -0,0 +1,74 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_func.h
+ *
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_func.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_FUNC_H
+#define PARSE_FUNC_H
+
+#include "catalog/namespace.h"
+#include "parser/parse_node.h"
+
+
+/* Result codes for func_get_detail */
+typedef enum
+{
+ FUNCDETAIL_NOTFOUND, /* no matching function */
+ FUNCDETAIL_MULTIPLE, /* too many matching functions */
+ FUNCDETAIL_NORMAL, /* found a matching regular function */
+ FUNCDETAIL_PROCEDURE, /* found a matching procedure */
+ FUNCDETAIL_AGGREGATE, /* found a matching aggregate function */
+ FUNCDETAIL_WINDOWFUNC, /* found a matching window function */
+ FUNCDETAIL_COERCION /* it's a type coercion request */
+} FuncDetailCode;
+
+
+extern Node *ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
+ Node *last_srf, FuncCall *fn, bool proc_call,
+ int location);
+
+extern FuncDetailCode func_get_detail(List *funcname,
+ List *fargs, List *fargnames,
+ int nargs, Oid *argtypes,
+ bool expand_variadic, bool expand_defaults,
+ bool include_out_arguments,
+ Oid *funcid, Oid *rettype,
+ bool *retset, int *nvargs, Oid *vatype,
+ Oid **true_typeids, List **argdefaults);
+
+extern int func_match_argtypes(int nargs,
+ Oid *input_typeids,
+ FuncCandidateList raw_candidates,
+ FuncCandidateList *candidates);
+
+extern FuncCandidateList func_select_candidate(int nargs,
+ Oid *input_typeids,
+ FuncCandidateList candidates);
+
+extern void make_fn_arguments(ParseState *pstate,
+ List *fargs,
+ Oid *actual_arg_types,
+ Oid *declared_arg_types);
+
+extern const char *funcname_signature_string(const char *funcname, int nargs,
+ List *argnames, const Oid *argtypes);
+extern const char *func_signature_string(List *funcname, int nargs,
+ List *argnames, const Oid *argtypes);
+
+extern Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes,
+ bool missing_ok);
+extern Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func,
+ bool missing_ok);
+
+extern void check_srf_call_placement(ParseState *pstate, Node *last_srf,
+ int location);
+
+#endif /* PARSE_FUNC_H */
diff --git a/pgsql/include/server/parser/parse_merge.h b/pgsql/include/server/parser/parse_merge.h
new file mode 100644
index 0000000000000000000000000000000000000000..751cbdf112a7d7b8a6147f04debf992771a4908f
--- /dev/null
+++ b/pgsql/include/server/parser/parse_merge.h
@@ -0,0 +1,21 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_merge.h
+ * handle MERGE statement in parser
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_merge.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_MERGE_H
+#define PARSE_MERGE_H
+
+#include "parser/parse_node.h"
+
+extern Query *transformMergeStmt(ParseState *pstate, MergeStmt *stmt);
+
+#endif /* PARSE_MERGE_H */
diff --git a/pgsql/include/server/parser/parse_node.h b/pgsql/include/server/parser/parse_node.h
new file mode 100644
index 0000000000000000000000000000000000000000..f589112d5e5f0bd224d71046bd883486955c2e00
--- /dev/null
+++ b/pgsql/include/server/parser/parse_node.h
@@ -0,0 +1,357 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_node.h
+ * Internal definitions for parser
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_node.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_NODE_H
+#define PARSE_NODE_H
+
+#include "nodes/parsenodes.h"
+#include "utils/queryenvironment.h"
+#include "utils/relcache.h"
+
+
+/* Forward references for some structs declared below */
+typedef struct ParseState ParseState;
+typedef struct ParseNamespaceItem ParseNamespaceItem;
+typedef struct ParseNamespaceColumn ParseNamespaceColumn;
+
+/*
+ * Expression kinds distinguished by transformExpr(). Many of these are not
+ * semantically distinct so far as expression transformation goes; rather,
+ * we distinguish them so that context-specific error messages can be printed.
+ *
+ * Note: EXPR_KIND_OTHER is not used in the core code, but is left for use
+ * by extension code that might need to call transformExpr(). The core code
+ * will not enforce any context-driven restrictions on EXPR_KIND_OTHER
+ * expressions, so the caller would have to check for sub-selects, aggregates,
+ * window functions, SRFs, etc if those need to be disallowed.
+ */
+typedef enum ParseExprKind
+{
+ EXPR_KIND_NONE = 0, /* "not in an expression" */
+ EXPR_KIND_OTHER, /* reserved for extensions */
+ EXPR_KIND_JOIN_ON, /* JOIN ON */
+ EXPR_KIND_JOIN_USING, /* JOIN USING */
+ EXPR_KIND_FROM_SUBSELECT, /* sub-SELECT in FROM clause */
+ EXPR_KIND_FROM_FUNCTION, /* function in FROM clause */
+ EXPR_KIND_WHERE, /* WHERE */
+ EXPR_KIND_HAVING, /* HAVING */
+ EXPR_KIND_FILTER, /* FILTER */
+ EXPR_KIND_WINDOW_PARTITION, /* window definition PARTITION BY */
+ EXPR_KIND_WINDOW_ORDER, /* window definition ORDER BY */
+ EXPR_KIND_WINDOW_FRAME_RANGE, /* window frame clause with RANGE */
+ EXPR_KIND_WINDOW_FRAME_ROWS, /* window frame clause with ROWS */
+ EXPR_KIND_WINDOW_FRAME_GROUPS, /* window frame clause with GROUPS */
+ EXPR_KIND_SELECT_TARGET, /* SELECT target list item */
+ EXPR_KIND_INSERT_TARGET, /* INSERT target list item */
+ EXPR_KIND_UPDATE_SOURCE, /* UPDATE assignment source item */
+ EXPR_KIND_UPDATE_TARGET, /* UPDATE assignment target item */
+ EXPR_KIND_MERGE_WHEN, /* MERGE WHEN [NOT] MATCHED condition */
+ EXPR_KIND_GROUP_BY, /* GROUP BY */
+ EXPR_KIND_ORDER_BY, /* ORDER BY */
+ EXPR_KIND_DISTINCT_ON, /* DISTINCT ON */
+ EXPR_KIND_LIMIT, /* LIMIT */
+ EXPR_KIND_OFFSET, /* OFFSET */
+ EXPR_KIND_RETURNING, /* RETURNING */
+ EXPR_KIND_VALUES, /* VALUES */
+ EXPR_KIND_VALUES_SINGLE, /* single-row VALUES (in INSERT only) */
+ EXPR_KIND_CHECK_CONSTRAINT, /* CHECK constraint for a table */
+ EXPR_KIND_DOMAIN_CHECK, /* CHECK constraint for a domain */
+ EXPR_KIND_COLUMN_DEFAULT, /* default value for a table column */
+ EXPR_KIND_FUNCTION_DEFAULT, /* default parameter value for function */
+ EXPR_KIND_INDEX_EXPRESSION, /* index expression */
+ EXPR_KIND_INDEX_PREDICATE, /* index predicate */
+ EXPR_KIND_STATS_EXPRESSION, /* extended statistics expression */
+ EXPR_KIND_ALTER_COL_TRANSFORM, /* transform expr in ALTER COLUMN TYPE */
+ EXPR_KIND_EXECUTE_PARAMETER, /* parameter value in EXECUTE */
+ EXPR_KIND_TRIGGER_WHEN, /* WHEN condition in CREATE TRIGGER */
+ EXPR_KIND_POLICY, /* USING or WITH CHECK expr in policy */
+ EXPR_KIND_PARTITION_BOUND, /* partition bound expression */
+ EXPR_KIND_PARTITION_EXPRESSION, /* PARTITION BY expression */
+ EXPR_KIND_CALL_ARGUMENT, /* procedure argument in CALL */
+ EXPR_KIND_COPY_WHERE, /* WHERE condition in COPY FROM */
+ EXPR_KIND_GENERATED_COLUMN, /* generation expression for a column */
+ EXPR_KIND_CYCLE_MARK, /* cycle mark value */
+} ParseExprKind;
+
+
+/*
+ * Function signatures for parser hooks
+ */
+typedef Node *(*PreParseColumnRefHook) (ParseState *pstate, ColumnRef *cref);
+typedef Node *(*PostParseColumnRefHook) (ParseState *pstate, ColumnRef *cref, Node *var);
+typedef Node *(*ParseParamRefHook) (ParseState *pstate, ParamRef *pref);
+typedef Node *(*CoerceParamHook) (ParseState *pstate, Param *param,
+ Oid targetTypeId, int32 targetTypeMod,
+ int location);
+
+
+/*
+ * State information used during parse analysis
+ *
+ * parentParseState: NULL in a top-level ParseState. When parsing a subquery,
+ * links to current parse state of outer query.
+ *
+ * p_sourcetext: source string that generated the raw parsetree being
+ * analyzed, or NULL if not available. (The string is used only to
+ * generate cursor positions in error messages: we need it to convert
+ * byte-wise locations in parse structures to character-wise cursor
+ * positions.)
+ *
+ * p_rtable: list of RTEs that will become the rangetable of the query.
+ * Note that neither relname nor refname of these entries are necessarily
+ * unique; searching the rtable by name is a bad idea.
+ *
+ * p_rteperminfos: list of RTEPermissionInfo containing an entry corresponding
+ * to each RTE_RELATION entry in p_rtable.
+ *
+ * p_joinexprs: list of JoinExpr nodes associated with p_rtable entries.
+ * This is one-for-one with p_rtable, but contains NULLs for non-join
+ * RTEs, and may be shorter than p_rtable if the last RTE(s) aren't joins.
+ *
+ * p_nullingrels: list of Bitmapsets associated with p_rtable entries, each
+ * containing the set of outer-join RTE indexes that can null that relation
+ * at the current point in the parse tree. This is one-for-one with p_rtable,
+ * but may be shorter than p_rtable, in which case the missing entries are
+ * implicitly empty (NULL). That rule allows us to save work when the query
+ * contains no outer joins.
+ *
+ * p_joinlist: list of join items (RangeTblRef and JoinExpr nodes) that
+ * will become the fromlist of the query's top-level FromExpr node.
+ *
+ * p_namespace: list of ParseNamespaceItems that represents the current
+ * namespace for table and column lookup. (The RTEs listed here may be just
+ * a subset of the whole rtable. See ParseNamespaceItem comments below.)
+ *
+ * p_lateral_active: true if we are currently parsing a LATERAL subexpression
+ * of this parse level. This makes p_lateral_only namespace items visible,
+ * whereas they are not visible when p_lateral_active is FALSE.
+ *
+ * p_ctenamespace: list of CommonTableExprs (WITH items) that are visible
+ * at the moment. This is entirely different from p_namespace because a CTE
+ * is not an RTE, rather "visibility" means you could make an RTE from it.
+ *
+ * p_future_ctes: list of CommonTableExprs (WITH items) that are not yet
+ * visible due to scope rules. This is used to help improve error messages.
+ *
+ * p_parent_cte: CommonTableExpr that immediately contains the current query,
+ * if any.
+ *
+ * p_target_relation: target relation, if query is INSERT/UPDATE/DELETE/MERGE
+ *
+ * p_target_nsitem: target relation's ParseNamespaceItem.
+ *
+ * p_is_insert: true to process assignment expressions like INSERT, false
+ * to process them like UPDATE. (Note this can change intra-statement, for
+ * cases like INSERT ON CONFLICT UPDATE.)
+ *
+ * p_windowdefs: list of WindowDefs representing WINDOW and OVER clauses.
+ * We collect these while transforming expressions and then transform them
+ * afterwards (so that any resjunk tlist items needed for the sort/group
+ * clauses end up at the end of the query tlist). A WindowDef's location in
+ * this list, counting from 1, is the winref number to use to reference it.
+ *
+ * p_expr_kind: kind of expression we're currently parsing, as per enum above;
+ * EXPR_KIND_NONE when not in an expression.
+ *
+ * p_next_resno: next TargetEntry.resno to assign, starting from 1.
+ *
+ * p_multiassign_exprs: partially-processed MultiAssignRef source expressions.
+ *
+ * p_locking_clause: query's FOR UPDATE/FOR SHARE clause, if any.
+ *
+ * p_locked_from_parent: true if parent query level applies FOR UPDATE/SHARE
+ * to this subquery as a whole.
+ *
+ * p_resolve_unknowns: resolve unknown-type SELECT output columns as type TEXT
+ * (this is true by default).
+ *
+ * p_hasAggs, p_hasWindowFuncs, etc: true if we've found any of the indicated
+ * constructs in the query.
+ *
+ * p_last_srf: the set-returning FuncExpr or OpExpr most recently found in
+ * the query, or NULL if none.
+ *
+ * p_pre_columnref_hook, etc: optional parser hook functions for modifying the
+ * interpretation of ColumnRefs and ParamRefs.
+ *
+ * p_ref_hook_state: passthrough state for the parser hook functions.
+ */
+struct ParseState
+{
+ ParseState *parentParseState; /* stack link */
+ const char *p_sourcetext; /* source text, or NULL if not available */
+ List *p_rtable; /* range table so far */
+ List *p_rteperminfos; /* list of RTEPermissionInfo nodes for each
+ * RTE_RELATION entry in rtable */
+ List *p_joinexprs; /* JoinExprs for RTE_JOIN p_rtable entries */
+ List *p_nullingrels; /* Bitmapsets showing nulling outer joins */
+ List *p_joinlist; /* join items so far (will become FromExpr
+ * node's fromlist) */
+ List *p_namespace; /* currently-referenceable RTEs (List of
+ * ParseNamespaceItem) */
+ bool p_lateral_active; /* p_lateral_only items visible? */
+ List *p_ctenamespace; /* current namespace for common table exprs */
+ List *p_future_ctes; /* common table exprs not yet in namespace */
+ CommonTableExpr *p_parent_cte; /* this query's containing CTE */
+ Relation p_target_relation; /* INSERT/UPDATE/DELETE/MERGE target rel */
+ ParseNamespaceItem *p_target_nsitem; /* target rel's NSItem, or NULL */
+ bool p_is_insert; /* process assignment like INSERT not UPDATE */
+ List *p_windowdefs; /* raw representations of window clauses */
+ ParseExprKind p_expr_kind; /* what kind of expression we're parsing */
+ int p_next_resno; /* next targetlist resno to assign */
+ List *p_multiassign_exprs; /* junk tlist entries for multiassign */
+ List *p_locking_clause; /* raw FOR UPDATE/FOR SHARE info */
+ bool p_locked_from_parent; /* parent has marked this subquery
+ * with FOR UPDATE/FOR SHARE */
+ bool p_resolve_unknowns; /* resolve unknown-type SELECT outputs as
+ * type text */
+
+ QueryEnvironment *p_queryEnv; /* curr env, incl refs to enclosing env */
+
+ /* Flags telling about things found in the query: */
+ bool p_hasAggs;
+ bool p_hasWindowFuncs;
+ bool p_hasTargetSRFs;
+ bool p_hasSubLinks;
+ bool p_hasModifyingCTE;
+
+ Node *p_last_srf; /* most recent set-returning func/op found */
+
+ /*
+ * Optional hook functions for parser callbacks. These are null unless
+ * set up by the caller of make_parsestate.
+ */
+ PreParseColumnRefHook p_pre_columnref_hook;
+ PostParseColumnRefHook p_post_columnref_hook;
+ ParseParamRefHook p_paramref_hook;
+ CoerceParamHook p_coerce_param_hook;
+ void *p_ref_hook_state; /* common passthrough link for above */
+};
+
+/*
+ * An element of a namespace list.
+ *
+ * p_names contains the table name and column names exposed by this nsitem.
+ * (Typically it's equal to p_rte->eref, but for a JOIN USING alias it's
+ * equal to p_rte->join_using_alias. Since the USING columns will be the
+ * join's first N columns, the net effect is just that we expose only those
+ * join columns via this nsitem.)
+ *
+ * p_rte and p_rtindex link to the underlying rangetable entry, and
+ * p_perminfo to the entry in rteperminfos.
+ *
+ * The p_nscolumns array contains info showing how to construct Vars
+ * referencing the names appearing in the p_names->colnames list.
+ *
+ * Namespace items with p_rel_visible set define which RTEs are accessible by
+ * qualified names, while those with p_cols_visible set define which RTEs are
+ * accessible by unqualified names. These sets are different because a JOIN
+ * without an alias does not hide the contained tables (so they must be
+ * visible for qualified references) but it does hide their columns
+ * (unqualified references to the columns refer to the JOIN, not the member
+ * tables, so we must not complain that such a reference is ambiguous).
+ * Conversely, a subquery without an alias does not hide the columns selected
+ * by the subquery, but it does hide the auto-generated relation name (so the
+ * subquery columns are visible for unqualified references only). Various
+ * special RTEs such as NEW/OLD for rules may also appear with only one flag
+ * set.
+ *
+ * While processing the FROM clause, namespace items may appear with
+ * p_lateral_only set, meaning they are visible only to LATERAL
+ * subexpressions. (The pstate's p_lateral_active flag tells whether we are
+ * inside such a subexpression at the moment.) If p_lateral_ok is not set,
+ * it's an error to actually use such a namespace item. One might think it
+ * would be better to just exclude such items from visibility, but the wording
+ * of SQL:2008 requires us to do it this way. We also use p_lateral_ok to
+ * forbid LATERAL references to an UPDATE/DELETE target table.
+ *
+ * At no time should a namespace list contain two entries that conflict
+ * according to the rules in checkNameSpaceConflicts; but note that those
+ * are more complicated than "must have different alias names", so in practice
+ * code searching a namespace list has to check for ambiguous references.
+ */
+struct ParseNamespaceItem
+{
+ Alias *p_names; /* Table and column names */
+ RangeTblEntry *p_rte; /* The relation's rangetable entry */
+ int p_rtindex; /* The relation's index in the rangetable */
+ RTEPermissionInfo *p_perminfo; /* The relation's rteperminfos entry */
+ /* array of same length as p_names->colnames: */
+ ParseNamespaceColumn *p_nscolumns; /* per-column data */
+ bool p_rel_visible; /* Relation name is visible? */
+ bool p_cols_visible; /* Column names visible as unqualified refs? */
+ bool p_lateral_only; /* Is only visible to LATERAL expressions? */
+ bool p_lateral_ok; /* If so, does join type allow use? */
+};
+
+/*
+ * Data about one column of a ParseNamespaceItem.
+ *
+ * We track the info needed to construct a Var referencing the column
+ * (but only for user-defined columns; system column references and
+ * whole-row references are handled separately).
+ *
+ * p_varno and p_varattno identify the semantic referent, which is a
+ * base-relation column unless the reference is to a join USING column that
+ * isn't semantically equivalent to either join input column (because it is a
+ * FULL join or the input column requires a type coercion). In those cases
+ * p_varno and p_varattno refer to the JOIN RTE.
+ *
+ * p_varnosyn and p_varattnosyn are either identical to p_varno/p_varattno,
+ * or they specify the column's position in an aliased JOIN RTE that hides
+ * the semantic referent RTE's refname. (That could be either the JOIN RTE
+ * in which this ParseNamespaceColumn entry exists, or some lower join level.)
+ *
+ * If an RTE contains a dropped column, its ParseNamespaceColumn struct
+ * is all-zeroes. (Conventionally, test for p_varno == 0 to detect this.)
+ */
+struct ParseNamespaceColumn
+{
+ Index p_varno; /* rangetable index */
+ AttrNumber p_varattno; /* attribute number of the column */
+ Oid p_vartype; /* pg_type OID */
+ int32 p_vartypmod; /* type modifier value */
+ Oid p_varcollid; /* OID of collation, or InvalidOid */
+ Index p_varnosyn; /* rangetable index of syntactic referent */
+ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */
+ bool p_dontexpand; /* not included in star expansion */
+};
+
+/* Support for parser_errposition_callback function */
+typedef struct ParseCallbackState
+{
+ ParseState *pstate;
+ int location;
+ ErrorContextCallback errcallback;
+} ParseCallbackState;
+
+
+extern ParseState *make_parsestate(ParseState *parentParseState);
+extern void free_parsestate(ParseState *pstate);
+extern int parser_errposition(ParseState *pstate, int location);
+
+extern void setup_parser_errposition_callback(ParseCallbackState *pcbstate,
+ ParseState *pstate, int location);
+extern void cancel_parser_errposition_callback(ParseCallbackState *pcbstate);
+
+extern void transformContainerType(Oid *containerType, int32 *containerTypmod);
+
+extern SubscriptingRef *transformContainerSubscripts(ParseState *pstate,
+ Node *containerBase,
+ Oid containerType,
+ int32 containerTypMod,
+ List *indirection,
+ bool isAssignment);
+extern Const *make_const(ParseState *pstate, A_Const *aconst);
+
+#endif /* PARSE_NODE_H */
diff --git a/pgsql/include/server/parser/parse_oper.h b/pgsql/include/server/parser/parse_oper.h
new file mode 100644
index 0000000000000000000000000000000000000000..5768a1ce87a50eeee64a1731b91db9d343177389
--- /dev/null
+++ b/pgsql/include/server/parser/parse_oper.h
@@ -0,0 +1,65 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_oper.h
+ * handle operator things for parser
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_oper.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_OPER_H
+#define PARSE_OPER_H
+
+#include "access/htup.h"
+#include "nodes/parsenodes.h"
+#include "parser/parse_node.h"
+
+
+typedef HeapTuple Operator;
+
+/* Routines to look up an operator given name and exact input type(s) */
+extern Oid LookupOperName(ParseState *pstate, List *opername,
+ Oid oprleft, Oid oprright,
+ bool noError, int location);
+extern Oid LookupOperWithArgs(ObjectWithArgs *oper, bool noError);
+
+/* Routines to find operators matching a name and given input types */
+/* NB: the selected operator may require coercion of the input types! */
+extern Operator oper(ParseState *pstate, List *opname, Oid ltypeId,
+ Oid rtypeId, bool noError, int location);
+extern Operator left_oper(ParseState *pstate, List *op, Oid arg,
+ bool noError, int location);
+
+/* Routines to find operators that DO NOT require coercion --- ie, their */
+/* input types are either exactly as given, or binary-compatible */
+extern Operator compatible_oper(ParseState *pstate, List *op,
+ Oid arg1, Oid arg2,
+ bool noError, int location);
+
+/* currently no need for compatible_left_oper/compatible_right_oper */
+
+/* Routines for identifying "<", "=", ">" operators for a type */
+extern void get_sort_group_operators(Oid argtype,
+ bool needLT, bool needEQ, bool needGT,
+ Oid *ltOpr, Oid *eqOpr, Oid *gtOpr,
+ bool *isHashable);
+
+/* Convenience routines for common calls on the above */
+extern Oid compatible_oper_opid(List *op, Oid arg1, Oid arg2, bool noError);
+
+/* Extract operator OID or underlying-function OID from an Operator tuple */
+extern Oid oprid(Operator op);
+extern Oid oprfuncid(Operator op);
+
+/* Build expression tree for an operator invocation */
+extern Expr *make_op(ParseState *pstate, List *opname,
+ Node *ltree, Node *rtree, Node *last_srf, int location);
+extern Expr *make_scalar_array_op(ParseState *pstate, List *opname,
+ bool useOr,
+ Node *ltree, Node *rtree, int location);
+
+#endif /* PARSE_OPER_H */
diff --git a/pgsql/include/server/parser/parse_param.h b/pgsql/include/server/parser/parse_param.h
new file mode 100644
index 0000000000000000000000000000000000000000..d4865e50f678029c59da76f3153a961e9f832657
--- /dev/null
+++ b/pgsql/include/server/parser/parse_param.h
@@ -0,0 +1,25 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_param.h
+ * handle parameters in parser
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_param.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_PARAM_H
+#define PARSE_PARAM_H
+
+#include "parser/parse_node.h"
+
+extern void setup_parse_fixed_parameters(ParseState *pstate,
+ const Oid *paramTypes, int numParams);
+extern void setup_parse_variable_parameters(ParseState *pstate,
+ Oid **paramTypes, int *numParams);
+extern void check_variable_parameters(ParseState *pstate, Query *query);
+extern bool query_contains_extern_params(Query *query);
+
+#endif /* PARSE_PARAM_H */
diff --git a/pgsql/include/server/parser/parse_relation.h b/pgsql/include/server/parser/parse_relation.h
new file mode 100644
index 0000000000000000000000000000000000000000..67d9b1e412c6a6cb025f32dfaba5a2ba5d39dffe
--- /dev/null
+++ b/pgsql/include/server/parser/parse_relation.h
@@ -0,0 +1,129 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_relation.h
+ * prototypes for parse_relation.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_relation.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_RELATION_H
+#define PARSE_RELATION_H
+
+#include "parser/parse_node.h"
+
+
+extern ParseNamespaceItem *refnameNamespaceItem(ParseState *pstate,
+ const char *schemaname,
+ const char *refname,
+ int location,
+ int *sublevels_up);
+extern CommonTableExpr *scanNameSpaceForCTE(ParseState *pstate,
+ const char *refname,
+ Index *ctelevelsup);
+extern bool scanNameSpaceForENR(ParseState *pstate, const char *refname);
+extern void checkNameSpaceConflicts(ParseState *pstate, List *namespace1,
+ List *namespace2);
+extern ParseNamespaceItem *GetNSItemByRangeTablePosn(ParseState *pstate,
+ int varno,
+ int sublevels_up);
+extern RangeTblEntry *GetRTEByRangeTablePosn(ParseState *pstate,
+ int varno,
+ int sublevels_up);
+extern CommonTableExpr *GetCTEForRTE(ParseState *pstate, RangeTblEntry *rte,
+ int rtelevelsup);
+extern Node *scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem,
+ int sublevels_up, const char *colname,
+ int location);
+extern Node *colNameToVar(ParseState *pstate, const char *colname, bool localonly,
+ int location);
+extern void markNullableIfNeeded(ParseState *pstate, Var *var);
+extern void markVarForSelectPriv(ParseState *pstate, Var *var);
+extern Relation parserOpenTable(ParseState *pstate, const RangeVar *relation,
+ int lockmode);
+extern ParseNamespaceItem *addRangeTableEntry(ParseState *pstate,
+ RangeVar *relation,
+ Alias *alias,
+ bool inh,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForRelation(ParseState *pstate,
+ Relation rel,
+ int lockmode,
+ Alias *alias,
+ bool inh,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForSubquery(ParseState *pstate,
+ Query *subquery,
+ Alias *alias,
+ bool lateral,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForFunction(ParseState *pstate,
+ List *funcnames,
+ List *funcexprs,
+ List *coldeflists,
+ RangeFunction *rangefunc,
+ bool lateral,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForValues(ParseState *pstate,
+ List *exprs,
+ List *coltypes,
+ List *coltypmods,
+ List *colcollations,
+ Alias *alias,
+ bool lateral,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForTableFunc(ParseState *pstate,
+ TableFunc *tf,
+ Alias *alias,
+ bool lateral,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForJoin(ParseState *pstate,
+ List *colnames,
+ ParseNamespaceColumn *nscolumns,
+ JoinType jointype,
+ int nummergedcols,
+ List *aliasvars,
+ List *leftcols,
+ List *rightcols,
+ Alias *join_using_alias,
+ Alias *alias,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForCTE(ParseState *pstate,
+ CommonTableExpr *cte,
+ Index levelsup,
+ RangeVar *rv,
+ bool inFromCl);
+extern ParseNamespaceItem *addRangeTableEntryForENR(ParseState *pstate,
+ RangeVar *rv,
+ bool inFromCl);
+extern RTEPermissionInfo *addRTEPermissionInfo(List **rteperminfos,
+ RangeTblEntry *rte);
+extern RTEPermissionInfo *getRTEPermissionInfo(List *rteperminfos,
+ RangeTblEntry *rte);
+extern bool isLockedRefname(ParseState *pstate, const char *refname);
+extern void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem,
+ bool addToJoinList,
+ bool addToRelNameSpace, bool addToVarNameSpace);
+extern void errorMissingRTE(ParseState *pstate, RangeVar *relation) pg_attribute_noreturn();
+extern void errorMissingColumn(ParseState *pstate,
+ const char *relname, const char *colname, int location) pg_attribute_noreturn();
+extern void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up,
+ int location, bool include_dropped,
+ List **colnames, List **colvars);
+extern List *expandNSItemVars(ParseState *pstate, ParseNamespaceItem *nsitem,
+ int sublevels_up, int location,
+ List **colnames);
+extern List *expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem,
+ int sublevels_up, bool require_col_privs,
+ int location);
+extern int attnameAttNum(Relation rd, const char *attname, bool sysColOK);
+extern const NameData *attnumAttName(Relation rd, int attid);
+extern Oid attnumTypeId(Relation rd, int attid);
+extern Oid attnumCollationId(Relation rd, int attid);
+extern bool isQueryUsingTempRelation(Query *query);
+
+#endif /* PARSE_RELATION_H */
diff --git a/pgsql/include/server/parser/parse_target.h b/pgsql/include/server/parser/parse_target.h
new file mode 100644
index 0000000000000000000000000000000000000000..d84c311bbcaf9d1a40b6556c7d3e987c5eaeeb82
--- /dev/null
+++ b/pgsql/include/server/parser/parse_target.h
@@ -0,0 +1,58 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_target.h
+ * handle target lists
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_target.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_TARGET_H
+#define PARSE_TARGET_H
+
+#include "parser/parse_node.h"
+
+
+extern List *transformTargetList(ParseState *pstate, List *targetlist,
+ ParseExprKind exprKind);
+extern List *transformExpressionList(ParseState *pstate, List *exprlist,
+ ParseExprKind exprKind, bool allowDefault);
+extern void resolveTargetListUnknowns(ParseState *pstate, List *targetlist);
+extern void markTargetListOrigins(ParseState *pstate, List *targetlist);
+extern TargetEntry *transformTargetEntry(ParseState *pstate,
+ Node *node, Node *expr, ParseExprKind exprKind,
+ char *colname, bool resjunk);
+extern Expr *transformAssignedExpr(ParseState *pstate, Expr *expr,
+ ParseExprKind exprKind,
+ const char *colname,
+ int attrno,
+ List *indirection,
+ int location);
+extern void updateTargetListEntry(ParseState *pstate, TargetEntry *tle,
+ char *colname, int attrno,
+ List *indirection,
+ int location);
+extern Node *transformAssignmentIndirection(ParseState *pstate,
+ Node *basenode,
+ const char *targetName,
+ bool targetIsSubscripting,
+ Oid targetTypeId,
+ int32 targetTypMod,
+ Oid targetCollation,
+ List *indirection,
+ ListCell *indirection_cell,
+ Node *rhs,
+ CoercionContext ccontext,
+ int location);
+extern List *checkInsertTargets(ParseState *pstate, List *cols,
+ List **attrnos);
+extern TupleDesc expandRecordVariable(ParseState *pstate, Var *var,
+ int levelsup);
+extern char *FigureColname(Node *node);
+extern char *FigureIndexColname(Node *node);
+
+#endif /* PARSE_TARGET_H */
diff --git a/pgsql/include/server/parser/parse_type.h b/pgsql/include/server/parser/parse_type.h
new file mode 100644
index 0000000000000000000000000000000000000000..848c467a182c2b87fce88556ab3bc7bb84b7cca0
--- /dev/null
+++ b/pgsql/include/server/parser/parse_type.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_type.h
+ * handle type operations for parser
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_type.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_TYPE_H
+#define PARSE_TYPE_H
+
+#include "access/htup.h"
+#include "parser/parse_node.h"
+
+
+typedef HeapTuple Type;
+
+extern Type LookupTypeName(ParseState *pstate, const TypeName *typeName,
+ int32 *typmod_p, bool missing_ok);
+extern Type LookupTypeNameExtended(ParseState *pstate,
+ const TypeName *typeName, int32 *typmod_p,
+ bool temp_ok, bool missing_ok);
+extern Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName,
+ bool missing_ok);
+extern Type typenameType(ParseState *pstate, const TypeName *typeName,
+ int32 *typmod_p);
+extern Oid typenameTypeId(ParseState *pstate, const TypeName *typeName);
+extern void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName,
+ Oid *typeid_p, int32 *typmod_p);
+
+extern char *TypeNameToString(const TypeName *typeName);
+extern char *TypeNameListToString(List *typenames);
+
+extern Oid LookupCollation(ParseState *pstate, List *collnames, int location);
+extern Oid GetColumnDefCollation(ParseState *pstate, ColumnDef *coldef, Oid typeOid);
+
+extern Type typeidType(Oid id);
+
+extern Oid typeTypeId(Type tp);
+extern int16 typeLen(Type t);
+extern bool typeByVal(Type t);
+extern char *typeTypeName(Type t);
+extern Oid typeTypeRelid(Type typ);
+extern Oid typeTypeCollation(Type typ);
+extern Datum stringTypeDatum(Type tp, char *string, int32 atttypmod);
+
+extern Oid typeidTypeRelid(Oid type_id);
+extern Oid typeOrDomainTypeRelid(Oid type_id);
+
+extern TypeName *typeStringToTypeName(const char *str, Node *escontext);
+extern bool parseTypeString(const char *str, Oid *typeid_p, int32 *typmod_p,
+ Node *escontext);
+
+/* true if typeid is composite, or domain over composite, but not RECORD */
+#define ISCOMPLEX(typeid) (typeOrDomainTypeRelid(typeid) != InvalidOid)
+
+#endif /* PARSE_TYPE_H */
diff --git a/pgsql/include/server/parser/parse_utilcmd.h b/pgsql/include/server/parser/parse_utilcmd.h
new file mode 100644
index 0000000000000000000000000000000000000000..2b40a0b5b19d903b0682f93595f0d1ec36b4608e
--- /dev/null
+++ b/pgsql/include/server/parser/parse_utilcmd.h
@@ -0,0 +1,44 @@
+/*-------------------------------------------------------------------------
+ *
+ * parse_utilcmd.h
+ * parse analysis for utility commands
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parse_utilcmd.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSE_UTILCMD_H
+#define PARSE_UTILCMD_H
+
+#include "parser/parse_node.h"
+
+struct AttrMap; /* avoid including attmap.h here */
+
+
+extern List *transformCreateStmt(CreateStmt *stmt, const char *queryString);
+extern AlterTableStmt *transformAlterTableStmt(Oid relid, AlterTableStmt *stmt,
+ const char *queryString,
+ List **beforeStmts,
+ List **afterStmts);
+extern IndexStmt *transformIndexStmt(Oid relid, IndexStmt *stmt,
+ const char *queryString);
+extern CreateStatsStmt *transformStatsStmt(Oid relid, CreateStatsStmt *stmt,
+ const char *queryString);
+extern void transformRuleStmt(RuleStmt *stmt, const char *queryString,
+ List **actions, Node **whereClause);
+extern List *transformCreateSchemaStmtElements(List *schemaElts,
+ const char *schemaName);
+extern PartitionBoundSpec *transformPartitionBound(ParseState *pstate, Relation parent,
+ PartitionBoundSpec *spec);
+extern List *expandTableLikeClause(RangeVar *heapRel,
+ TableLikeClause *table_like_clause);
+extern IndexStmt *generateClonedIndexStmt(RangeVar *heapRel,
+ Relation source_idx,
+ const struct AttrMap *attmap,
+ Oid *constraintOid);
+
+#endif /* PARSE_UTILCMD_H */
diff --git a/pgsql/include/server/parser/parser.h b/pgsql/include/server/parser/parser.h
new file mode 100644
index 0000000000000000000000000000000000000000..8d90064d87ba16a000b373095bf479ece291ec33
--- /dev/null
+++ b/pgsql/include/server/parser/parser.h
@@ -0,0 +1,68 @@
+/*-------------------------------------------------------------------------
+ *
+ * parser.h
+ * Definitions for the "raw" parser (flex and bison phases only)
+ *
+ * This is the external API for the raw lexing/parsing functions.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parser.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSER_H
+#define PARSER_H
+
+#include "nodes/parsenodes.h"
+
+
+/*
+ * RawParseMode determines the form of the string that raw_parser() accepts:
+ *
+ * RAW_PARSE_DEFAULT: parse a semicolon-separated list of SQL commands,
+ * and return a List of RawStmt nodes.
+ *
+ * RAW_PARSE_TYPE_NAME: parse a type name, and return a one-element List
+ * containing a TypeName node.
+ *
+ * RAW_PARSE_PLPGSQL_EXPR: parse a PL/pgSQL expression, and return
+ * a one-element List containing a RawStmt node.
+ *
+ * RAW_PARSE_PLPGSQL_ASSIGNn: parse a PL/pgSQL assignment statement,
+ * and return a one-element List containing a RawStmt node. "n"
+ * gives the number of dotted names comprising the target ColumnRef.
+ */
+typedef enum
+{
+ RAW_PARSE_DEFAULT = 0,
+ RAW_PARSE_TYPE_NAME,
+ RAW_PARSE_PLPGSQL_EXPR,
+ RAW_PARSE_PLPGSQL_ASSIGN1,
+ RAW_PARSE_PLPGSQL_ASSIGN2,
+ RAW_PARSE_PLPGSQL_ASSIGN3
+} RawParseMode;
+
+/* Values for the backslash_quote GUC */
+typedef enum
+{
+ BACKSLASH_QUOTE_OFF,
+ BACKSLASH_QUOTE_ON,
+ BACKSLASH_QUOTE_SAFE_ENCODING
+} BackslashQuoteType;
+
+/* GUC variables in scan.l (every one of these is a bad idea :-() */
+extern PGDLLIMPORT int backslash_quote;
+extern PGDLLIMPORT bool escape_string_warning;
+extern PGDLLIMPORT bool standard_conforming_strings;
+
+
+/* Primary entry point for the raw parsing functions */
+extern List *raw_parser(const char *str, RawParseMode mode);
+
+/* Utility functions exported by gram.y (perhaps these should be elsewhere) */
+extern List *SystemFuncName(char *name);
+extern TypeName *SystemTypeName(char *name);
+
+#endif /* PARSER_H */
diff --git a/pgsql/include/server/parser/parsetree.h b/pgsql/include/server/parser/parsetree.h
new file mode 100644
index 0000000000000000000000000000000000000000..69a9a258318a170d341453485d486efd2ede9636
--- /dev/null
+++ b/pgsql/include/server/parser/parsetree.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * parsetree.h
+ * Routines to access various components and subcomponents of
+ * parse trees.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/parsetree.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARSETREE_H
+#define PARSETREE_H
+
+#include "nodes/parsenodes.h"
+
+
+/* ----------------
+ * range table operations
+ * ----------------
+ */
+
+/*
+ * rt_fetch
+ *
+ * NB: this will crash and burn if handed an out-of-range RT index
+ */
+#define rt_fetch(rangetable_index, rangetable) \
+ ((RangeTblEntry *) list_nth(rangetable, (rangetable_index)-1))
+
+/*
+ * Given an RTE and an attribute number, return the appropriate
+ * variable name or alias for that attribute of that RTE.
+ */
+extern char *get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum);
+
+/*
+ * Check whether an attribute of an RTE has been dropped
+ */
+extern bool get_rte_attribute_is_dropped(RangeTblEntry *rte,
+ AttrNumber attnum);
+
+
+/* ----------------
+ * target list operations
+ * ----------------
+ */
+
+extern TargetEntry *get_tle_by_resno(List *tlist, AttrNumber resno);
+
+/* ----------------
+ * FOR UPDATE/SHARE info
+ * ----------------
+ */
+
+extern RowMarkClause *get_parse_rowmark(Query *qry, Index rtindex);
+
+#endif /* PARSETREE_H */
diff --git a/pgsql/include/server/parser/scanner.h b/pgsql/include/server/parser/scanner.h
new file mode 100644
index 0000000000000000000000000000000000000000..da013837cd91869cbfefbe4e516b33545475bee4
--- /dev/null
+++ b/pgsql/include/server/parser/scanner.h
@@ -0,0 +1,150 @@
+/*-------------------------------------------------------------------------
+ *
+ * scanner.h
+ * API for the core scanner (flex machine)
+ *
+ * The core scanner is also used by PL/pgSQL, so we provide a public API
+ * for it. However, the rest of the backend is only expected to use the
+ * higher-level API provided by parser.h.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/scanner.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef SCANNER_H
+#define SCANNER_H
+
+#include "common/keywords.h"
+
+/*
+ * The scanner returns extra data about scanned tokens in this union type.
+ * Note that this is a subset of the fields used in YYSTYPE of the bison
+ * parsers built atop the scanner.
+ */
+typedef union core_YYSTYPE
+{
+ int ival; /* for integer literals */
+ char *str; /* for identifiers and non-integer literals */
+ const char *keyword; /* canonical spelling of keywords */
+} core_YYSTYPE;
+
+/*
+ * We track token locations in terms of byte offsets from the start of the
+ * source string, not the column number/line number representation that
+ * bison uses by default. Also, to minimize overhead we track only one
+ * location (usually the first token location) for each construct, not
+ * the beginning and ending locations as bison does by default. It's
+ * therefore sufficient to make YYLTYPE an int.
+ */
+#define YYLTYPE int
+
+/*
+ * Another important component of the scanner's API is the token code numbers.
+ * However, those are not defined in this file, because bison insists on
+ * defining them for itself. The token codes used by the core scanner are
+ * the ASCII characters plus these:
+ * %token IDENT UIDENT FCONST SCONST USCONST BCONST XCONST Op
+ * %token ICONST PARAM
+ * %token TYPECAST DOT_DOT COLON_EQUALS EQUALS_GREATER
+ * %token LESS_EQUALS GREATER_EQUALS NOT_EQUALS
+ * The above token definitions *must* be the first ones declared in any
+ * bison parser built atop this scanner, so that they will have consistent
+ * numbers assigned to them (specifically, IDENT = 258 and so on).
+ */
+
+/*
+ * The YY_EXTRA data that a flex scanner allows us to pass around.
+ * Private state needed by the core scanner goes here. Note that the actual
+ * yy_extra struct may be larger and have this as its first component, thus
+ * allowing the calling parser to keep some fields of its own in YY_EXTRA.
+ */
+typedef struct core_yy_extra_type
+{
+ /*
+ * The string the scanner is physically scanning. We keep this mainly so
+ * that we can cheaply compute the offset of the current token (yytext).
+ */
+ char *scanbuf;
+ Size scanbuflen;
+
+ /*
+ * The keyword list to use, and the associated grammar token codes.
+ */
+ const ScanKeywordList *keywordlist;
+ const uint16 *keyword_tokens;
+
+ /*
+ * Scanner settings to use. These are initialized from the corresponding
+ * GUC variables by scanner_init(). Callers can modify them after
+ * scanner_init() if they don't want the scanner's behavior to follow the
+ * prevailing GUC settings.
+ */
+ int backslash_quote;
+ bool escape_string_warning;
+ bool standard_conforming_strings;
+
+ /*
+ * literalbuf is used to accumulate literal values when multiple rules are
+ * needed to parse a single literal. Call startlit() to reset buffer to
+ * empty, addlit() to add text. NOTE: the string in literalbuf is NOT
+ * necessarily null-terminated, but there always IS room to add a trailing
+ * null at offset literallen. We store a null only when we need it.
+ */
+ char *literalbuf; /* palloc'd expandable buffer */
+ int literallen; /* actual current string length */
+ int literalalloc; /* current allocated buffer size */
+
+ /*
+ * Random assorted scanner state.
+ */
+ int state_before_str_stop; /* start cond. before end quote */
+ int xcdepth; /* depth of nesting in slash-star comments */
+ char *dolqstart; /* current $foo$ quote start string */
+ YYLTYPE save_yylloc; /* one-element stack for PUSH_YYLLOC() */
+
+ /* first part of UTF16 surrogate pair for Unicode escapes */
+ int32 utf16_first_part;
+
+ /* state variables for literal-lexing warnings */
+ bool warn_on_first_escape;
+ bool saw_non_ascii;
+} core_yy_extra_type;
+
+/*
+ * The type of yyscanner is opaque outside scan.l.
+ */
+typedef void *core_yyscan_t;
+
+/* Support for scanner_errposition_callback function */
+typedef struct ScannerCallbackState
+{
+ core_yyscan_t yyscanner;
+ int location;
+ ErrorContextCallback errcallback;
+} ScannerCallbackState;
+
+
+/* Constant data exported from parser/scan.l */
+extern PGDLLIMPORT const uint16 ScanKeywordTokens[];
+
+/* Entry points in parser/scan.l */
+extern core_yyscan_t scanner_init(const char *str,
+ core_yy_extra_type *yyext,
+ const ScanKeywordList *keywordlist,
+ const uint16 *keyword_tokens);
+extern void scanner_finish(core_yyscan_t yyscanner);
+extern int core_yylex(core_YYSTYPE *yylval_param, YYLTYPE *yylloc_param,
+ core_yyscan_t yyscanner);
+extern int scanner_errposition(int location, core_yyscan_t yyscanner);
+extern void setup_scanner_errposition_callback(ScannerCallbackState *scbstate,
+ core_yyscan_t yyscanner,
+ int location);
+extern void cancel_scanner_errposition_callback(ScannerCallbackState *scbstate);
+extern void scanner_yyerror(const char *message, core_yyscan_t yyscanner) pg_attribute_noreturn();
+
+#endif /* SCANNER_H */
diff --git a/pgsql/include/server/parser/scansup.h b/pgsql/include/server/parser/scansup.h
new file mode 100644
index 0000000000000000000000000000000000000000..f2fa19779189fed09e9ad8214f26b43b9803feca
--- /dev/null
+++ b/pgsql/include/server/parser/scansup.h
@@ -0,0 +1,27 @@
+/*-------------------------------------------------------------------------
+ *
+ * scansup.h
+ * scanner support routines used by the core lexer
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/parser/scansup.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef SCANSUP_H
+#define SCANSUP_H
+
+extern char *downcase_truncate_identifier(const char *ident, int len,
+ bool warn);
+
+extern char *downcase_identifier(const char *ident, int len,
+ bool warn, bool truncate);
+
+extern void truncate_identifier(char *ident, int len, bool warn);
+
+extern bool scanner_isspace(char ch);
+
+#endif /* SCANSUP_H */
diff --git a/pgsql/include/server/partitioning/partbounds.h b/pgsql/include/server/partitioning/partbounds.h
new file mode 100644
index 0000000000000000000000000000000000000000..d2e01f92dfec117fcf1d598e0f3209e5f025e33d
--- /dev/null
+++ b/pgsql/include/server/partitioning/partbounds.h
@@ -0,0 +1,146 @@
+/*-------------------------------------------------------------------------
+ *
+ * partbounds.h
+ *
+ * Copyright (c) 2007-2023, PostgreSQL Global Development Group
+ *
+ * src/include/partitioning/partbounds.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARTBOUNDS_H
+#define PARTBOUNDS_H
+
+#include "fmgr.h"
+#include "parser/parse_node.h"
+#include "partitioning/partdefs.h"
+
+struct RelOptInfo; /* avoid including pathnodes.h here */
+
+
+/*
+ * PartitionBoundInfoData encapsulates a set of partition bounds. It is
+ * usually associated with partitioned tables as part of its partition
+ * descriptor, but may also be used to represent a virtual partitioned
+ * table such as a partitioned joinrel within the planner.
+ *
+ * A list partition datum that is known to be NULL is never put into the
+ * datums array. Instead, it is tracked using the null_index field.
+ *
+ * In the case of range partitioning, ndatums will typically be far less than
+ * 2 * nparts, because a partition's upper bound and the next partition's lower
+ * bound are the same in most common cases, and we only store one of them (the
+ * upper bound). In case of hash partitioning, ndatums will be the same as the
+ * number of partitions.
+ *
+ * For range and list partitioned tables, datums is an array of datum-tuples
+ * with key->partnatts datums each. For hash partitioned tables, it is an array
+ * of datum-tuples with 2 datums, modulus and remainder, corresponding to a
+ * given partition.
+ *
+ * The datums in datums array are arranged in increasing order as defined by
+ * functions qsort_partition_rbound_cmp(), qsort_partition_list_value_cmp() and
+ * qsort_partition_hbound_cmp() for range, list and hash partitioned tables
+ * respectively. For range and list partitions this simply means that the
+ * datums in the datums array are arranged in increasing order as defined by
+ * the partition key's operator classes and collations.
+ *
+ * In the case of list partitioning, the indexes array stores one entry for
+ * each datum-array entry, which is the index of the partition that accepts
+ * rows matching that datum. So nindexes == ndatums.
+ *
+ * In the case of range partitioning, the indexes array stores one entry per
+ * distinct range datum, which is the index of the partition for which that
+ * datum is an upper bound (or -1 for a "gap" that has no partition). It is
+ * convenient to have an extra -1 entry representing values above the last
+ * range datum, so nindexes == ndatums + 1.
+ *
+ * In the case of hash partitioning, the number of entries in the indexes
+ * array is the same as the greatest modulus amongst all partitions (which
+ * is a multiple of all partition moduli), so nindexes == greatest modulus.
+ * The indexes array is indexed according to the hash key's remainder modulo
+ * the greatest modulus, and it contains either the partition index accepting
+ * that remainder, or -1 if there is no partition for that remainder.
+ *
+ * For LIST partitioned tables, we track the partition indexes of partitions
+ * which are possibly "interleaved" partitions. A partition is considered
+ * interleaved if it allows multiple values and there exists at least one
+ * other partition which could contain a value that lies between those values.
+ * For example, if a partition exists FOR VALUES IN(3,5) and another partition
+ * exists FOR VALUES IN (4), then the IN(3,5) partition is an interleaved
+ * partition. The same is possible with DEFAULT partitions since they can
+ * contain any value that does not belong in another partition. This field
+ * only serves as proof that a particular partition is not interleaved, not
+ * proof that it is interleaved. When we're uncertain, we marked the
+ * partition as interleaved. The interleaved_parts field is only ever set for
+ * RELOPT_BASEREL and RELOPT_OTHER_MEMBER_REL, it is always left NULL for join
+ * relations.
+ */
+typedef struct PartitionBoundInfoData
+{
+ PartitionStrategy strategy; /* hash, list or range? */
+ int ndatums; /* Length of the datums[] array */
+ Datum **datums;
+ PartitionRangeDatumKind **kind; /* The kind of each range bound datum;
+ * NULL for hash and list partitioned
+ * tables */
+ Bitmapset *interleaved_parts; /* Partition indexes of partitions which
+ * may be interleaved. See above. This is
+ * only set for LIST partitioned tables */
+ int nindexes; /* Length of the indexes[] array */
+ int *indexes; /* Partition indexes */
+ int null_index; /* Index of the null-accepting partition; -1
+ * if there isn't one */
+ int default_index; /* Index of the default partition; -1 if there
+ * isn't one */
+} PartitionBoundInfoData;
+
+#define partition_bound_accepts_nulls(bi) ((bi)->null_index != -1)
+#define partition_bound_has_default(bi) ((bi)->default_index != -1)
+
+extern int get_hash_partition_greatest_modulus(PartitionBoundInfo bound);
+extern uint64 compute_partition_hash_value(int partnatts, FmgrInfo *partsupfunc,
+ Oid *partcollation,
+ Datum *values, bool *isnull);
+extern List *get_qual_from_partbound(Relation parent,
+ PartitionBoundSpec *spec);
+extern PartitionBoundInfo partition_bounds_create(PartitionBoundSpec **boundspecs,
+ int nparts, PartitionKey key, int **mapping);
+extern bool partition_bounds_equal(int partnatts, int16 *parttyplen,
+ bool *parttypbyval, PartitionBoundInfo b1,
+ PartitionBoundInfo b2);
+extern PartitionBoundInfo partition_bounds_copy(PartitionBoundInfo src,
+ PartitionKey key);
+extern PartitionBoundInfo partition_bounds_merge(int partnatts,
+ FmgrInfo *partsupfunc,
+ Oid *partcollation,
+ struct RelOptInfo *outer_rel,
+ struct RelOptInfo *inner_rel,
+ JoinType jointype,
+ List **outer_parts,
+ List **inner_parts);
+extern bool partitions_are_ordered(PartitionBoundInfo boundinfo,
+ Bitmapset *live_parts);
+extern void check_new_partition_bound(char *relname, Relation parent,
+ PartitionBoundSpec *spec,
+ ParseState *pstate);
+extern void check_default_partition_contents(Relation parent,
+ Relation default_rel,
+ PartitionBoundSpec *new_spec);
+
+extern int32 partition_rbound_datum_cmp(FmgrInfo *partsupfunc,
+ Oid *partcollation,
+ Datum *rb_datums, PartitionRangeDatumKind *rb_kind,
+ Datum *tuple_datums, int n_tuple_datums);
+extern int partition_list_bsearch(FmgrInfo *partsupfunc,
+ Oid *partcollation,
+ PartitionBoundInfo boundinfo,
+ Datum value, bool *is_equal);
+extern int partition_range_datum_bsearch(FmgrInfo *partsupfunc,
+ Oid *partcollation,
+ PartitionBoundInfo boundinfo,
+ int nvalues, Datum *values, bool *is_equal);
+extern int partition_hash_bsearch(PartitionBoundInfo boundinfo,
+ int modulus, int remainder);
+
+#endif /* PARTBOUNDS_H */
diff --git a/pgsql/include/server/partitioning/partdefs.h b/pgsql/include/server/partitioning/partdefs.h
new file mode 100644
index 0000000000000000000000000000000000000000..55bb49c816cc227ffddfc19f31bc0f6fd460a8ec
--- /dev/null
+++ b/pgsql/include/server/partitioning/partdefs.h
@@ -0,0 +1,26 @@
+/*-------------------------------------------------------------------------
+ *
+ * partdefs.h
+ * Base definitions for partitioned table handling
+ *
+ * Copyright (c) 2007-2023, PostgreSQL Global Development Group
+ *
+ * src/include/partitioning/partdefs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARTDEFS_H
+#define PARTDEFS_H
+
+
+typedef struct PartitionBoundInfoData *PartitionBoundInfo;
+
+typedef struct PartitionKeyData *PartitionKey;
+
+typedef struct PartitionBoundSpec PartitionBoundSpec;
+
+typedef struct PartitionDescData *PartitionDesc;
+
+typedef struct PartitionDirectoryData *PartitionDirectory;
+
+#endif /* PARTDEFS_H */
diff --git a/pgsql/include/server/partitioning/partdesc.h b/pgsql/include/server/partitioning/partdesc.h
new file mode 100644
index 0000000000000000000000000000000000000000..e157eae9c1ebf21a14fb9ae57debfa09046e79c3
--- /dev/null
+++ b/pgsql/include/server/partitioning/partdesc.h
@@ -0,0 +1,75 @@
+/*-------------------------------------------------------------------------
+ *
+ * partdesc.h
+ *
+ * Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/partitioning/partdesc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef PARTDESC_H
+#define PARTDESC_H
+
+#include "partitioning/partdefs.h"
+#include "utils/relcache.h"
+
+/*
+ * Information about partitions of a partitioned table.
+ *
+ * For partitioned tables where detached partitions exist, we only cache
+ * descriptors that include all partitions, including detached; when we're
+ * requested a descriptor without the detached partitions, we create one
+ * afresh each time. (The reason for this is that the set of detached
+ * partitions that are visible to each caller depends on the snapshot it has,
+ * so it's pretty much impossible to evict a descriptor from cache at the
+ * right time.)
+ */
+typedef struct PartitionDescData
+{
+ int nparts; /* Number of partitions */
+ bool detached_exist; /* Are there any detached partitions? */
+ Oid *oids; /* Array of 'nparts' elements containing
+ * partition OIDs in order of their bounds */
+ bool *is_leaf; /* Array of 'nparts' elements storing whether
+ * the corresponding 'oids' element belongs to
+ * a leaf partition or not */
+ PartitionBoundInfo boundinfo; /* collection of partition bounds */
+
+ /* Caching fields to cache lookups in get_partition_for_tuple() */
+
+ /*
+ * Index into the PartitionBoundInfo's datum array for the last found
+ * partition or -1 if none.
+ */
+ int last_found_datum_index;
+
+ /*
+ * Partition index of the last found partition or -1 if none has been
+ * found yet.
+ */
+ int last_found_part_index;
+
+ /*
+ * For LIST partitioning, this is the number of times in a row that the
+ * datum we're looking for a partition for matches the datum in the
+ * last_found_datum_index index of the boundinfo->datums array. For RANGE
+ * partitioning, this is the number of times in a row we've found that the
+ * datum we're looking for a partition for falls into the range of the
+ * partition corresponding to the last_found_datum_index index of the
+ * boundinfo->datums array.
+ */
+ int last_found_count;
+} PartitionDescData;
+
+
+extern PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached);
+
+extern PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool omit_detached);
+extern PartitionDesc PartitionDirectoryLookup(PartitionDirectory, Relation);
+extern void DestroyPartitionDirectory(PartitionDirectory pdir);
+
+extern Oid get_default_oid_from_partdesc(PartitionDesc partdesc);
+
+#endif /* PARTCACHE_H */
diff --git a/pgsql/include/server/partitioning/partprune.h b/pgsql/include/server/partitioning/partprune.h
new file mode 100644
index 0000000000000000000000000000000000000000..8636e04e374e0c3456e7ae7e38b6ba9ecdc8aca9
--- /dev/null
+++ b/pgsql/include/server/partitioning/partprune.h
@@ -0,0 +1,81 @@
+/*-------------------------------------------------------------------------
+ *
+ * partprune.h
+ * prototypes for partprune.c
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/partitioning/partprune.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARTPRUNE_H
+#define PARTPRUNE_H
+
+#include "nodes/execnodes.h"
+#include "partitioning/partdefs.h"
+
+struct PlannerInfo; /* avoid including pathnodes.h here */
+struct RelOptInfo;
+
+
+/*
+ * PartitionPruneContext
+ * Stores information needed at runtime for pruning computations
+ * related to a single partitioned table.
+ *
+ * strategy Partition strategy, e.g. LIST, RANGE, HASH.
+ * partnatts Number of columns in the partition key.
+ * nparts Number of partitions in this partitioned table.
+ * boundinfo Partition boundary info for the partitioned table.
+ * partcollation Array of partnatts elements, storing the collations of the
+ * partition key columns.
+ * partsupfunc Array of FmgrInfos for the comparison or hashing functions
+ * associated with the partition keys (partnatts elements).
+ * (This points into the partrel's partition key, typically.)
+ * stepcmpfuncs Array of FmgrInfos for the comparison or hashing function
+ * for each pruning step and partition key.
+ * ppccontext Memory context holding this PartitionPruneContext's
+ * subsidiary data, such as the FmgrInfos.
+ * planstate Points to the parent plan node's PlanState when called
+ * during execution; NULL when called from the planner.
+ * exprcontext ExprContext to use when evaluating pruning expressions
+ * exprstates Array of ExprStates, indexed as per PruneCxtStateIdx; one
+ * for each partition key in each pruning step. Allocated if
+ * planstate is non-NULL, otherwise NULL.
+ */
+typedef struct PartitionPruneContext
+{
+ char strategy;
+ int partnatts;
+ int nparts;
+ PartitionBoundInfo boundinfo;
+ Oid *partcollation;
+ FmgrInfo *partsupfunc;
+ FmgrInfo *stepcmpfuncs;
+ MemoryContext ppccontext;
+ PlanState *planstate;
+ ExprContext *exprcontext;
+ ExprState **exprstates;
+} PartitionPruneContext;
+
+/*
+ * PruneCxtStateIdx() computes the correct index into the stepcmpfuncs[]
+ * and exprstates[] arrays for step step_id and partition key column keyno.
+ * (Note: there is code that assumes the entries for a given step are
+ * sequential, so this is not chosen freely.)
+ */
+#define PruneCxtStateIdx(partnatts, step_id, keyno) \
+ ((partnatts) * (step_id) + (keyno))
+
+extern PartitionPruneInfo *make_partition_pruneinfo(struct PlannerInfo *root,
+ struct RelOptInfo *parentrel,
+ List *subpaths,
+ List *prunequal);
+extern Bitmapset *prune_append_rel_partitions(struct RelOptInfo *rel);
+extern Bitmapset *get_matching_partitions(PartitionPruneContext *context,
+ List *pruning_steps);
+
+#endif /* PARTPRUNE_H */
diff --git a/pgsql/include/server/pch/c_pch.h b/pgsql/include/server/pch/c_pch.h
new file mode 100644
index 0000000000000000000000000000000000000000..f40c757ca62ed360ac021640d19e6fdcd1f062f2
--- /dev/null
+++ b/pgsql/include/server/pch/c_pch.h
@@ -0,0 +1 @@
+#include "c.h"
diff --git a/pgsql/include/server/pch/postgres_fe_pch.h b/pgsql/include/server/pch/postgres_fe_pch.h
new file mode 100644
index 0000000000000000000000000000000000000000..f3ea20912d352df26a041aa2427164ba8e88b0b9
--- /dev/null
+++ b/pgsql/include/server/pch/postgres_fe_pch.h
@@ -0,0 +1 @@
+#include "postgres_fe.h"
diff --git a/pgsql/include/server/pch/postgres_pch.h b/pgsql/include/server/pch/postgres_pch.h
new file mode 100644
index 0000000000000000000000000000000000000000..71b2f35f76ba9d03da8a1adf878434015f399314
--- /dev/null
+++ b/pgsql/include/server/pch/postgres_pch.h
@@ -0,0 +1 @@
+#include "postgres.h"
diff --git a/pgsql/include/server/port/aix.h b/pgsql/include/server/port/aix.h
new file mode 100644
index 0000000000000000000000000000000000000000..5b1159c57857494e92f23a57168d76433531ca33
--- /dev/null
+++ b/pgsql/include/server/port/aix.h
@@ -0,0 +1,14 @@
+/*
+ * src/include/port/aix.h
+ */
+#define CLASS_CONFLICT
+#define DISABLE_XOPEN_NLS
+
+/*
+ * "IBM XL C/C++ for AIX, V12.1" miscompiles, for 32-bit, some inline
+ * expansions of ginCompareItemPointers() "long long" arithmetic. To take
+ * advantage of inlining, build a 64-bit PostgreSQL.
+ */
+#if defined(__ILP32__) && defined(__IBMC__)
+#define PG_FORCE_DISABLE_INLINE
+#endif
diff --git a/pgsql/include/server/port/atomics.h b/pgsql/include/server/port/atomics.h
new file mode 100644
index 0000000000000000000000000000000000000000..bbff945ebad0f62e02f0e098997f19e99f8226c8
--- /dev/null
+++ b/pgsql/include/server/port/atomics.h
@@ -0,0 +1,519 @@
+/*-------------------------------------------------------------------------
+ *
+ * atomics.h
+ * Atomic operations.
+ *
+ * Hardware and compiler dependent functions for manipulating memory
+ * atomically and dealing with cache coherency. Used to implement locking
+ * facilities and lockless algorithms/data structures.
+ *
+ * To bring up postgres on a platform/compiler at the very least
+ * implementations for the following operations should be provided:
+ * * pg_compiler_barrier(), pg_write_barrier(), pg_read_barrier()
+ * * pg_atomic_compare_exchange_u32(), pg_atomic_fetch_add_u32()
+ * * pg_atomic_test_set_flag(), pg_atomic_init_flag(), pg_atomic_clear_flag()
+ * * PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY should be defined if appropriate.
+ *
+ * There exist generic, hardware independent, implementations for several
+ * compilers which might be sufficient, although possibly not optimal, for a
+ * new platform. If no such generic implementation is available spinlocks (or
+ * even OS provided semaphores) will be used to implement the API.
+ *
+ * Implement _u64 atomics if and only if your platform can use them
+ * efficiently (and obviously correctly).
+ *
+ * Use higher level functionality (lwlocks, spinlocks, heavyweight locks)
+ * whenever possible. Writing correct code using these facilities is hard.
+ *
+ * For an introduction to using memory barriers within the PostgreSQL backend,
+ * see src/backend/storage/lmgr/README.barrier
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/atomics.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ATOMICS_H
+#define ATOMICS_H
+
+#ifdef FRONTEND
+#error "atomics.h may not be included from frontend code"
+#endif
+
+#define INSIDE_ATOMICS_H
+
+#include
+
+/*
+ * First a set of architecture specific files is included.
+ *
+ * These files can provide the full set of atomics or can do pretty much
+ * nothing if all the compilers commonly used on these platforms provide
+ * usable generics.
+ *
+ * Don't add an inline assembly of the actual atomic operations if all the
+ * common implementations of your platform provide intrinsics. Intrinsics are
+ * much easier to understand and potentially support more architectures.
+ *
+ * It will often make sense to define memory barrier semantics here, since
+ * e.g. generic compiler intrinsics for x86 memory barriers can't know that
+ * postgres doesn't need x86 read/write barriers do anything more than a
+ * compiler barrier.
+ *
+ */
+#if defined(__arm__) || defined(__arm) || defined(__aarch64__)
+#include "port/atomics/arch-arm.h"
+#elif defined(__i386__) || defined(__i386) || defined(__x86_64__)
+#include "port/atomics/arch-x86.h"
+#elif defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__) || defined(__powerpc64__)
+#include "port/atomics/arch-ppc.h"
+#elif defined(__hppa) || defined(__hppa__)
+#include "port/atomics/arch-hppa.h"
+#endif
+
+/*
+ * Compiler specific, but architecture independent implementations.
+ *
+ * Provide architecture independent implementations of the atomic
+ * facilities. At the very least compiler barriers should be provided, but a
+ * full implementation of
+ * * pg_compiler_barrier(), pg_write_barrier(), pg_read_barrier()
+ * * pg_atomic_compare_exchange_u32(), pg_atomic_fetch_add_u32()
+ * using compiler intrinsics are a good idea.
+ */
+/*
+ * gcc or compatible, including clang and icc. Exclude xlc. The ppc64le "IBM
+ * XL C/C++ for Linux, V13.1.2" emulates gcc, but __sync_lock_test_and_set()
+ * of one-byte types elicits SIGSEGV. That bug was gone by V13.1.5 (2016-12).
+ */
+#if (defined(__GNUC__) || defined(__INTEL_COMPILER)) && !(defined(__IBMC__) || defined(__IBMCPP__))
+#include "port/atomics/generic-gcc.h"
+#elif defined(_MSC_VER)
+#include "port/atomics/generic-msvc.h"
+#elif defined(__SUNPRO_C) && !defined(__GNUC__)
+#include "port/atomics/generic-sunpro.h"
+#else
+/*
+ * Unsupported compiler, we'll likely use slower fallbacks... At least
+ * compiler barriers should really be provided.
+ */
+#endif
+
+/*
+ * Provide a full fallback of the pg_*_barrier(), pg_atomic**_flag and
+ * pg_atomic_* APIs for platforms without sufficient spinlock and/or atomics
+ * support. In the case of spinlock backed atomics the emulation is expected
+ * to be efficient, although less so than native atomics support.
+ */
+#include "port/atomics/fallback.h"
+
+/*
+ * Provide additional operations using supported infrastructure. These are
+ * expected to be efficient if the underlying atomic operations are efficient.
+ */
+#include "port/atomics/generic.h"
+
+
+/*
+ * pg_compiler_barrier - prevent the compiler from moving code across
+ *
+ * A compiler barrier need not (and preferably should not) emit any actual
+ * machine code, but must act as an optimization fence: the compiler must not
+ * reorder loads or stores to main memory around the barrier. However, the
+ * CPU may still reorder loads or stores at runtime, if the architecture's
+ * memory model permits this.
+ */
+#define pg_compiler_barrier() pg_compiler_barrier_impl()
+
+/*
+ * pg_memory_barrier - prevent the CPU from reordering memory access
+ *
+ * A memory barrier must act as a compiler barrier, and in addition must
+ * guarantee that all loads and stores issued prior to the barrier are
+ * completed before any loads or stores issued after the barrier. Unless
+ * loads and stores are totally ordered (which is not the case on most
+ * architectures) this requires issuing some sort of memory fencing
+ * instruction.
+ */
+#define pg_memory_barrier() pg_memory_barrier_impl()
+
+/*
+ * pg_(read|write)_barrier - prevent the CPU from reordering memory access
+ *
+ * A read barrier must act as a compiler barrier, and in addition must
+ * guarantee that any loads issued prior to the barrier are completed before
+ * any loads issued after the barrier. Similarly, a write barrier acts
+ * as a compiler barrier, and also orders stores. Read and write barriers
+ * are thus weaker than a full memory barrier, but stronger than a compiler
+ * barrier. In practice, on machines with strong memory ordering, read and
+ * write barriers may require nothing more than a compiler barrier.
+ */
+#define pg_read_barrier() pg_read_barrier_impl()
+#define pg_write_barrier() pg_write_barrier_impl()
+
+/*
+ * Spinloop delay - Allow CPU to relax in busy loops
+ */
+#define pg_spin_delay() pg_spin_delay_impl()
+
+/*
+ * pg_atomic_init_flag - initialize atomic flag.
+ *
+ * No barrier semantics.
+ */
+static inline void
+pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
+{
+ pg_atomic_init_flag_impl(ptr);
+}
+
+/*
+ * pg_atomic_test_set_flag - TAS()
+ *
+ * Returns true if the flag has successfully been set, false otherwise.
+ *
+ * Acquire (including read barrier) semantics.
+ */
+static inline bool
+pg_atomic_test_set_flag(volatile pg_atomic_flag *ptr)
+{
+ return pg_atomic_test_set_flag_impl(ptr);
+}
+
+/*
+ * pg_atomic_unlocked_test_flag - Check if the lock is free
+ *
+ * Returns true if the flag currently is not set, false otherwise.
+ *
+ * No barrier semantics.
+ */
+static inline bool
+pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
+{
+ return pg_atomic_unlocked_test_flag_impl(ptr);
+}
+
+/*
+ * pg_atomic_clear_flag - release lock set by TAS()
+ *
+ * Release (including write barrier) semantics.
+ */
+static inline void
+pg_atomic_clear_flag(volatile pg_atomic_flag *ptr)
+{
+ pg_atomic_clear_flag_impl(ptr);
+}
+
+
+/*
+ * pg_atomic_init_u32 - initialize atomic variable
+ *
+ * Has to be done before any concurrent usage..
+ *
+ * No barrier semantics.
+ */
+static inline void
+pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
+{
+ AssertPointerAlignment(ptr, 4);
+
+ pg_atomic_init_u32_impl(ptr, val);
+}
+
+/*
+ * pg_atomic_read_u32 - unlocked read from atomic variable.
+ *
+ * The read is guaranteed to return a value as it has been written by this or
+ * another process at some point in the past. There's however no cache
+ * coherency interaction guaranteeing the value hasn't since been written to
+ * again.
+ *
+ * No barrier semantics.
+ */
+static inline uint32
+pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
+{
+ AssertPointerAlignment(ptr, 4);
+ return pg_atomic_read_u32_impl(ptr);
+}
+
+/*
+ * pg_atomic_write_u32 - write to atomic variable.
+ *
+ * The write is guaranteed to succeed as a whole, i.e. it's not possible to
+ * observe a partial write for any reader. Note that this correctly interacts
+ * with pg_atomic_compare_exchange_u32, in contrast to
+ * pg_atomic_unlocked_write_u32().
+ *
+ * No barrier semantics.
+ */
+static inline void
+pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
+{
+ AssertPointerAlignment(ptr, 4);
+
+ pg_atomic_write_u32_impl(ptr, val);
+}
+
+/*
+ * pg_atomic_unlocked_write_u32 - unlocked write to atomic variable.
+ *
+ * The write is guaranteed to succeed as a whole, i.e. it's not possible to
+ * observe a partial write for any reader. But note that writing this way is
+ * not guaranteed to correctly interact with read-modify-write operations like
+ * pg_atomic_compare_exchange_u32. This should only be used in cases where
+ * minor performance regressions due to atomics emulation are unacceptable.
+ *
+ * No barrier semantics.
+ */
+static inline void
+pg_atomic_unlocked_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
+{
+ AssertPointerAlignment(ptr, 4);
+
+ pg_atomic_unlocked_write_u32_impl(ptr, val);
+}
+
+/*
+ * pg_atomic_exchange_u32 - exchange newval with current value
+ *
+ * Returns the old value of 'ptr' before the swap.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 newval)
+{
+ AssertPointerAlignment(ptr, 4);
+
+ return pg_atomic_exchange_u32_impl(ptr, newval);
+}
+
+/*
+ * pg_atomic_compare_exchange_u32 - CAS operation
+ *
+ * Atomically compare the current value of ptr with *expected and store newval
+ * iff ptr and *expected have the same value. The current value of *ptr will
+ * always be stored in *expected.
+ *
+ * Return true if values have been exchanged, false otherwise.
+ *
+ * Full barrier semantics.
+ */
+static inline bool
+pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ AssertPointerAlignment(ptr, 4);
+ AssertPointerAlignment(expected, 4);
+
+ return pg_atomic_compare_exchange_u32_impl(ptr, expected, newval);
+}
+
+/*
+ * pg_atomic_fetch_add_u32 - atomically add to variable
+ *
+ * Returns the value of ptr before the arithmetic operation.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ AssertPointerAlignment(ptr, 4);
+ return pg_atomic_fetch_add_u32_impl(ptr, add_);
+}
+
+/*
+ * pg_atomic_fetch_sub_u32 - atomically subtract from variable
+ *
+ * Returns the value of ptr before the arithmetic operation. Note that sub_
+ * may not be INT_MIN due to platform limitations.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_fetch_sub_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
+{
+ AssertPointerAlignment(ptr, 4);
+ Assert(sub_ != INT_MIN);
+ return pg_atomic_fetch_sub_u32_impl(ptr, sub_);
+}
+
+/*
+ * pg_atomic_fetch_and_u32 - atomically bit-and and_ with variable
+ *
+ * Returns the value of ptr before the arithmetic operation.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_fetch_and_u32(volatile pg_atomic_uint32 *ptr, uint32 and_)
+{
+ AssertPointerAlignment(ptr, 4);
+ return pg_atomic_fetch_and_u32_impl(ptr, and_);
+}
+
+/*
+ * pg_atomic_fetch_or_u32 - atomically bit-or or_ with variable
+ *
+ * Returns the value of ptr before the arithmetic operation.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
+{
+ AssertPointerAlignment(ptr, 4);
+ return pg_atomic_fetch_or_u32_impl(ptr, or_);
+}
+
+/*
+ * pg_atomic_add_fetch_u32 - atomically add to variable
+ *
+ * Returns the value of ptr after the arithmetic operation.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_add_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ AssertPointerAlignment(ptr, 4);
+ return pg_atomic_add_fetch_u32_impl(ptr, add_);
+}
+
+/*
+ * pg_atomic_sub_fetch_u32 - atomically subtract from variable
+ *
+ * Returns the value of ptr after the arithmetic operation. Note that sub_ may
+ * not be INT_MIN due to platform limitations.
+ *
+ * Full barrier semantics.
+ */
+static inline uint32
+pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
+{
+ AssertPointerAlignment(ptr, 4);
+ Assert(sub_ != INT_MIN);
+ return pg_atomic_sub_fetch_u32_impl(ptr, sub_);
+}
+
+/* ----
+ * The 64 bit operations have the same semantics as their 32bit counterparts
+ * if they are available. Check the corresponding 32bit function for
+ * documentation.
+ * ----
+ */
+static inline void
+pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
+{
+ /*
+ * Can't necessarily enforce alignment - and don't need it - when using
+ * the spinlock based fallback implementation. Therefore only assert when
+ * not using it.
+ */
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ pg_atomic_init_u64_impl(ptr, val);
+}
+
+static inline uint64
+pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ return pg_atomic_read_u64_impl(ptr);
+}
+
+static inline void
+pg_atomic_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ pg_atomic_write_u64_impl(ptr, val);
+}
+
+static inline uint64
+pg_atomic_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 newval)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ return pg_atomic_exchange_u64_impl(ptr, newval);
+}
+
+static inline bool
+pg_atomic_compare_exchange_u64(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+ AssertPointerAlignment(expected, 8);
+#endif
+ return pg_atomic_compare_exchange_u64_impl(ptr, expected, newval);
+}
+
+static inline uint64
+pg_atomic_fetch_add_u64(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ return pg_atomic_fetch_add_u64_impl(ptr, add_);
+}
+
+static inline uint64
+pg_atomic_fetch_sub_u64(volatile pg_atomic_uint64 *ptr, int64 sub_)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ Assert(sub_ != PG_INT64_MIN);
+ return pg_atomic_fetch_sub_u64_impl(ptr, sub_);
+}
+
+static inline uint64
+pg_atomic_fetch_and_u64(volatile pg_atomic_uint64 *ptr, uint64 and_)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ return pg_atomic_fetch_and_u64_impl(ptr, and_);
+}
+
+static inline uint64
+pg_atomic_fetch_or_u64(volatile pg_atomic_uint64 *ptr, uint64 or_)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ return pg_atomic_fetch_or_u64_impl(ptr, or_);
+}
+
+static inline uint64
+pg_atomic_add_fetch_u64(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ return pg_atomic_add_fetch_u64_impl(ptr, add_);
+}
+
+static inline uint64
+pg_atomic_sub_fetch_u64(volatile pg_atomic_uint64 *ptr, int64 sub_)
+{
+#ifndef PG_HAVE_ATOMIC_U64_SIMULATION
+ AssertPointerAlignment(ptr, 8);
+#endif
+ Assert(sub_ != PG_INT64_MIN);
+ return pg_atomic_sub_fetch_u64_impl(ptr, sub_);
+}
+
+#undef INSIDE_ATOMICS_H
+
+#endif /* ATOMICS_H */
diff --git a/pgsql/include/server/port/atomics/arch-arm.h b/pgsql/include/server/port/atomics/arch-arm.h
new file mode 100644
index 0000000000000000000000000000000000000000..c90bf58029cbe0b0ef6b6a9fae13e5c48162f5ad
--- /dev/null
+++ b/pgsql/include/server/port/atomics/arch-arm.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * arch-arm.h
+ * Atomic operations considerations specific to ARM
+ *
+ * Portions Copyright (c) 2013-2023, PostgreSQL Global Development Group
+ *
+ * NOTES:
+ *
+ * src/include/port/atomics/arch-arm.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* intentionally no include guards, should only be included by atomics.h */
+#ifndef INSIDE_ATOMICS_H
+#error "should be included via atomics.h"
+#endif
+
+/*
+ * 64 bit atomics on ARM32 are implemented using kernel fallbacks and thus
+ * might be slow, so disable entirely. On ARM64 that problem doesn't exist.
+ */
+#if !defined(__aarch64__)
+#define PG_DISABLE_64_BIT_ATOMICS
+#else
+/*
+ * Architecture Reference Manual for ARMv8 states aligned read/write to/from
+ * general purpose register is atomic.
+ */
+#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY
+#endif /* __aarch64__ */
diff --git a/pgsql/include/server/port/atomics/arch-hppa.h b/pgsql/include/server/port/atomics/arch-hppa.h
new file mode 100644
index 0000000000000000000000000000000000000000..4c89fbff71992a0dc1ecbb3d8ca086338b216a89
--- /dev/null
+++ b/pgsql/include/server/port/atomics/arch-hppa.h
@@ -0,0 +1,17 @@
+/*-------------------------------------------------------------------------
+ *
+ * arch-hppa.h
+ * Atomic operations considerations specific to HPPA
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES:
+ *
+ * src/include/port/atomics/arch-hppa.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* HPPA doesn't do either read or write reordering */
+#define pg_memory_barrier_impl() pg_compiler_barrier_impl()
diff --git a/pgsql/include/server/port/atomics/arch-ppc.h b/pgsql/include/server/port/atomics/arch-ppc.h
new file mode 100644
index 0000000000000000000000000000000000000000..d992d4c8a265b7e76d57fc7c64a295df96251a78
--- /dev/null
+++ b/pgsql/include/server/port/atomics/arch-ppc.h
@@ -0,0 +1,254 @@
+/*-------------------------------------------------------------------------
+ *
+ * arch-ppc.h
+ * Atomic operations considerations specific to PowerPC
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES:
+ *
+ * src/include/port/atomics/arch-ppc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#if defined(__GNUC__)
+
+/*
+ * lwsync orders loads with respect to each other, and similarly with stores.
+ * But a load can be performed before a subsequent store, so sync must be used
+ * for a full memory barrier.
+ */
+#define pg_memory_barrier_impl() __asm__ __volatile__ ("sync" : : : "memory")
+#define pg_read_barrier_impl() __asm__ __volatile__ ("lwsync" : : : "memory")
+#define pg_write_barrier_impl() __asm__ __volatile__ ("lwsync" : : : "memory")
+#endif
+
+#define PG_HAVE_ATOMIC_U32_SUPPORT
+typedef struct pg_atomic_uint32
+{
+ volatile uint32 value;
+} pg_atomic_uint32;
+
+/* 64bit atomics are only supported in 64bit mode */
+#if SIZEOF_VOID_P >= 8
+#define PG_HAVE_ATOMIC_U64_SUPPORT
+typedef struct pg_atomic_uint64
+{
+ volatile uint64 value pg_attribute_aligned(8);
+} pg_atomic_uint64;
+
+#endif
+
+/*
+ * This mimics gcc __atomic_compare_exchange_n(..., __ATOMIC_SEQ_CST), but
+ * code generation differs at the end. __atomic_compare_exchange_n():
+ * 100: isync
+ * 104: mfcr r3
+ * 108: rlwinm r3,r3,3,31,31
+ * 10c: bne 120 <.eb+0x10>
+ * 110: clrldi r3,r3,63
+ * 114: addi r1,r1,112
+ * 118: blr
+ * 11c: nop
+ * 120: clrldi r3,r3,63
+ * 124: stw r9,0(r4)
+ * 128: addi r1,r1,112
+ * 12c: blr
+ *
+ * This:
+ * f0: isync
+ * f4: mfcr r9
+ * f8: rldicl. r3,r9,35,63
+ * fc: bne 104 <.eb>
+ * 100: stw r10,0(r4)
+ * 104: addi r1,r1,112
+ * 108: blr
+ *
+ * This implementation may or may not have materially different performance.
+ * It's not exploiting the fact that cr0 still holds the relevant comparison
+ * bits, set during the __asm__. One could fix that by moving more code into
+ * the __asm__. (That would remove the freedom to eliminate dead stores when
+ * the caller ignores "expected", but few callers do.)
+ *
+ * Recognizing constant "newval" would be superfluous, because there's no
+ * immediate-operand version of stwcx.
+ */
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+static inline bool
+pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ uint32 found;
+ uint32 condition_register;
+ bool ret;
+
+#ifdef HAVE_I_CONSTRAINT__BUILTIN_CONSTANT_P
+ if (__builtin_constant_p(*expected) &&
+ (int32) *expected <= PG_INT16_MAX &&
+ (int32) *expected >= PG_INT16_MIN)
+ __asm__ __volatile__(
+ " sync \n"
+ " lwarx %0,0,%5,1 \n"
+ " cmpwi %0,%3 \n"
+ " bne $+12 \n" /* branch to lwsync */
+ " stwcx. %4,0,%5 \n"
+ " bne $-16 \n" /* branch to lwarx */
+ " lwsync \n"
+ " mfcr %1 \n"
+: "=&r"(found), "=r"(condition_register), "+m"(ptr->value)
+: "i"(*expected), "r"(newval), "r"(&ptr->value)
+: "memory", "cc");
+ else
+#endif
+ __asm__ __volatile__(
+ " sync \n"
+ " lwarx %0,0,%5,1 \n"
+ " cmpw %0,%3 \n"
+ " bne $+12 \n" /* branch to lwsync */
+ " stwcx. %4,0,%5 \n"
+ " bne $-16 \n" /* branch to lwarx */
+ " lwsync \n"
+ " mfcr %1 \n"
+: "=&r"(found), "=r"(condition_register), "+m"(ptr->value)
+: "r"(*expected), "r"(newval), "r"(&ptr->value)
+: "memory", "cc");
+
+ ret = (condition_register >> 29) & 1; /* test eq bit of cr0 */
+ if (!ret)
+ *expected = found;
+ return ret;
+}
+
+/*
+ * This mirrors gcc __sync_fetch_and_add().
+ *
+ * Like tas(), use constraint "=&b" to avoid allocating r0.
+ */
+#define PG_HAVE_ATOMIC_FETCH_ADD_U32
+static inline uint32
+pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ uint32 _t;
+ uint32 res;
+
+#ifdef HAVE_I_CONSTRAINT__BUILTIN_CONSTANT_P
+ if (__builtin_constant_p(add_) &&
+ add_ <= PG_INT16_MAX && add_ >= PG_INT16_MIN)
+ __asm__ __volatile__(
+ " sync \n"
+ " lwarx %1,0,%4,1 \n"
+ " addi %0,%1,%3 \n"
+ " stwcx. %0,0,%4 \n"
+ " bne $-12 \n" /* branch to lwarx */
+ " lwsync \n"
+: "=&r"(_t), "=&b"(res), "+m"(ptr->value)
+: "i"(add_), "r"(&ptr->value)
+: "memory", "cc");
+ else
+#endif
+ __asm__ __volatile__(
+ " sync \n"
+ " lwarx %1,0,%4,1 \n"
+ " add %0,%1,%3 \n"
+ " stwcx. %0,0,%4 \n"
+ " bne $-12 \n" /* branch to lwarx */
+ " lwsync \n"
+: "=&r"(_t), "=&r"(res), "+m"(ptr->value)
+: "r"(add_), "r"(&ptr->value)
+: "memory", "cc");
+
+ return res;
+}
+
+#ifdef PG_HAVE_ATOMIC_U64_SUPPORT
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+static inline bool
+pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+ uint64 found;
+ uint32 condition_register;
+ bool ret;
+
+ /* Like u32, but s/lwarx/ldarx/; s/stwcx/stdcx/; s/cmpw/cmpd/ */
+#ifdef HAVE_I_CONSTRAINT__BUILTIN_CONSTANT_P
+ if (__builtin_constant_p(*expected) &&
+ (int64) *expected <= PG_INT16_MAX &&
+ (int64) *expected >= PG_INT16_MIN)
+ __asm__ __volatile__(
+ " sync \n"
+ " ldarx %0,0,%5,1 \n"
+ " cmpdi %0,%3 \n"
+ " bne $+12 \n" /* branch to lwsync */
+ " stdcx. %4,0,%5 \n"
+ " bne $-16 \n" /* branch to ldarx */
+ " lwsync \n"
+ " mfcr %1 \n"
+: "=&r"(found), "=r"(condition_register), "+m"(ptr->value)
+: "i"(*expected), "r"(newval), "r"(&ptr->value)
+: "memory", "cc");
+ else
+#endif
+ __asm__ __volatile__(
+ " sync \n"
+ " ldarx %0,0,%5,1 \n"
+ " cmpd %0,%3 \n"
+ " bne $+12 \n" /* branch to lwsync */
+ " stdcx. %4,0,%5 \n"
+ " bne $-16 \n" /* branch to ldarx */
+ " lwsync \n"
+ " mfcr %1 \n"
+: "=&r"(found), "=r"(condition_register), "+m"(ptr->value)
+: "r"(*expected), "r"(newval), "r"(&ptr->value)
+: "memory", "cc");
+
+ ret = (condition_register >> 29) & 1; /* test eq bit of cr0 */
+ if (!ret)
+ *expected = found;
+ return ret;
+}
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U64
+static inline uint64
+pg_atomic_fetch_add_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+ uint64 _t;
+ uint64 res;
+
+ /* Like u32, but s/lwarx/ldarx/; s/stwcx/stdcx/ */
+#ifdef HAVE_I_CONSTRAINT__BUILTIN_CONSTANT_P
+ if (__builtin_constant_p(add_) &&
+ add_ <= PG_INT16_MAX && add_ >= PG_INT16_MIN)
+ __asm__ __volatile__(
+ " sync \n"
+ " ldarx %1,0,%4,1 \n"
+ " addi %0,%1,%3 \n"
+ " stdcx. %0,0,%4 \n"
+ " bne $-12 \n" /* branch to ldarx */
+ " lwsync \n"
+: "=&r"(_t), "=&b"(res), "+m"(ptr->value)
+: "i"(add_), "r"(&ptr->value)
+: "memory", "cc");
+ else
+#endif
+ __asm__ __volatile__(
+ " sync \n"
+ " ldarx %1,0,%4,1 \n"
+ " add %0,%1,%3 \n"
+ " stdcx. %0,0,%4 \n"
+ " bne $-12 \n" /* branch to ldarx */
+ " lwsync \n"
+: "=&r"(_t), "=&r"(res), "+m"(ptr->value)
+: "r"(add_), "r"(&ptr->value)
+: "memory", "cc");
+
+ return res;
+}
+
+#endif /* PG_HAVE_ATOMIC_U64_SUPPORT */
+
+/* per architecture manual doubleword accesses have single copy atomicity */
+#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY
diff --git a/pgsql/include/server/port/atomics/arch-x86.h b/pgsql/include/server/port/atomics/arch-x86.h
new file mode 100644
index 0000000000000000000000000000000000000000..bb84b9bad83869cf4620f288014798e940025c20
--- /dev/null
+++ b/pgsql/include/server/port/atomics/arch-x86.h
@@ -0,0 +1,252 @@
+/*-------------------------------------------------------------------------
+ *
+ * arch-x86.h
+ * Atomic operations considerations specific to intel x86
+ *
+ * Note that we actually require a 486 upwards because the 386 doesn't have
+ * support for xadd and cmpxchg. Given that the 386 isn't supported anywhere
+ * anymore that's not much of a restriction luckily.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES:
+ *
+ * src/include/port/atomics/arch-x86.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/*
+ * Both 32 and 64 bit x86 do not allow loads to be reordered with other loads,
+ * or stores to be reordered with other stores, but a load can be performed
+ * before a subsequent store.
+ *
+ * Technically, some x86-ish chips support uncached memory access and/or
+ * special instructions that are weakly ordered. In those cases we'd need
+ * the read and write barriers to be lfence and sfence. But since we don't
+ * do those things, a compiler barrier should be enough.
+ *
+ * "lock; addl" has worked for longer than "mfence". It's also rumored to be
+ * faster in many scenarios.
+ */
+
+#if defined(__GNUC__) || defined(__INTEL_COMPILER)
+#if defined(__i386__) || defined(__i386)
+#define pg_memory_barrier_impl() \
+ __asm__ __volatile__ ("lock; addl $0,0(%%esp)" : : : "memory", "cc")
+#elif defined(__x86_64__)
+#define pg_memory_barrier_impl() \
+ __asm__ __volatile__ ("lock; addl $0,0(%%rsp)" : : : "memory", "cc")
+#endif
+#endif /* defined(__GNUC__) || defined(__INTEL_COMPILER) */
+
+#define pg_read_barrier_impl() pg_compiler_barrier_impl()
+#define pg_write_barrier_impl() pg_compiler_barrier_impl()
+
+/*
+ * Provide implementation for atomics using inline assembly on x86 gcc. It's
+ * nice to support older gcc's and the compare/exchange implementation here is
+ * actually more efficient than the * __sync variant.
+ */
+#if defined(HAVE_ATOMICS)
+
+#if defined(__GNUC__) || defined(__INTEL_COMPILER)
+
+#define PG_HAVE_ATOMIC_FLAG_SUPPORT
+typedef struct pg_atomic_flag
+{
+ volatile char value;
+} pg_atomic_flag;
+
+#define PG_HAVE_ATOMIC_U32_SUPPORT
+typedef struct pg_atomic_uint32
+{
+ volatile uint32 value;
+} pg_atomic_uint32;
+
+/*
+ * It's too complicated to write inline asm for 64bit types on 32bit and the
+ * 486 can't do it anyway.
+ */
+#ifdef __x86_64__
+#define PG_HAVE_ATOMIC_U64_SUPPORT
+typedef struct pg_atomic_uint64
+{
+ /* alignment guaranteed due to being on a 64bit platform */
+ volatile uint64 value;
+} pg_atomic_uint64;
+#endif /* __x86_64__ */
+
+#endif /* defined(__GNUC__) || defined(__INTEL_COMPILER) */
+
+#endif /* defined(HAVE_ATOMICS) */
+
+#if !defined(PG_HAVE_SPIN_DELAY)
+/*
+ * This sequence is equivalent to the PAUSE instruction ("rep" is
+ * ignored by old IA32 processors if the following instruction is
+ * not a string operation); the IA-32 Architecture Software
+ * Developer's Manual, Vol. 3, Section 7.7.2 describes why using
+ * PAUSE in the inner loop of a spin lock is necessary for good
+ * performance:
+ *
+ * The PAUSE instruction improves the performance of IA-32
+ * processors supporting Hyper-Threading Technology when
+ * executing spin-wait loops and other routines where one
+ * thread is accessing a shared lock or semaphore in a tight
+ * polling loop. When executing a spin-wait loop, the
+ * processor can suffer a severe performance penalty when
+ * exiting the loop because it detects a possible memory order
+ * violation and flushes the core processor's pipeline. The
+ * PAUSE instruction provides a hint to the processor that the
+ * code sequence is a spin-wait loop. The processor uses this
+ * hint to avoid the memory order violation and prevent the
+ * pipeline flush. In addition, the PAUSE instruction
+ * de-pipelines the spin-wait loop to prevent it from
+ * consuming execution resources excessively.
+ */
+#if defined(__GNUC__) || defined(__INTEL_COMPILER)
+#define PG_HAVE_SPIN_DELAY
+static __inline__ void
+pg_spin_delay_impl(void)
+{
+ __asm__ __volatile__(" rep; nop \n");
+}
+#elif defined(_MSC_VER) && defined(__x86_64__)
+#define PG_HAVE_SPIN_DELAY
+static __forceinline void
+pg_spin_delay_impl(void)
+{
+ _mm_pause();
+}
+#elif defined(_MSC_VER)
+#define PG_HAVE_SPIN_DELAY
+static __forceinline void
+pg_spin_delay_impl(void)
+{
+ /* See comment for gcc code. Same code, MASM syntax */
+ __asm rep nop;
+}
+#endif
+#endif /* !defined(PG_HAVE_SPIN_DELAY) */
+
+
+#if defined(HAVE_ATOMICS)
+
+#if defined(__GNUC__) || defined(__INTEL_COMPILER)
+
+#define PG_HAVE_ATOMIC_TEST_SET_FLAG
+static inline bool
+pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ char _res = 1;
+
+ __asm__ __volatile__(
+ " lock \n"
+ " xchgb %0,%1 \n"
+: "+q"(_res), "+m"(ptr->value)
+:
+: "memory");
+ return _res == 0;
+}
+
+#define PG_HAVE_ATOMIC_CLEAR_FLAG
+static inline void
+pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ /*
+ * On a TSO architecture like x86 it's sufficient to use a compiler
+ * barrier to achieve release semantics.
+ */
+ __asm__ __volatile__("" ::: "memory");
+ ptr->value = 0;
+}
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+static inline bool
+pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ char ret;
+
+ /*
+ * Perform cmpxchg and use the zero flag which it implicitly sets when
+ * equal to measure the success.
+ */
+ __asm__ __volatile__(
+ " lock \n"
+ " cmpxchgl %4,%5 \n"
+ " setz %2 \n"
+: "=a" (*expected), "=m"(ptr->value), "=q" (ret)
+: "a" (*expected), "r" (newval), "m"(ptr->value)
+: "memory", "cc");
+ return (bool) ret;
+}
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U32
+static inline uint32
+pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ uint32 res;
+ __asm__ __volatile__(
+ " lock \n"
+ " xaddl %0,%1 \n"
+: "=q"(res), "=m"(ptr->value)
+: "0" (add_), "m"(ptr->value)
+: "memory", "cc");
+ return res;
+}
+
+#ifdef __x86_64__
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+static inline bool
+pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+ char ret;
+
+ /*
+ * Perform cmpxchg and use the zero flag which it implicitly sets when
+ * equal to measure the success.
+ */
+ __asm__ __volatile__(
+ " lock \n"
+ " cmpxchgq %4,%5 \n"
+ " setz %2 \n"
+: "=a" (*expected), "=m"(ptr->value), "=q" (ret)
+: "a" (*expected), "r" (newval), "m"(ptr->value)
+: "memory", "cc");
+ return (bool) ret;
+}
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U64
+static inline uint64
+pg_atomic_fetch_add_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+ uint64 res;
+ __asm__ __volatile__(
+ " lock \n"
+ " xaddq %0,%1 \n"
+: "=q"(res), "=m"(ptr->value)
+: "0" (add_), "m"(ptr->value)
+: "memory", "cc");
+ return res;
+}
+
+#endif /* __x86_64__ */
+
+#endif /* defined(__GNUC__) || defined(__INTEL_COMPILER) */
+
+/*
+ * 8 byte reads / writes have single-copy atomicity on 32 bit x86 platforms
+ * since at least the 586. As well as on all x86-64 cpus.
+ */
+#if defined(__i568__) || defined(__i668__) || /* gcc i586+ */ \
+ (defined(_M_IX86) && _M_IX86 >= 500) || /* msvc i586+ */ \
+ defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) /* gcc, sunpro, msvc */
+#define PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY
+#endif /* 8 byte single-copy atomicity */
+
+#endif /* HAVE_ATOMICS */
diff --git a/pgsql/include/server/port/atomics/fallback.h b/pgsql/include/server/port/atomics/fallback.h
new file mode 100644
index 0000000000000000000000000000000000000000..a9e8e77c036ce169e60a9320ab3406f5d8ae71f9
--- /dev/null
+++ b/pgsql/include/server/port/atomics/fallback.h
@@ -0,0 +1,170 @@
+/*-------------------------------------------------------------------------
+ *
+ * fallback.h
+ * Fallback for platforms without spinlock and/or atomics support. Slower
+ * than native atomics support, but not unusably slow.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/atomics/fallback.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* intentionally no include guards, should only be included by atomics.h */
+#ifndef INSIDE_ATOMICS_H
+# error "should be included via atomics.h"
+#endif
+
+#ifndef pg_memory_barrier_impl
+/*
+ * If we have no memory barrier implementation for this architecture, we
+ * fall back to acquiring and releasing a spinlock. This might, in turn,
+ * fall back to the semaphore-based spinlock implementation, which will be
+ * amazingly slow.
+ *
+ * It's not self-evident that every possible legal implementation of a
+ * spinlock acquire-and-release would be equivalent to a full memory barrier.
+ * For example, I'm not sure that Itanium's acq and rel add up to a full
+ * fence. But all of our actual implementations seem OK in this regard.
+ */
+#define PG_HAVE_MEMORY_BARRIER_EMULATION
+
+extern void pg_spinlock_barrier(void);
+#define pg_memory_barrier_impl pg_spinlock_barrier
+#endif
+
+#ifndef pg_compiler_barrier_impl
+/*
+ * If the compiler/arch combination does not provide compiler barriers,
+ * provide a fallback. The fallback simply consists of a function call into
+ * an externally defined function. That should guarantee compiler barrier
+ * semantics except for compilers that do inter translation unit/global
+ * optimization - those better provide an actual compiler barrier.
+ *
+ * A native compiler barrier for sure is a lot faster than this...
+ */
+#define PG_HAVE_COMPILER_BARRIER_EMULATION
+extern void pg_extern_compiler_barrier(void);
+#define pg_compiler_barrier_impl pg_extern_compiler_barrier
+#endif
+
+
+/*
+ * If we have atomics implementation for this platform, fall back to providing
+ * the atomics API using a spinlock to protect the internal state. Possibly
+ * the spinlock implementation uses semaphores internally...
+ *
+ * We have to be a bit careful here, as it's not guaranteed that atomic
+ * variables are mapped to the same address in every process (e.g. dynamic
+ * shared memory segments). We can't just hash the address and use that to map
+ * to a spinlock. Instead assign a spinlock on initialization of the atomic
+ * variable.
+ */
+#if !defined(PG_HAVE_ATOMIC_FLAG_SUPPORT) && !defined(PG_HAVE_ATOMIC_U32_SUPPORT)
+
+#define PG_HAVE_ATOMIC_FLAG_SIMULATION
+#define PG_HAVE_ATOMIC_FLAG_SUPPORT
+
+typedef struct pg_atomic_flag
+{
+ /*
+ * To avoid circular includes we can't use s_lock as a type here. Instead
+ * just reserve enough space for all spinlock types. Some platforms would
+ * be content with just one byte instead of 4, but that's not too much
+ * waste.
+ */
+#if defined(__hppa) || defined(__hppa__) /* HP PA-RISC, GCC and HP compilers */
+ int sema[4];
+#else
+ int sema;
+#endif
+ volatile bool value;
+} pg_atomic_flag;
+
+#endif /* PG_HAVE_ATOMIC_FLAG_SUPPORT */
+
+#if !defined(PG_HAVE_ATOMIC_U32_SUPPORT)
+
+#define PG_HAVE_ATOMIC_U32_SIMULATION
+
+#define PG_HAVE_ATOMIC_U32_SUPPORT
+typedef struct pg_atomic_uint32
+{
+ /* Check pg_atomic_flag's definition above for an explanation */
+#if defined(__hppa) || defined(__hppa__) /* HP PA-RISC */
+ int sema[4];
+#else
+ int sema;
+#endif
+ volatile uint32 value;
+} pg_atomic_uint32;
+
+#endif /* PG_HAVE_ATOMIC_U32_SUPPORT */
+
+#if !defined(PG_HAVE_ATOMIC_U64_SUPPORT)
+
+#define PG_HAVE_ATOMIC_U64_SIMULATION
+
+#define PG_HAVE_ATOMIC_U64_SUPPORT
+typedef struct pg_atomic_uint64
+{
+ /* Check pg_atomic_flag's definition above for an explanation */
+#if defined(__hppa) || defined(__hppa__) /* HP PA-RISC */
+ int sema[4];
+#else
+ int sema;
+#endif
+ volatile uint64 value;
+} pg_atomic_uint64;
+
+#endif /* PG_HAVE_ATOMIC_U64_SUPPORT */
+
+#ifdef PG_HAVE_ATOMIC_FLAG_SIMULATION
+
+#define PG_HAVE_ATOMIC_INIT_FLAG
+extern void pg_atomic_init_flag_impl(volatile pg_atomic_flag *ptr);
+
+#define PG_HAVE_ATOMIC_TEST_SET_FLAG
+extern bool pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr);
+
+#define PG_HAVE_ATOMIC_CLEAR_FLAG
+extern void pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr);
+
+#define PG_HAVE_ATOMIC_UNLOCKED_TEST_FLAG
+extern bool pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr);
+
+#endif /* PG_HAVE_ATOMIC_FLAG_SIMULATION */
+
+#ifdef PG_HAVE_ATOMIC_U32_SIMULATION
+
+#define PG_HAVE_ATOMIC_INIT_U32
+extern void pg_atomic_init_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 val_);
+
+#define PG_HAVE_ATOMIC_WRITE_U32
+extern void pg_atomic_write_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 val);
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+extern bool pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval);
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U32
+extern uint32 pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_);
+
+#endif /* PG_HAVE_ATOMIC_U32_SIMULATION */
+
+
+#ifdef PG_HAVE_ATOMIC_U64_SIMULATION
+
+#define PG_HAVE_ATOMIC_INIT_U64
+extern void pg_atomic_init_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 val_);
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+extern bool pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval);
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U64
+extern uint64 pg_atomic_fetch_add_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_);
+
+#endif /* PG_HAVE_ATOMIC_U64_SIMULATION */
diff --git a/pgsql/include/server/port/atomics/generic-gcc.h b/pgsql/include/server/port/atomics/generic-gcc.h
new file mode 100644
index 0000000000000000000000000000000000000000..da04e9f0dc3a6d3ba9b855e3d72879f05324a106
--- /dev/null
+++ b/pgsql/include/server/port/atomics/generic-gcc.h
@@ -0,0 +1,286 @@
+/*-------------------------------------------------------------------------
+ *
+ * generic-gcc.h
+ * Atomic operations, implemented using gcc (or compatible) intrinsics.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES:
+ *
+ * Documentation:
+ * * Legacy __sync Built-in Functions for Atomic Memory Access
+ * https://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/_005f_005fsync-Builtins.html
+ * * Built-in functions for memory model aware atomic operations
+ * https://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/_005f_005fatomic-Builtins.html
+ *
+ * src/include/port/atomics/generic-gcc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* intentionally no include guards, should only be included by atomics.h */
+#ifndef INSIDE_ATOMICS_H
+#error "should be included via atomics.h"
+#endif
+
+/*
+ * An empty asm block should be a sufficient compiler barrier.
+ */
+#define pg_compiler_barrier_impl() __asm__ __volatile__("" ::: "memory")
+
+/*
+ * If we're on GCC 4.1.0 or higher, we should be able to get a memory barrier
+ * out of this compiler built-in. But we prefer to rely on platform specific
+ * definitions where possible, and use this only as a fallback.
+ */
+#if !defined(pg_memory_barrier_impl)
+# if defined(HAVE_GCC__ATOMIC_INT32_CAS)
+# define pg_memory_barrier_impl() __atomic_thread_fence(__ATOMIC_SEQ_CST)
+# elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))
+# define pg_memory_barrier_impl() __sync_synchronize()
+# endif
+#endif /* !defined(pg_memory_barrier_impl) */
+
+#if !defined(pg_read_barrier_impl) && defined(HAVE_GCC__ATOMIC_INT32_CAS)
+/* acquire semantics include read barrier semantics */
+# define pg_read_barrier_impl() __atomic_thread_fence(__ATOMIC_ACQUIRE)
+#endif
+
+#if !defined(pg_write_barrier_impl) && defined(HAVE_GCC__ATOMIC_INT32_CAS)
+/* release semantics include write barrier semantics */
+# define pg_write_barrier_impl() __atomic_thread_fence(__ATOMIC_RELEASE)
+#endif
+
+
+#ifdef HAVE_ATOMICS
+
+/* generic gcc based atomic flag implementation */
+#if !defined(PG_HAVE_ATOMIC_FLAG_SUPPORT) \
+ && (defined(HAVE_GCC__SYNC_INT32_TAS) || defined(HAVE_GCC__SYNC_CHAR_TAS))
+
+#define PG_HAVE_ATOMIC_FLAG_SUPPORT
+typedef struct pg_atomic_flag
+{
+ /*
+ * If we have a choice, use int-width TAS, because that is more efficient
+ * and/or more reliably implemented on most non-Intel platforms. (Note
+ * that this code isn't used on x86[_64]; see arch-x86.h for that.)
+ */
+#ifdef HAVE_GCC__SYNC_INT32_TAS
+ volatile int value;
+#else
+ volatile char value;
+#endif
+} pg_atomic_flag;
+
+#endif /* !ATOMIC_FLAG_SUPPORT && SYNC_INT32_TAS */
+
+/* generic gcc based atomic uint32 implementation */
+#if !defined(PG_HAVE_ATOMIC_U32_SUPPORT) \
+ && (defined(HAVE_GCC__ATOMIC_INT32_CAS) || defined(HAVE_GCC__SYNC_INT32_CAS))
+
+#define PG_HAVE_ATOMIC_U32_SUPPORT
+typedef struct pg_atomic_uint32
+{
+ volatile uint32 value;
+} pg_atomic_uint32;
+
+#endif /* defined(HAVE_GCC__ATOMIC_INT32_CAS) || defined(HAVE_GCC__SYNC_INT32_CAS) */
+
+/* generic gcc based atomic uint64 implementation */
+#if !defined(PG_HAVE_ATOMIC_U64_SUPPORT) \
+ && !defined(PG_DISABLE_64_BIT_ATOMICS) \
+ && (defined(HAVE_GCC__ATOMIC_INT64_CAS) || defined(HAVE_GCC__SYNC_INT64_CAS))
+
+#define PG_HAVE_ATOMIC_U64_SUPPORT
+
+typedef struct pg_atomic_uint64
+{
+ volatile uint64 value pg_attribute_aligned(8);
+} pg_atomic_uint64;
+
+#endif /* defined(HAVE_GCC__ATOMIC_INT64_CAS) || defined(HAVE_GCC__SYNC_INT64_CAS) */
+
+#ifdef PG_HAVE_ATOMIC_FLAG_SUPPORT
+
+#if defined(HAVE_GCC__SYNC_CHAR_TAS) || defined(HAVE_GCC__SYNC_INT32_TAS)
+
+#ifndef PG_HAVE_ATOMIC_TEST_SET_FLAG
+#define PG_HAVE_ATOMIC_TEST_SET_FLAG
+static inline bool
+pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ /* NB: only an acquire barrier, not a full one */
+ /* some platform only support a 1 here */
+ return __sync_lock_test_and_set(&ptr->value, 1) == 0;
+}
+#endif
+
+#endif /* defined(HAVE_GCC__SYNC_*_TAS) */
+
+#ifndef PG_HAVE_ATOMIC_UNLOCKED_TEST_FLAG
+#define PG_HAVE_ATOMIC_UNLOCKED_TEST_FLAG
+static inline bool
+pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ return ptr->value == 0;
+}
+#endif
+
+#ifndef PG_HAVE_ATOMIC_CLEAR_FLAG
+#define PG_HAVE_ATOMIC_CLEAR_FLAG
+static inline void
+pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ __sync_lock_release(&ptr->value);
+}
+#endif
+
+#ifndef PG_HAVE_ATOMIC_INIT_FLAG
+#define PG_HAVE_ATOMIC_INIT_FLAG
+static inline void
+pg_atomic_init_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ pg_atomic_clear_flag_impl(ptr);
+}
+#endif
+
+#endif /* defined(PG_HAVE_ATOMIC_FLAG_SUPPORT) */
+
+/* prefer __atomic, it has a better API */
+#if !defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32) && defined(HAVE_GCC__ATOMIC_INT32_CAS)
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+static inline bool
+pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ /* FIXME: we can probably use a lower consistency model */
+ return __atomic_compare_exchange_n(&ptr->value, expected, newval, false,
+ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32) && defined(HAVE_GCC__SYNC_INT32_CAS)
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+static inline bool
+pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ bool ret;
+ uint32 current;
+ current = __sync_val_compare_and_swap(&ptr->value, *expected, newval);
+ ret = current == *expected;
+ *expected = current;
+ return ret;
+}
+#endif
+
+/* if we have 32-bit __sync_val_compare_and_swap, assume we have these too: */
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_ADD_U32) && defined(HAVE_GCC__SYNC_INT32_CAS)
+#define PG_HAVE_ATOMIC_FETCH_ADD_U32
+static inline uint32
+pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ return __sync_fetch_and_add(&ptr->value, add_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_SUB_U32) && defined(HAVE_GCC__SYNC_INT32_CAS)
+#define PG_HAVE_ATOMIC_FETCH_SUB_U32
+static inline uint32
+pg_atomic_fetch_sub_u32_impl(volatile pg_atomic_uint32 *ptr, int32 sub_)
+{
+ return __sync_fetch_and_sub(&ptr->value, sub_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_AND_U32) && defined(HAVE_GCC__SYNC_INT32_CAS)
+#define PG_HAVE_ATOMIC_FETCH_AND_U32
+static inline uint32
+pg_atomic_fetch_and_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 and_)
+{
+ return __sync_fetch_and_and(&ptr->value, and_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_OR_U32) && defined(HAVE_GCC__SYNC_INT32_CAS)
+#define PG_HAVE_ATOMIC_FETCH_OR_U32
+static inline uint32
+pg_atomic_fetch_or_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 or_)
+{
+ return __sync_fetch_and_or(&ptr->value, or_);
+}
+#endif
+
+
+#if !defined(PG_DISABLE_64_BIT_ATOMICS)
+
+#if !defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64) && defined(HAVE_GCC__ATOMIC_INT64_CAS)
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+static inline bool
+pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+ return __atomic_compare_exchange_n(&ptr->value, expected, newval, false,
+ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64) && defined(HAVE_GCC__SYNC_INT64_CAS)
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+static inline bool
+pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+ bool ret;
+ uint64 current;
+ current = __sync_val_compare_and_swap(&ptr->value, *expected, newval);
+ ret = current == *expected;
+ *expected = current;
+ return ret;
+}
+#endif
+
+/* if we have 64-bit __sync_val_compare_and_swap, assume we have these too: */
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_ADD_U64) && defined(HAVE_GCC__SYNC_INT64_CAS)
+#define PG_HAVE_ATOMIC_FETCH_ADD_U64
+static inline uint64
+pg_atomic_fetch_add_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+ return __sync_fetch_and_add(&ptr->value, add_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_SUB_U64) && defined(HAVE_GCC__SYNC_INT64_CAS)
+#define PG_HAVE_ATOMIC_FETCH_SUB_U64
+static inline uint64
+pg_atomic_fetch_sub_u64_impl(volatile pg_atomic_uint64 *ptr, int64 sub_)
+{
+ return __sync_fetch_and_sub(&ptr->value, sub_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_AND_U64) && defined(HAVE_GCC__SYNC_INT64_CAS)
+#define PG_HAVE_ATOMIC_FETCH_AND_U64
+static inline uint64
+pg_atomic_fetch_and_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 and_)
+{
+ return __sync_fetch_and_and(&ptr->value, and_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_OR_U64) && defined(HAVE_GCC__SYNC_INT64_CAS)
+#define PG_HAVE_ATOMIC_FETCH_OR_U64
+static inline uint64
+pg_atomic_fetch_or_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 or_)
+{
+ return __sync_fetch_and_or(&ptr->value, or_);
+}
+#endif
+
+#endif /* !defined(PG_DISABLE_64_BIT_ATOMICS) */
+
+#endif /* defined(HAVE_ATOMICS) */
diff --git a/pgsql/include/server/port/atomics/generic-msvc.h b/pgsql/include/server/port/atomics/generic-msvc.h
new file mode 100644
index 0000000000000000000000000000000000000000..8835f4ceea81f573768d6a2ecbbe89b0ea79a37a
--- /dev/null
+++ b/pgsql/include/server/port/atomics/generic-msvc.h
@@ -0,0 +1,101 @@
+/*-------------------------------------------------------------------------
+ *
+ * generic-msvc.h
+ * Atomic operations support when using MSVC
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES:
+ *
+ * Documentation:
+ * * Interlocked Variable Access
+ * http://msdn.microsoft.com/en-us/library/ms684122%28VS.85%29.aspx
+ *
+ * src/include/port/atomics/generic-msvc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#include
+
+/* intentionally no include guards, should only be included by atomics.h */
+#ifndef INSIDE_ATOMICS_H
+#error "should be included via atomics.h"
+#endif
+
+#pragma intrinsic(_ReadWriteBarrier)
+#define pg_compiler_barrier_impl() _ReadWriteBarrier()
+
+#ifndef pg_memory_barrier_impl
+#define pg_memory_barrier_impl() MemoryBarrier()
+#endif
+
+#if defined(HAVE_ATOMICS)
+
+#define PG_HAVE_ATOMIC_U32_SUPPORT
+typedef struct pg_atomic_uint32
+{
+ volatile uint32 value;
+} pg_atomic_uint32;
+
+#define PG_HAVE_ATOMIC_U64_SUPPORT
+typedef struct pg_attribute_aligned(8) pg_atomic_uint64
+{
+ volatile uint64 value;
+} pg_atomic_uint64;
+
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+static inline bool
+pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ bool ret;
+ uint32 current;
+ current = InterlockedCompareExchange(&ptr->value, newval, *expected);
+ ret = current == *expected;
+ *expected = current;
+ return ret;
+}
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U32
+static inline uint32
+pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ return InterlockedExchangeAdd(&ptr->value, add_);
+}
+
+/*
+ * The non-intrinsics versions are only available in vista upwards, so use the
+ * intrinsic version. Only supported on >486, but we require XP as a minimum
+ * baseline, which doesn't support the 486, so we don't need to add checks for
+ * that case.
+ */
+#pragma intrinsic(_InterlockedCompareExchange64)
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+static inline bool
+pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+ bool ret;
+ uint64 current;
+ current = _InterlockedCompareExchange64(&ptr->value, newval, *expected);
+ ret = current == *expected;
+ *expected = current;
+ return ret;
+}
+
+/* Only implemented on 64bit builds */
+#ifdef _WIN64
+#pragma intrinsic(_InterlockedExchangeAdd64)
+
+#define PG_HAVE_ATOMIC_FETCH_ADD_U64
+static inline uint64
+pg_atomic_fetch_add_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+ return _InterlockedExchangeAdd64(&ptr->value, add_);
+}
+#endif /* _WIN64 */
+
+#endif /* HAVE_ATOMICS */
diff --git a/pgsql/include/server/port/atomics/generic-sunpro.h b/pgsql/include/server/port/atomics/generic-sunpro.h
new file mode 100644
index 0000000000000000000000000000000000000000..30f7d8b5362a2bdf498263f6edcc4f36addeada5
--- /dev/null
+++ b/pgsql/include/server/port/atomics/generic-sunpro.h
@@ -0,0 +1,106 @@
+/*-------------------------------------------------------------------------
+ *
+ * generic-sunpro.h
+ * Atomic operations for solaris' CC
+ *
+ * Portions Copyright (c) 2013-2023, PostgreSQL Global Development Group
+ *
+ * NOTES:
+ *
+ * Documentation:
+ * * manpage for atomic_cas(3C)
+ * http://www.unix.com/man-page/opensolaris/3c/atomic_cas/
+ * http://docs.oracle.com/cd/E23824_01/html/821-1465/atomic-cas-3c.html
+ *
+ * src/include/port/atomics/generic-sunpro.h
+ *
+ * -------------------------------------------------------------------------
+ */
+
+#if defined(HAVE_ATOMICS)
+
+#ifdef HAVE_MBARRIER_H
+#include
+
+#define pg_compiler_barrier_impl() __compiler_barrier()
+
+#ifndef pg_memory_barrier_impl
+/*
+ * Despite the name this is actually a full barrier. Expanding to mfence/
+ * membar #StoreStore | #LoadStore | #StoreLoad | #LoadLoad on x86/sparc
+ * respectively.
+ */
+# define pg_memory_barrier_impl() __machine_rw_barrier()
+#endif
+#ifndef pg_read_barrier_impl
+# define pg_read_barrier_impl() __machine_r_barrier()
+#endif
+#ifndef pg_write_barrier_impl
+# define pg_write_barrier_impl() __machine_w_barrier()
+#endif
+
+#endif /* HAVE_MBARRIER_H */
+
+/* Older versions of the compiler don't have atomic.h... */
+#ifdef HAVE_ATOMIC_H
+
+#include
+
+#define PG_HAVE_ATOMIC_U32_SUPPORT
+typedef struct pg_atomic_uint32
+{
+ volatile uint32 value;
+} pg_atomic_uint32;
+
+#define PG_HAVE_ATOMIC_U64_SUPPORT
+typedef struct pg_atomic_uint64
+{
+ /*
+ * Syntax to enforce variable alignment should be supported by versions
+ * supporting atomic.h, but it's hard to find accurate documentation. If
+ * it proves to be a problem, we'll have to add more version checks for 64
+ * bit support.
+ */
+ volatile uint64 value pg_attribute_aligned(8);
+} pg_atomic_uint64;
+
+#endif /* HAVE_ATOMIC_H */
+
+#endif /* defined(HAVE_ATOMICS) */
+
+
+#if defined(HAVE_ATOMICS)
+
+#ifdef HAVE_ATOMIC_H
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32
+static inline bool
+pg_atomic_compare_exchange_u32_impl(volatile pg_atomic_uint32 *ptr,
+ uint32 *expected, uint32 newval)
+{
+ bool ret;
+ uint32 current;
+
+ current = atomic_cas_32(&ptr->value, *expected, newval);
+ ret = current == *expected;
+ *expected = current;
+ return ret;
+}
+
+#define PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64
+static inline bool
+pg_atomic_compare_exchange_u64_impl(volatile pg_atomic_uint64 *ptr,
+ uint64 *expected, uint64 newval)
+{
+ bool ret;
+ uint64 current;
+
+ current = atomic_cas_64(&ptr->value, *expected, newval);
+ ret = current == *expected;
+ *expected = current;
+ return ret;
+}
+
+#endif /* HAVE_ATOMIC_H */
+
+#endif /* defined(HAVE_ATOMICS) */
diff --git a/pgsql/include/server/port/atomics/generic.h b/pgsql/include/server/port/atomics/generic.h
new file mode 100644
index 0000000000000000000000000000000000000000..95d99dd0be0a6fb3463e80ee28b00709f2066f4c
--- /dev/null
+++ b/pgsql/include/server/port/atomics/generic.h
@@ -0,0 +1,401 @@
+/*-------------------------------------------------------------------------
+ *
+ * generic.h
+ * Implement higher level operations based on some lower level atomic
+ * operations.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/atomics/generic.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/* intentionally no include guards, should only be included by atomics.h */
+#ifndef INSIDE_ATOMICS_H
+# error "should be included via atomics.h"
+#endif
+
+/*
+ * If read or write barriers are undefined, we upgrade them to full memory
+ * barriers.
+ */
+#if !defined(pg_read_barrier_impl)
+# define pg_read_barrier_impl pg_memory_barrier_impl
+#endif
+#if !defined(pg_write_barrier_impl)
+# define pg_write_barrier_impl pg_memory_barrier_impl
+#endif
+
+#ifndef PG_HAVE_SPIN_DELAY
+#define PG_HAVE_SPIN_DELAY
+#define pg_spin_delay_impl() ((void)0)
+#endif
+
+
+/* provide fallback */
+#if !defined(PG_HAVE_ATOMIC_FLAG_SUPPORT) && defined(PG_HAVE_ATOMIC_U32_SUPPORT)
+#define PG_HAVE_ATOMIC_FLAG_SUPPORT
+typedef pg_atomic_uint32 pg_atomic_flag;
+#endif
+
+#ifndef PG_HAVE_ATOMIC_READ_U32
+#define PG_HAVE_ATOMIC_READ_U32
+static inline uint32
+pg_atomic_read_u32_impl(volatile pg_atomic_uint32 *ptr)
+{
+ return ptr->value;
+}
+#endif
+
+#ifndef PG_HAVE_ATOMIC_WRITE_U32
+#define PG_HAVE_ATOMIC_WRITE_U32
+static inline void
+pg_atomic_write_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 val)
+{
+ ptr->value = val;
+}
+#endif
+
+#ifndef PG_HAVE_ATOMIC_UNLOCKED_WRITE_U32
+#define PG_HAVE_ATOMIC_UNLOCKED_WRITE_U32
+static inline void
+pg_atomic_unlocked_write_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 val)
+{
+ ptr->value = val;
+}
+#endif
+
+/*
+ * provide fallback for test_and_set using atomic_exchange if available
+ */
+#if !defined(PG_HAVE_ATOMIC_TEST_SET_FLAG) && defined(PG_HAVE_ATOMIC_EXCHANGE_U32)
+
+#define PG_HAVE_ATOMIC_INIT_FLAG
+static inline void
+pg_atomic_init_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ pg_atomic_write_u32_impl(ptr, 0);
+}
+
+#define PG_HAVE_ATOMIC_TEST_SET_FLAG
+static inline bool
+pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ return pg_atomic_exchange_u32_impl(ptr, 1) == 0;
+}
+
+#define PG_HAVE_ATOMIC_UNLOCKED_TEST_FLAG
+static inline bool
+pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ return pg_atomic_read_u32_impl(ptr) == 0;
+}
+
+
+#define PG_HAVE_ATOMIC_CLEAR_FLAG
+static inline void
+pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ /* XXX: release semantics suffice? */
+ pg_memory_barrier_impl();
+ pg_atomic_write_u32_impl(ptr, 0);
+}
+
+/*
+ * provide fallback for test_and_set using atomic_compare_exchange if
+ * available.
+ */
+#elif !defined(PG_HAVE_ATOMIC_TEST_SET_FLAG) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32)
+
+#define PG_HAVE_ATOMIC_INIT_FLAG
+static inline void
+pg_atomic_init_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ pg_atomic_write_u32_impl(ptr, 0);
+}
+
+#define PG_HAVE_ATOMIC_TEST_SET_FLAG
+static inline bool
+pg_atomic_test_set_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ uint32 value = 0;
+ return pg_atomic_compare_exchange_u32_impl(ptr, &value, 1);
+}
+
+#define PG_HAVE_ATOMIC_UNLOCKED_TEST_FLAG
+static inline bool
+pg_atomic_unlocked_test_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ return pg_atomic_read_u32_impl(ptr) == 0;
+}
+
+#define PG_HAVE_ATOMIC_CLEAR_FLAG
+static inline void
+pg_atomic_clear_flag_impl(volatile pg_atomic_flag *ptr)
+{
+ /*
+ * Use a memory barrier + plain write if we have a native memory
+ * barrier. But don't do so if memory barriers use spinlocks - that'd lead
+ * to circularity if flags are used to implement spinlocks.
+ */
+#ifndef PG_HAVE_MEMORY_BARRIER_EMULATION
+ /* XXX: release semantics suffice? */
+ pg_memory_barrier_impl();
+ pg_atomic_write_u32_impl(ptr, 0);
+#else
+ uint32 value = 1;
+ pg_atomic_compare_exchange_u32_impl(ptr, &value, 0);
+#endif
+}
+
+#elif !defined(PG_HAVE_ATOMIC_TEST_SET_FLAG)
+# error "No pg_atomic_test_and_set provided"
+#endif /* !defined(PG_HAVE_ATOMIC_TEST_SET_FLAG) */
+
+
+#ifndef PG_HAVE_ATOMIC_INIT_U32
+#define PG_HAVE_ATOMIC_INIT_U32
+static inline void
+pg_atomic_init_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 val_)
+{
+ ptr->value = val_;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_EXCHANGE_U32) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32)
+#define PG_HAVE_ATOMIC_EXCHANGE_U32
+static inline uint32
+pg_atomic_exchange_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 xchg_)
+{
+ uint32 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u32_impl(ptr, &old, xchg_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_ADD_U32) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32)
+#define PG_HAVE_ATOMIC_FETCH_ADD_U32
+static inline uint32
+pg_atomic_fetch_add_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ uint32 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u32_impl(ptr, &old, old + add_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_SUB_U32) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32)
+#define PG_HAVE_ATOMIC_FETCH_SUB_U32
+static inline uint32
+pg_atomic_fetch_sub_u32_impl(volatile pg_atomic_uint32 *ptr, int32 sub_)
+{
+ return pg_atomic_fetch_add_u32_impl(ptr, -sub_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_AND_U32) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32)
+#define PG_HAVE_ATOMIC_FETCH_AND_U32
+static inline uint32
+pg_atomic_fetch_and_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 and_)
+{
+ uint32 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u32_impl(ptr, &old, old & and_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_OR_U32) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U32)
+#define PG_HAVE_ATOMIC_FETCH_OR_U32
+static inline uint32
+pg_atomic_fetch_or_u32_impl(volatile pg_atomic_uint32 *ptr, uint32 or_)
+{
+ uint32 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u32_impl(ptr, &old, old | or_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_ADD_FETCH_U32) && defined(PG_HAVE_ATOMIC_FETCH_ADD_U32)
+#define PG_HAVE_ATOMIC_ADD_FETCH_U32
+static inline uint32
+pg_atomic_add_fetch_u32_impl(volatile pg_atomic_uint32 *ptr, int32 add_)
+{
+ return pg_atomic_fetch_add_u32_impl(ptr, add_) + add_;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_SUB_FETCH_U32) && defined(PG_HAVE_ATOMIC_FETCH_SUB_U32)
+#define PG_HAVE_ATOMIC_SUB_FETCH_U32
+static inline uint32
+pg_atomic_sub_fetch_u32_impl(volatile pg_atomic_uint32 *ptr, int32 sub_)
+{
+ return pg_atomic_fetch_sub_u32_impl(ptr, sub_) - sub_;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_EXCHANGE_U64) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64)
+#define PG_HAVE_ATOMIC_EXCHANGE_U64
+static inline uint64
+pg_atomic_exchange_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 xchg_)
+{
+ uint64 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u64_impl(ptr, &old, xchg_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#ifndef PG_HAVE_ATOMIC_WRITE_U64
+#define PG_HAVE_ATOMIC_WRITE_U64
+
+#if defined(PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY) && \
+ !defined(PG_HAVE_ATOMIC_U64_SIMULATION)
+
+static inline void
+pg_atomic_write_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 val)
+{
+ /*
+ * On this platform aligned 64bit writes are guaranteed to be atomic,
+ * except if using the fallback implementation, where can't guarantee the
+ * required alignment.
+ */
+ AssertPointerAlignment(ptr, 8);
+ ptr->value = val;
+}
+
+#else
+
+static inline void
+pg_atomic_write_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 val)
+{
+ /*
+ * 64 bit writes aren't safe on all platforms. In the generic
+ * implementation implement them as an atomic exchange.
+ */
+ pg_atomic_exchange_u64_impl(ptr, val);
+}
+
+#endif /* PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY && !PG_HAVE_ATOMIC_U64_SIMULATION */
+#endif /* PG_HAVE_ATOMIC_WRITE_U64 */
+
+#ifndef PG_HAVE_ATOMIC_READ_U64
+#define PG_HAVE_ATOMIC_READ_U64
+
+#if defined(PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY) && \
+ !defined(PG_HAVE_ATOMIC_U64_SIMULATION)
+
+static inline uint64
+pg_atomic_read_u64_impl(volatile pg_atomic_uint64 *ptr)
+{
+ /*
+ * On this platform aligned 64-bit reads are guaranteed to be atomic.
+ */
+ AssertPointerAlignment(ptr, 8);
+ return ptr->value;
+}
+
+#else
+
+static inline uint64
+pg_atomic_read_u64_impl(volatile pg_atomic_uint64 *ptr)
+{
+ uint64 old = 0;
+
+ /*
+ * 64-bit reads aren't atomic on all platforms. In the generic
+ * implementation implement them as a compare/exchange with 0. That'll
+ * fail or succeed, but always return the old value. Possibly might store
+ * a 0, but only if the previous value also was a 0 - i.e. harmless.
+ */
+ pg_atomic_compare_exchange_u64_impl(ptr, &old, 0);
+
+ return old;
+}
+#endif /* PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY && !PG_HAVE_ATOMIC_U64_SIMULATION */
+#endif /* PG_HAVE_ATOMIC_READ_U64 */
+
+#ifndef PG_HAVE_ATOMIC_INIT_U64
+#define PG_HAVE_ATOMIC_INIT_U64
+static inline void
+pg_atomic_init_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 val_)
+{
+ ptr->value = val_;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_ADD_U64) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64)
+#define PG_HAVE_ATOMIC_FETCH_ADD_U64
+static inline uint64
+pg_atomic_fetch_add_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+ uint64 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u64_impl(ptr, &old, old + add_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_SUB_U64) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64)
+#define PG_HAVE_ATOMIC_FETCH_SUB_U64
+static inline uint64
+pg_atomic_fetch_sub_u64_impl(volatile pg_atomic_uint64 *ptr, int64 sub_)
+{
+ return pg_atomic_fetch_add_u64_impl(ptr, -sub_);
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_AND_U64) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64)
+#define PG_HAVE_ATOMIC_FETCH_AND_U64
+static inline uint64
+pg_atomic_fetch_and_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 and_)
+{
+ uint64 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u64_impl(ptr, &old, old & and_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_FETCH_OR_U64) && defined(PG_HAVE_ATOMIC_COMPARE_EXCHANGE_U64)
+#define PG_HAVE_ATOMIC_FETCH_OR_U64
+static inline uint64
+pg_atomic_fetch_or_u64_impl(volatile pg_atomic_uint64 *ptr, uint64 or_)
+{
+ uint64 old;
+ old = ptr->value; /* ok if read is not atomic */
+ while (!pg_atomic_compare_exchange_u64_impl(ptr, &old, old | or_))
+ /* skip */;
+ return old;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_ADD_FETCH_U64) && defined(PG_HAVE_ATOMIC_FETCH_ADD_U64)
+#define PG_HAVE_ATOMIC_ADD_FETCH_U64
+static inline uint64
+pg_atomic_add_fetch_u64_impl(volatile pg_atomic_uint64 *ptr, int64 add_)
+{
+ return pg_atomic_fetch_add_u64_impl(ptr, add_) + add_;
+}
+#endif
+
+#if !defined(PG_HAVE_ATOMIC_SUB_FETCH_U64) && defined(PG_HAVE_ATOMIC_FETCH_SUB_U64)
+#define PG_HAVE_ATOMIC_SUB_FETCH_U64
+static inline uint64
+pg_atomic_sub_fetch_u64_impl(volatile pg_atomic_uint64 *ptr, int64 sub_)
+{
+ return pg_atomic_fetch_sub_u64_impl(ptr, sub_) - sub_;
+}
+#endif
diff --git a/pgsql/include/server/port/cygwin.h b/pgsql/include/server/port/cygwin.h
new file mode 100644
index 0000000000000000000000000000000000000000..44bf8533729cc6c4d214a8c637c2f1e6d5b171ed
--- /dev/null
+++ b/pgsql/include/server/port/cygwin.h
@@ -0,0 +1,23 @@
+/* src/include/port/cygwin.h */
+
+/*
+ * Variables declared in the core backend and referenced by loadable
+ * modules need to be marked "dllimport" in the core build, but
+ * "dllexport" when the declaration is read in a loadable module.
+ * No special markings should be used when compiling frontend code.
+ */
+#ifndef FRONTEND
+#ifdef BUILDING_DLL
+#define PGDLLIMPORT __declspec (dllexport)
+#else
+#define PGDLLIMPORT __declspec (dllimport)
+#endif
+#endif
+
+/*
+ * Cygwin has a strtof() which is literally just (float)strtod(), which means
+ * we get misrounding _and_ silent over/underflow. Using our wrapper doesn't
+ * fix the misrounding but does fix the error checks, which cuts down on the
+ * number of test variant files needed.
+ */
+#define HAVE_BUGGY_STRTOF 1
diff --git a/pgsql/include/server/port/darwin.h b/pgsql/include/server/port/darwin.h
new file mode 100644
index 0000000000000000000000000000000000000000..15fb69d6dbb4bcf60b26640146f6f850296bcc63
--- /dev/null
+++ b/pgsql/include/server/port/darwin.h
@@ -0,0 +1,8 @@
+/* src/include/port/darwin.h */
+
+#define __darwin__ 1
+
+#if HAVE_DECL_F_FULLFSYNC /* not present before macOS 10.3 */
+#define HAVE_FSYNC_WRITETHROUGH
+
+#endif
diff --git a/pgsql/include/server/port/freebsd.h b/pgsql/include/server/port/freebsd.h
new file mode 100644
index 0000000000000000000000000000000000000000..0e3fde55d6d9ad99a4a473eabcc79067fafd2fc5
--- /dev/null
+++ b/pgsql/include/server/port/freebsd.h
@@ -0,0 +1,8 @@
+/* src/include/port/freebsd.h */
+
+/*
+ * Set the default wal_sync_method to fdatasync. xlogdefs.h's normal rules
+ * would prefer open_datasync on FreeBSD 13+, but that is not a good choice on
+ * many systems.
+ */
+#define PLATFORM_DEFAULT_SYNC_METHOD SYNC_METHOD_FDATASYNC
diff --git a/pgsql/include/server/port/linux.h b/pgsql/include/server/port/linux.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a6e46cdbb787f8196ed1c28e0d046a1748ed4f0
--- /dev/null
+++ b/pgsql/include/server/port/linux.h
@@ -0,0 +1,22 @@
+/* src/include/port/linux.h */
+
+/*
+ * As of July 2007, all known versions of the Linux kernel will sometimes
+ * return EIDRM for a shmctl() operation when EINVAL is correct (it happens
+ * when the low-order 15 bits of the supplied shm ID match the slot number
+ * assigned to a newer shmem segment). We deal with this by assuming that
+ * EIDRM means EINVAL in PGSharedMemoryIsInUse(). This is reasonably safe
+ * since in fact Linux has no excuse for ever returning EIDRM; it doesn't
+ * track removed segments in a way that would allow distinguishing them from
+ * private ones. But someday that code might get upgraded, and we'd have
+ * to have a kernel version test here.
+ */
+#define HAVE_LINUX_EIDRM_BUG
+
+/*
+ * Set the default wal_sync_method to fdatasync. With recent Linux versions,
+ * xlogdefs.h's normal rules will prefer open_datasync, which (a) doesn't
+ * perform better and (b) causes outright failures on ext4 data=journal
+ * filesystems, because those don't support O_DIRECT.
+ */
+#define PLATFORM_DEFAULT_SYNC_METHOD SYNC_METHOD_FDATASYNC
diff --git a/pgsql/include/server/port/netbsd.h b/pgsql/include/server/port/netbsd.h
new file mode 100644
index 0000000000000000000000000000000000000000..590233fbdb47fbed00905ab1d06a00885135086e
--- /dev/null
+++ b/pgsql/include/server/port/netbsd.h
@@ -0,0 +1 @@
+/* src/include/port/netbsd.h */
diff --git a/pgsql/include/server/port/openbsd.h b/pgsql/include/server/port/openbsd.h
new file mode 100644
index 0000000000000000000000000000000000000000..395319bd77c6e3bb62925c6807a27fa2fbfead14
--- /dev/null
+++ b/pgsql/include/server/port/openbsd.h
@@ -0,0 +1 @@
+/* src/include/port/openbsd.h */
diff --git a/pgsql/include/server/port/pg_bitutils.h b/pgsql/include/server/port/pg_bitutils.h
new file mode 100644
index 0000000000000000000000000000000000000000..21a4fa0341059c722be99a61665edeb5f23c7a8f
--- /dev/null
+++ b/pgsql/include/server/port/pg_bitutils.h
@@ -0,0 +1,339 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_bitutils.h
+ * Miscellaneous functions for bit-wise operations.
+ *
+ *
+ * Copyright (c) 2019-2023, PostgreSQL Global Development Group
+ *
+ * src/include/port/pg_bitutils.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_BITUTILS_H
+#define PG_BITUTILS_H
+
+#ifdef _MSC_VER
+#include
+#define HAVE_BITSCAN_FORWARD
+#define HAVE_BITSCAN_REVERSE
+
+#else
+#if defined(HAVE__BUILTIN_CTZ)
+#define HAVE_BITSCAN_FORWARD
+#endif
+
+#if defined(HAVE__BUILTIN_CLZ)
+#define HAVE_BITSCAN_REVERSE
+#endif
+#endif /* _MSC_VER */
+
+extern PGDLLIMPORT const uint8 pg_leftmost_one_pos[256];
+extern PGDLLIMPORT const uint8 pg_rightmost_one_pos[256];
+extern PGDLLIMPORT const uint8 pg_number_of_ones[256];
+
+/*
+ * pg_leftmost_one_pos32
+ * Returns the position of the most significant set bit in "word",
+ * measured from the least significant bit. word must not be 0.
+ */
+static inline int
+pg_leftmost_one_pos32(uint32 word)
+{
+#ifdef HAVE__BUILTIN_CLZ
+ Assert(word != 0);
+
+ return 31 - __builtin_clz(word);
+#elif defined(_MSC_VER)
+ unsigned long result;
+ bool non_zero;
+
+ non_zero = _BitScanReverse(&result, word);
+ Assert(non_zero);
+ return (int) result;
+#else
+ int shift = 32 - 8;
+
+ Assert(word != 0);
+
+ while ((word >> shift) == 0)
+ shift -= 8;
+
+ return shift + pg_leftmost_one_pos[(word >> shift) & 255];
+#endif /* HAVE__BUILTIN_CLZ */
+}
+
+/*
+ * pg_leftmost_one_pos64
+ * As above, but for a 64-bit word.
+ */
+static inline int
+pg_leftmost_one_pos64(uint64 word)
+{
+#ifdef HAVE__BUILTIN_CLZ
+ Assert(word != 0);
+
+#if defined(HAVE_LONG_INT_64)
+ return 63 - __builtin_clzl(word);
+#elif defined(HAVE_LONG_LONG_INT_64)
+ return 63 - __builtin_clzll(word);
+#else
+#error must have a working 64-bit integer datatype
+#endif /* HAVE_LONG_INT_64 */
+
+#elif defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_ARM64))
+ unsigned long result;
+ bool non_zero;
+
+ non_zero = _BitScanReverse64(&result, word);
+ Assert(non_zero);
+ return (int) result;
+#else
+ int shift = 64 - 8;
+
+ Assert(word != 0);
+
+ while ((word >> shift) == 0)
+ shift -= 8;
+
+ return shift + pg_leftmost_one_pos[(word >> shift) & 255];
+#endif /* HAVE__BUILTIN_CLZ */
+}
+
+/*
+ * pg_rightmost_one_pos32
+ * Returns the position of the least significant set bit in "word",
+ * measured from the least significant bit. word must not be 0.
+ */
+static inline int
+pg_rightmost_one_pos32(uint32 word)
+{
+#ifdef HAVE__BUILTIN_CTZ
+ Assert(word != 0);
+
+ return __builtin_ctz(word);
+#elif defined(_MSC_VER)
+ unsigned long result;
+ bool non_zero;
+
+ non_zero = _BitScanForward(&result, word);
+ Assert(non_zero);
+ return (int) result;
+#else
+ int result = 0;
+
+ Assert(word != 0);
+
+ while ((word & 255) == 0)
+ {
+ word >>= 8;
+ result += 8;
+ }
+ result += pg_rightmost_one_pos[word & 255];
+ return result;
+#endif /* HAVE__BUILTIN_CTZ */
+}
+
+/*
+ * pg_rightmost_one_pos64
+ * As above, but for a 64-bit word.
+ */
+static inline int
+pg_rightmost_one_pos64(uint64 word)
+{
+#ifdef HAVE__BUILTIN_CTZ
+ Assert(word != 0);
+
+#if defined(HAVE_LONG_INT_64)
+ return __builtin_ctzl(word);
+#elif defined(HAVE_LONG_LONG_INT_64)
+ return __builtin_ctzll(word);
+#else
+#error must have a working 64-bit integer datatype
+#endif /* HAVE_LONG_INT_64 */
+
+#elif defined(_MSC_VER) && (defined(_M_AMD64) || defined(_M_ARM64))
+ unsigned long result;
+ bool non_zero;
+
+ non_zero = _BitScanForward64(&result, word);
+ Assert(non_zero);
+ return (int) result;
+#else
+ int result = 0;
+
+ Assert(word != 0);
+
+ while ((word & 255) == 0)
+ {
+ word >>= 8;
+ result += 8;
+ }
+ result += pg_rightmost_one_pos[word & 255];
+ return result;
+#endif /* HAVE__BUILTIN_CTZ */
+}
+
+/*
+ * pg_nextpower2_32
+ * Returns the next higher power of 2 above 'num', or 'num' if it's
+ * already a power of 2.
+ *
+ * 'num' mustn't be 0 or be above PG_UINT32_MAX / 2 + 1.
+ */
+static inline uint32
+pg_nextpower2_32(uint32 num)
+{
+ Assert(num > 0 && num <= PG_UINT32_MAX / 2 + 1);
+
+ /*
+ * A power 2 number has only 1 bit set. Subtracting 1 from such a number
+ * will turn on all previous bits resulting in no common bits being set
+ * between num and num-1.
+ */
+ if ((num & (num - 1)) == 0)
+ return num; /* already power 2 */
+
+ return ((uint32) 1) << (pg_leftmost_one_pos32(num) + 1);
+}
+
+/*
+ * pg_nextpower2_64
+ * Returns the next higher power of 2 above 'num', or 'num' if it's
+ * already a power of 2.
+ *
+ * 'num' mustn't be 0 or be above PG_UINT64_MAX / 2 + 1.
+ */
+static inline uint64
+pg_nextpower2_64(uint64 num)
+{
+ Assert(num > 0 && num <= PG_UINT64_MAX / 2 + 1);
+
+ /*
+ * A power 2 number has only 1 bit set. Subtracting 1 from such a number
+ * will turn on all previous bits resulting in no common bits being set
+ * between num and num-1.
+ */
+ if ((num & (num - 1)) == 0)
+ return num; /* already power 2 */
+
+ return ((uint64) 1) << (pg_leftmost_one_pos64(num) + 1);
+}
+
+/*
+ * pg_prevpower2_32
+ * Returns the next lower power of 2 below 'num', or 'num' if it's
+ * already a power of 2.
+ *
+ * 'num' mustn't be 0.
+ */
+static inline uint32
+pg_prevpower2_32(uint32 num)
+{
+ return ((uint32) 1) << pg_leftmost_one_pos32(num);
+}
+
+/*
+ * pg_prevpower2_64
+ * Returns the next lower power of 2 below 'num', or 'num' if it's
+ * already a power of 2.
+ *
+ * 'num' mustn't be 0.
+ */
+static inline uint64
+pg_prevpower2_64(uint64 num)
+{
+ return ((uint64) 1) << pg_leftmost_one_pos64(num);
+}
+
+/*
+ * pg_ceil_log2_32
+ * Returns equivalent of ceil(log2(num))
+ */
+static inline uint32
+pg_ceil_log2_32(uint32 num)
+{
+ if (num < 2)
+ return 0;
+ else
+ return pg_leftmost_one_pos32(num - 1) + 1;
+}
+
+/*
+ * pg_ceil_log2_64
+ * Returns equivalent of ceil(log2(num))
+ */
+static inline uint64
+pg_ceil_log2_64(uint64 num)
+{
+ if (num < 2)
+ return 0;
+ else
+ return pg_leftmost_one_pos64(num - 1) + 1;
+}
+
+/*
+ * With MSVC on x86_64 builds, try using native popcnt instructions via the
+ * __popcnt and __popcnt64 intrinsics. These don't work the same as GCC's
+ * __builtin_popcount* intrinsic functions as they always emit popcnt
+ * instructions.
+ */
+#if defined(_MSC_VER) && defined(_M_AMD64)
+#define HAVE_X86_64_POPCNTQ
+#endif
+
+/*
+ * On x86_64, we can use the hardware popcount instruction, but only if
+ * we can verify that the CPU supports it via the cpuid instruction.
+ *
+ * Otherwise, we fall back to a hand-rolled implementation.
+ */
+#ifdef HAVE_X86_64_POPCNTQ
+#if defined(HAVE__GET_CPUID) || defined(HAVE__CPUID)
+#define TRY_POPCNT_FAST 1
+#endif
+#endif
+
+#ifdef TRY_POPCNT_FAST
+/* Attempt to use the POPCNT instruction, but perform a runtime check first */
+extern int (*pg_popcount32) (uint32 word);
+extern int (*pg_popcount64) (uint64 word);
+
+#else
+/* Use a portable implementation -- no need for a function pointer. */
+extern int pg_popcount32(uint32 word);
+extern int pg_popcount64(uint64 word);
+
+#endif /* TRY_POPCNT_FAST */
+
+/* Count the number of one-bits in a byte array */
+extern uint64 pg_popcount(const char *buf, int bytes);
+
+/*
+ * Rotate the bits of "word" to the right/left by n bits.
+ */
+static inline uint32
+pg_rotate_right32(uint32 word, int n)
+{
+ return (word >> n) | (word << (32 - n));
+}
+
+static inline uint32
+pg_rotate_left32(uint32 word, int n)
+{
+ return (word << n) | (word >> (32 - n));
+}
+
+/* size_t variants of the above, as required */
+
+#if SIZEOF_SIZE_T == 4
+#define pg_leftmost_one_pos_size_t pg_leftmost_one_pos32
+#define pg_nextpower2_size_t pg_nextpower2_32
+#define pg_prevpower2_size_t pg_prevpower2_32
+#else
+#define pg_leftmost_one_pos_size_t pg_leftmost_one_pos64
+#define pg_nextpower2_size_t pg_nextpower2_64
+#define pg_prevpower2_size_t pg_prevpower2_64
+#endif
+
+#endif /* PG_BITUTILS_H */
diff --git a/pgsql/include/server/port/pg_bswap.h b/pgsql/include/server/port/pg_bswap.h
new file mode 100644
index 0000000000000000000000000000000000000000..80abd750d41b3fa9d76715d031daf22dc8c62073
--- /dev/null
+++ b/pgsql/include/server/port/pg_bswap.h
@@ -0,0 +1,161 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_bswap.h
+ * Byte swapping.
+ *
+ * Macros for reversing the byte order of 16, 32 and 64-bit unsigned integers.
+ * For example, 0xAABBCCDD becomes 0xDDCCBBAA. These are just wrappers for
+ * built-in functions provided by the compiler where support exists.
+ *
+ * Note that all of these functions accept unsigned integers as arguments and
+ * return the same. Use caution when using these wrapper macros with signed
+ * integers.
+ *
+ * Copyright (c) 2015-2023, PostgreSQL Global Development Group
+ *
+ * src/include/port/pg_bswap.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_BSWAP_H
+#define PG_BSWAP_H
+
+
+/*
+ * In all supported versions msvc provides _byteswap_* functions in stdlib.h,
+ * already included by c.h.
+ */
+
+
+/* implementation of uint16 pg_bswap16(uint16) */
+#if defined(HAVE__BUILTIN_BSWAP16)
+
+#define pg_bswap16(x) __builtin_bswap16(x)
+
+#elif defined(_MSC_VER)
+
+#define pg_bswap16(x) _byteswap_ushort(x)
+
+#else
+
+static inline uint16
+pg_bswap16(uint16 x)
+{
+ return
+ ((x << 8) & 0xff00) |
+ ((x >> 8) & 0x00ff);
+}
+
+#endif /* HAVE__BUILTIN_BSWAP16 */
+
+
+/* implementation of uint32 pg_bswap32(uint32) */
+#if defined(HAVE__BUILTIN_BSWAP32)
+
+#define pg_bswap32(x) __builtin_bswap32(x)
+
+#elif defined(_MSC_VER)
+
+#define pg_bswap32(x) _byteswap_ulong(x)
+
+#else
+
+static inline uint32
+pg_bswap32(uint32 x)
+{
+ return
+ ((x << 24) & 0xff000000) |
+ ((x << 8) & 0x00ff0000) |
+ ((x >> 8) & 0x0000ff00) |
+ ((x >> 24) & 0x000000ff);
+}
+
+#endif /* HAVE__BUILTIN_BSWAP32 */
+
+
+/* implementation of uint64 pg_bswap64(uint64) */
+#if defined(HAVE__BUILTIN_BSWAP64)
+
+#define pg_bswap64(x) __builtin_bswap64(x)
+
+
+#elif defined(_MSC_VER)
+
+#define pg_bswap64(x) _byteswap_uint64(x)
+
+#else
+
+static inline uint64
+pg_bswap64(uint64 x)
+{
+ return
+ ((x << 56) & UINT64CONST(0xff00000000000000)) |
+ ((x << 40) & UINT64CONST(0x00ff000000000000)) |
+ ((x << 24) & UINT64CONST(0x0000ff0000000000)) |
+ ((x << 8) & UINT64CONST(0x000000ff00000000)) |
+ ((x >> 8) & UINT64CONST(0x00000000ff000000)) |
+ ((x >> 24) & UINT64CONST(0x0000000000ff0000)) |
+ ((x >> 40) & UINT64CONST(0x000000000000ff00)) |
+ ((x >> 56) & UINT64CONST(0x00000000000000ff));
+}
+#endif /* HAVE__BUILTIN_BSWAP64 */
+
+
+/*
+ * Portable and fast equivalents for ntohs, ntohl, htons, htonl,
+ * additionally extended to 64 bits.
+ */
+#ifdef WORDS_BIGENDIAN
+
+#define pg_hton16(x) (x)
+#define pg_hton32(x) (x)
+#define pg_hton64(x) (x)
+
+#define pg_ntoh16(x) (x)
+#define pg_ntoh32(x) (x)
+#define pg_ntoh64(x) (x)
+
+#else
+
+#define pg_hton16(x) pg_bswap16(x)
+#define pg_hton32(x) pg_bswap32(x)
+#define pg_hton64(x) pg_bswap64(x)
+
+#define pg_ntoh16(x) pg_bswap16(x)
+#define pg_ntoh32(x) pg_bswap32(x)
+#define pg_ntoh64(x) pg_bswap64(x)
+
+#endif /* WORDS_BIGENDIAN */
+
+
+/*
+ * Rearrange the bytes of a Datum from big-endian order into the native byte
+ * order. On big-endian machines, this does nothing at all. Note that the C
+ * type Datum is an unsigned integer type on all platforms.
+ *
+ * One possible application of the DatumBigEndianToNative() macro is to make
+ * bitwise comparisons cheaper. A simple 3-way comparison of Datums
+ * transformed by the macro (based on native, unsigned comparisons) will return
+ * the same result as a memcmp() of the corresponding original Datums, but can
+ * be much cheaper. It's generally safe to do this on big-endian systems
+ * without any special transformation occurring first.
+ *
+ * If SIZEOF_DATUM is not defined, then postgres.h wasn't included and these
+ * macros probably shouldn't be used, so we define nothing. Note that
+ * SIZEOF_DATUM == 8 would evaluate as 0 == 8 in that case, potentially
+ * leading to the wrong implementation being selected and confusing errors, so
+ * defining nothing is safest.
+ */
+#ifdef SIZEOF_DATUM
+#ifdef WORDS_BIGENDIAN
+#define DatumBigEndianToNative(x) (x)
+#else /* !WORDS_BIGENDIAN */
+#if SIZEOF_DATUM == 8
+#define DatumBigEndianToNative(x) pg_bswap64(x)
+#else /* SIZEOF_DATUM != 8 */
+#define DatumBigEndianToNative(x) pg_bswap32(x)
+#endif /* SIZEOF_DATUM == 8 */
+#endif /* WORDS_BIGENDIAN */
+#endif /* SIZEOF_DATUM */
+
+#endif /* PG_BSWAP_H */
diff --git a/pgsql/include/server/port/pg_crc32c.h b/pgsql/include/server/port/pg_crc32c.h
new file mode 100644
index 0000000000000000000000000000000000000000..7f8779261c3c98949413c1a9ad7679f666bb8e52
--- /dev/null
+++ b/pgsql/include/server/port/pg_crc32c.h
@@ -0,0 +1,101 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_crc32c.h
+ * Routines for computing CRC-32C checksums.
+ *
+ * The speed of CRC-32C calculation has a big impact on performance, so we
+ * jump through some hoops to get the best implementation for each
+ * platform. Some CPU architectures have special instructions for speeding
+ * up CRC calculations (e.g. Intel SSE 4.2), on other platforms we use the
+ * Slicing-by-8 algorithm which uses lookup tables.
+ *
+ * The public interface consists of four macros:
+ *
+ * INIT_CRC32C(crc)
+ * Initialize a CRC accumulator
+ *
+ * COMP_CRC32C(crc, data, len)
+ * Accumulate some (more) bytes into a CRC
+ *
+ * FIN_CRC32C(crc)
+ * Finish a CRC calculation
+ *
+ * EQ_CRC32C(c1, c2)
+ * Check for equality of two CRCs.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/pg_crc32c.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_CRC32C_H
+#define PG_CRC32C_H
+
+#include "port/pg_bswap.h"
+
+typedef uint32 pg_crc32c;
+
+/* The INIT and EQ macros are the same for all implementations. */
+#define INIT_CRC32C(crc) ((crc) = 0xFFFFFFFF)
+#define EQ_CRC32C(c1, c2) ((c1) == (c2))
+
+#if defined(USE_SSE42_CRC32C)
+/* Use Intel SSE4.2 instructions. */
+#define COMP_CRC32C(crc, data, len) \
+ ((crc) = pg_comp_crc32c_sse42((crc), (data), (len)))
+#define FIN_CRC32C(crc) ((crc) ^= 0xFFFFFFFF)
+
+extern pg_crc32c pg_comp_crc32c_sse42(pg_crc32c crc, const void *data, size_t len);
+
+#elif defined(USE_ARMV8_CRC32C)
+/* Use ARMv8 CRC Extension instructions. */
+
+#define COMP_CRC32C(crc, data, len) \
+ ((crc) = pg_comp_crc32c_armv8((crc), (data), (len)))
+#define FIN_CRC32C(crc) ((crc) ^= 0xFFFFFFFF)
+
+extern pg_crc32c pg_comp_crc32c_armv8(pg_crc32c crc, const void *data, size_t len);
+
+#elif defined(USE_SSE42_CRC32C_WITH_RUNTIME_CHECK) || defined(USE_ARMV8_CRC32C_WITH_RUNTIME_CHECK)
+
+/*
+ * Use Intel SSE 4.2 or ARMv8 instructions, but perform a runtime check first
+ * to check that they are available.
+ */
+#define COMP_CRC32C(crc, data, len) \
+ ((crc) = pg_comp_crc32c((crc), (data), (len)))
+#define FIN_CRC32C(crc) ((crc) ^= 0xFFFFFFFF)
+
+extern pg_crc32c pg_comp_crc32c_sb8(pg_crc32c crc, const void *data, size_t len);
+extern pg_crc32c (*pg_comp_crc32c) (pg_crc32c crc, const void *data, size_t len);
+
+#ifdef USE_SSE42_CRC32C_WITH_RUNTIME_CHECK
+extern pg_crc32c pg_comp_crc32c_sse42(pg_crc32c crc, const void *data, size_t len);
+#endif
+#ifdef USE_ARMV8_CRC32C_WITH_RUNTIME_CHECK
+extern pg_crc32c pg_comp_crc32c_armv8(pg_crc32c crc, const void *data, size_t len);
+#endif
+
+#else
+/*
+ * Use slicing-by-8 algorithm.
+ *
+ * On big-endian systems, the intermediate value is kept in reverse byte
+ * order, to avoid byte-swapping during the calculation. FIN_CRC32C reverses
+ * the bytes to the final order.
+ */
+#define COMP_CRC32C(crc, data, len) \
+ ((crc) = pg_comp_crc32c_sb8((crc), (data), (len)))
+#ifdef WORDS_BIGENDIAN
+#define FIN_CRC32C(crc) ((crc) = pg_bswap32(crc) ^ 0xFFFFFFFF)
+#else
+#define FIN_CRC32C(crc) ((crc) ^= 0xFFFFFFFF)
+#endif
+
+extern pg_crc32c pg_comp_crc32c_sb8(pg_crc32c crc, const void *data, size_t len);
+
+#endif
+
+#endif /* PG_CRC32C_H */
diff --git a/pgsql/include/server/port/pg_iovec.h b/pgsql/include/server/port/pg_iovec.h
new file mode 100644
index 0000000000000000000000000000000000000000..689799c42580150eeb85bc7a5130d85768f89bc2
--- /dev/null
+++ b/pgsql/include/server/port/pg_iovec.h
@@ -0,0 +1,55 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_iovec.h
+ * Header for vectored I/O functions, to use in place of .
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/pg_iovec.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_IOVEC_H
+#define PG_IOVEC_H
+
+#ifndef WIN32
+
+#include
+#include
+
+#else
+
+/* POSIX requires at least 16 as a maximum iovcnt. */
+#define IOV_MAX 16
+
+/* Define our own POSIX-compatible iovec struct. */
+struct iovec
+{
+ void *iov_base;
+ size_t iov_len;
+};
+
+#endif
+
+/* Define a reasonable maximum that is safe to use on the stack. */
+#define PG_IOV_MAX Min(IOV_MAX, 32)
+
+/*
+ * Note that pg_preadv and pg_pwritev have a pg_ prefix as a warning that the
+ * Windows implementations have the side-effect of changing the file position.
+ */
+
+#if HAVE_DECL_PREADV
+#define pg_preadv preadv
+#else
+extern ssize_t pg_preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset);
+#endif
+
+#if HAVE_DECL_PWRITEV
+#define pg_pwritev pwritev
+#else
+extern ssize_t pg_pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset);
+#endif
+
+#endif /* PG_IOVEC_H */
diff --git a/pgsql/include/server/port/pg_lfind.h b/pgsql/include/server/port/pg_lfind.h
new file mode 100644
index 0000000000000000000000000000000000000000..59aa8245edc33572f47cf9593a4e5c4047200b9a
--- /dev/null
+++ b/pgsql/include/server/port/pg_lfind.h
@@ -0,0 +1,180 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_lfind.h
+ * Optimized linear search routines using SIMD intrinsics where
+ * available.
+ *
+ * Copyright (c) 2022-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/port/pg_lfind.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_LFIND_H
+#define PG_LFIND_H
+
+#include "port/simd.h"
+
+/*
+ * pg_lfind8
+ *
+ * Return true if there is an element in 'base' that equals 'key', otherwise
+ * return false.
+ */
+static inline bool
+pg_lfind8(uint8 key, uint8 *base, uint32 nelem)
+{
+ uint32 i;
+
+ /* round down to multiple of vector length */
+ uint32 tail_idx = nelem & ~(sizeof(Vector8) - 1);
+ Vector8 chunk;
+
+ for (i = 0; i < tail_idx; i += sizeof(Vector8))
+ {
+ vector8_load(&chunk, &base[i]);
+ if (vector8_has(chunk, key))
+ return true;
+ }
+
+ /* Process the remaining elements one at a time. */
+ for (; i < nelem; i++)
+ {
+ if (key == base[i])
+ return true;
+ }
+
+ return false;
+}
+
+/*
+ * pg_lfind8_le
+ *
+ * Return true if there is an element in 'base' that is less than or equal to
+ * 'key', otherwise return false.
+ */
+static inline bool
+pg_lfind8_le(uint8 key, uint8 *base, uint32 nelem)
+{
+ uint32 i;
+
+ /* round down to multiple of vector length */
+ uint32 tail_idx = nelem & ~(sizeof(Vector8) - 1);
+ Vector8 chunk;
+
+ for (i = 0; i < tail_idx; i += sizeof(Vector8))
+ {
+ vector8_load(&chunk, &base[i]);
+ if (vector8_has_le(chunk, key))
+ return true;
+ }
+
+ /* Process the remaining elements one at a time. */
+ for (; i < nelem; i++)
+ {
+ if (base[i] <= key)
+ return true;
+ }
+
+ return false;
+}
+
+/*
+ * pg_lfind32
+ *
+ * Return true if there is an element in 'base' that equals 'key', otherwise
+ * return false.
+ */
+static inline bool
+pg_lfind32(uint32 key, uint32 *base, uint32 nelem)
+{
+ uint32 i = 0;
+
+#ifndef USE_NO_SIMD
+
+ /*
+ * For better instruction-level parallelism, each loop iteration operates
+ * on a block of four registers. Testing for SSE2 has showed this is ~40%
+ * faster than using a block of two registers.
+ */
+ const Vector32 keys = vector32_broadcast(key); /* load copies of key */
+ const uint32 nelem_per_vector = sizeof(Vector32) / sizeof(uint32);
+ const uint32 nelem_per_iteration = 4 * nelem_per_vector;
+
+ /* round down to multiple of elements per iteration */
+ const uint32 tail_idx = nelem & ~(nelem_per_iteration - 1);
+
+#if defined(USE_ASSERT_CHECKING)
+ bool assert_result = false;
+
+ /* pre-compute the result for assert checking */
+ for (i = 0; i < nelem; i++)
+ {
+ if (key == base[i])
+ {
+ assert_result = true;
+ break;
+ }
+ }
+#endif
+
+ for (i = 0; i < tail_idx; i += nelem_per_iteration)
+ {
+ Vector32 vals1,
+ vals2,
+ vals3,
+ vals4,
+ result1,
+ result2,
+ result3,
+ result4,
+ tmp1,
+ tmp2,
+ result;
+
+ /* load the next block into 4 registers */
+ vector32_load(&vals1, &base[i]);
+ vector32_load(&vals2, &base[i + nelem_per_vector]);
+ vector32_load(&vals3, &base[i + nelem_per_vector * 2]);
+ vector32_load(&vals4, &base[i + nelem_per_vector * 3]);
+
+ /* compare each value to the key */
+ result1 = vector32_eq(keys, vals1);
+ result2 = vector32_eq(keys, vals2);
+ result3 = vector32_eq(keys, vals3);
+ result4 = vector32_eq(keys, vals4);
+
+ /* combine the results into a single variable */
+ tmp1 = vector32_or(result1, result2);
+ tmp2 = vector32_or(result3, result4);
+ result = vector32_or(tmp1, tmp2);
+
+ /* see if there was a match */
+ if (vector32_is_highbit_set(result))
+ {
+ Assert(assert_result == true);
+ return true;
+ }
+ }
+#endif /* ! USE_NO_SIMD */
+
+ /* Process the remaining elements one at a time. */
+ for (; i < nelem; i++)
+ {
+ if (key == base[i])
+ {
+#ifndef USE_NO_SIMD
+ Assert(assert_result == true);
+#endif
+ return true;
+ }
+ }
+
+#ifndef USE_NO_SIMD
+ Assert(assert_result == false);
+#endif
+ return false;
+}
+
+#endif /* PG_LFIND_H */
diff --git a/pgsql/include/server/port/pg_pthread.h b/pgsql/include/server/port/pg_pthread.h
new file mode 100644
index 0000000000000000000000000000000000000000..d102ce9d6f33e10deddf9895daf5fd81f3d79fd0
--- /dev/null
+++ b/pgsql/include/server/port/pg_pthread.h
@@ -0,0 +1,41 @@
+/*-------------------------------------------------------------------------
+ *
+ * Declarations for missing POSIX thread components.
+ *
+ * Currently this supplies an implementation of pthread_barrier_t for the
+ * benefit of macOS, which lacks it. These declarations are not in port.h,
+ * because that'd require to be included by every translation
+ * unit.
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef PG_PTHREAD_H
+#define PG_PTHREAD_H
+
+#include
+
+#ifndef HAVE_PTHREAD_BARRIER_WAIT
+
+#ifndef PTHREAD_BARRIER_SERIAL_THREAD
+#define PTHREAD_BARRIER_SERIAL_THREAD (-1)
+#endif
+
+typedef struct pg_pthread_barrier
+{
+ bool sense; /* we only need a one bit phase */
+ int count; /* number of threads expected */
+ int arrived; /* number of threads that have arrived */
+ pthread_mutex_t mutex;
+ pthread_cond_t cond;
+} pthread_barrier_t;
+
+extern int pthread_barrier_init(pthread_barrier_t *barrier,
+ const void *attr,
+ int count);
+extern int pthread_barrier_wait(pthread_barrier_t *barrier);
+extern int pthread_barrier_destroy(pthread_barrier_t *barrier);
+
+#endif
+
+#endif
diff --git a/pgsql/include/server/port/simd.h b/pgsql/include/server/port/simd.h
new file mode 100644
index 0000000000000000000000000000000000000000..1fa6c3bc6c49687c59ffa1a3471a22e4fadb4443
--- /dev/null
+++ b/pgsql/include/server/port/simd.h
@@ -0,0 +1,375 @@
+/*-------------------------------------------------------------------------
+ *
+ * simd.h
+ * Support for platform-specific vector operations.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/simd.h
+ *
+ * NOTES
+ * - VectorN in this file refers to a register where the element operands
+ * are N bits wide. The vector width is platform-specific, so users that care
+ * about that will need to inspect "sizeof(VectorN)".
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SIMD_H
+#define SIMD_H
+
+#if (defined(__x86_64__) || defined(_M_AMD64))
+/*
+ * SSE2 instructions are part of the spec for the 64-bit x86 ISA. We assume
+ * that compilers targeting this architecture understand SSE2 intrinsics.
+ *
+ * We use emmintrin.h rather than the comprehensive header immintrin.h in
+ * order to exclude extensions beyond SSE2. This is because MSVC, at least,
+ * will allow the use of intrinsics that haven't been enabled at compile
+ * time.
+ */
+#include
+#define USE_SSE2
+typedef __m128i Vector8;
+typedef __m128i Vector32;
+
+#elif defined(__aarch64__) && defined(__ARM_NEON)
+/*
+ * We use the Neon instructions if the compiler provides access to them (as
+ * indicated by __ARM_NEON) and we are on aarch64. While Neon support is
+ * technically optional for aarch64, it appears that all available 64-bit
+ * hardware does have it. Neon exists in some 32-bit hardware too, but we
+ * could not realistically use it there without a run-time check, which seems
+ * not worth the trouble for now.
+ */
+#include
+#define USE_NEON
+typedef uint8x16_t Vector8;
+typedef uint32x4_t Vector32;
+
+#else
+/*
+ * If no SIMD instructions are available, we can in some cases emulate vector
+ * operations using bitwise operations on unsigned integers. Note that many
+ * of the functions in this file presently do not have non-SIMD
+ * implementations. In particular, none of the functions involving Vector32
+ * are implemented without SIMD since it's likely not worthwhile to represent
+ * two 32-bit integers using a uint64.
+ */
+#define USE_NO_SIMD
+typedef uint64 Vector8;
+#endif
+
+/* load/store operations */
+static inline void vector8_load(Vector8 *v, const uint8 *s);
+#ifndef USE_NO_SIMD
+static inline void vector32_load(Vector32 *v, const uint32 *s);
+#endif
+
+/* assignment operations */
+static inline Vector8 vector8_broadcast(const uint8 c);
+#ifndef USE_NO_SIMD
+static inline Vector32 vector32_broadcast(const uint32 c);
+#endif
+
+/* element-wise comparisons to a scalar */
+static inline bool vector8_has(const Vector8 v, const uint8 c);
+static inline bool vector8_has_zero(const Vector8 v);
+static inline bool vector8_has_le(const Vector8 v, const uint8 c);
+static inline bool vector8_is_highbit_set(const Vector8 v);
+#ifndef USE_NO_SIMD
+static inline bool vector32_is_highbit_set(const Vector32 v);
+#endif
+
+/* arithmetic operations */
+static inline Vector8 vector8_or(const Vector8 v1, const Vector8 v2);
+#ifndef USE_NO_SIMD
+static inline Vector32 vector32_or(const Vector32 v1, const Vector32 v2);
+static inline Vector8 vector8_ssub(const Vector8 v1, const Vector8 v2);
+#endif
+
+/*
+ * comparisons between vectors
+ *
+ * Note: These return a vector rather than boolean, which is why we don't
+ * have non-SIMD implementations.
+ */
+#ifndef USE_NO_SIMD
+static inline Vector8 vector8_eq(const Vector8 v1, const Vector8 v2);
+static inline Vector32 vector32_eq(const Vector32 v1, const Vector32 v2);
+#endif
+
+/*
+ * Load a chunk of memory into the given vector.
+ */
+static inline void
+vector8_load(Vector8 *v, const uint8 *s)
+{
+#if defined(USE_SSE2)
+ *v = _mm_loadu_si128((const __m128i *) s);
+#elif defined(USE_NEON)
+ *v = vld1q_u8(s);
+#else
+ memcpy(v, s, sizeof(Vector8));
+#endif
+}
+
+#ifndef USE_NO_SIMD
+static inline void
+vector32_load(Vector32 *v, const uint32 *s)
+{
+#ifdef USE_SSE2
+ *v = _mm_loadu_si128((const __m128i *) s);
+#elif defined(USE_NEON)
+ *v = vld1q_u32(s);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+/*
+ * Create a vector with all elements set to the same value.
+ */
+static inline Vector8
+vector8_broadcast(const uint8 c)
+{
+#if defined(USE_SSE2)
+ return _mm_set1_epi8(c);
+#elif defined(USE_NEON)
+ return vdupq_n_u8(c);
+#else
+ return ~UINT64CONST(0) / 0xFF * c;
+#endif
+}
+
+#ifndef USE_NO_SIMD
+static inline Vector32
+vector32_broadcast(const uint32 c)
+{
+#ifdef USE_SSE2
+ return _mm_set1_epi32(c);
+#elif defined(USE_NEON)
+ return vdupq_n_u32(c);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+/*
+ * Return true if any elements in the vector are equal to the given scalar.
+ */
+static inline bool
+vector8_has(const Vector8 v, const uint8 c)
+{
+ bool result;
+
+ /* pre-compute the result for assert checking */
+#ifdef USE_ASSERT_CHECKING
+ bool assert_result = false;
+
+ for (Size i = 0; i < sizeof(Vector8); i++)
+ {
+ if (((const uint8 *) &v)[i] == c)
+ {
+ assert_result = true;
+ break;
+ }
+ }
+#endif /* USE_ASSERT_CHECKING */
+
+#if defined(USE_NO_SIMD)
+ /* any bytes in v equal to c will evaluate to zero via XOR */
+ result = vector8_has_zero(v ^ vector8_broadcast(c));
+#else
+ result = vector8_is_highbit_set(vector8_eq(v, vector8_broadcast(c)));
+#endif
+
+ Assert(assert_result == result);
+ return result;
+}
+
+/*
+ * Convenience function equivalent to vector8_has(v, 0)
+ */
+static inline bool
+vector8_has_zero(const Vector8 v)
+{
+#if defined(USE_NO_SIMD)
+ /*
+ * We cannot call vector8_has() here, because that would lead to a
+ * circular definition.
+ */
+ return vector8_has_le(v, 0);
+#else
+ return vector8_has(v, 0);
+#endif
+}
+
+/*
+ * Return true if any elements in the vector are less than or equal to the
+ * given scalar.
+ */
+static inline bool
+vector8_has_le(const Vector8 v, const uint8 c)
+{
+ bool result = false;
+
+ /* pre-compute the result for assert checking */
+#ifdef USE_ASSERT_CHECKING
+ bool assert_result = false;
+
+ for (Size i = 0; i < sizeof(Vector8); i++)
+ {
+ if (((const uint8 *) &v)[i] <= c)
+ {
+ assert_result = true;
+ break;
+ }
+ }
+#endif /* USE_ASSERT_CHECKING */
+
+#if defined(USE_NO_SIMD)
+
+ /*
+ * To find bytes <= c, we can use bitwise operations to find bytes < c+1,
+ * but it only works if c+1 <= 128 and if the highest bit in v is not set.
+ * Adapted from
+ * https://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord
+ */
+ if ((int64) v >= 0 && c < 0x80)
+ result = (v - vector8_broadcast(c + 1)) & ~v & vector8_broadcast(0x80);
+ else
+ {
+ /* one byte at a time */
+ for (Size i = 0; i < sizeof(Vector8); i++)
+ {
+ if (((const uint8 *) &v)[i] <= c)
+ {
+ result = true;
+ break;
+ }
+ }
+ }
+#else
+
+ /*
+ * Use saturating subtraction to find bytes <= c, which will present as
+ * NUL bytes. This approach is a workaround for the lack of unsigned
+ * comparison instructions on some architectures.
+ */
+ result = vector8_has_zero(vector8_ssub(v, vector8_broadcast(c)));
+#endif
+
+ Assert(assert_result == result);
+ return result;
+}
+
+/*
+ * Return true if the high bit of any element is set
+ */
+static inline bool
+vector8_is_highbit_set(const Vector8 v)
+{
+#ifdef USE_SSE2
+ return _mm_movemask_epi8(v) != 0;
+#elif defined(USE_NEON)
+ return vmaxvq_u8(v) > 0x7F;
+#else
+ return v & vector8_broadcast(0x80);
+#endif
+}
+
+/*
+ * Exactly like vector8_is_highbit_set except for the input type, so it
+ * looks at each byte separately.
+ *
+ * XXX x86 uses the same underlying type for 8-bit, 16-bit, and 32-bit
+ * integer elements, but Arm does not, hence the need for a separate
+ * function. We could instead adopt the behavior of Arm's vmaxvq_u32(), i.e.
+ * check each 32-bit element, but that would require an additional mask
+ * operation on x86.
+ */
+#ifndef USE_NO_SIMD
+static inline bool
+vector32_is_highbit_set(const Vector32 v)
+{
+#if defined(USE_NEON)
+ return vector8_is_highbit_set((Vector8) v);
+#else
+ return vector8_is_highbit_set(v);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+/*
+ * Return the bitwise OR of the inputs
+ */
+static inline Vector8
+vector8_or(const Vector8 v1, const Vector8 v2)
+{
+#ifdef USE_SSE2
+ return _mm_or_si128(v1, v2);
+#elif defined(USE_NEON)
+ return vorrq_u8(v1, v2);
+#else
+ return v1 | v2;
+#endif
+}
+
+#ifndef USE_NO_SIMD
+static inline Vector32
+vector32_or(const Vector32 v1, const Vector32 v2)
+{
+#ifdef USE_SSE2
+ return _mm_or_si128(v1, v2);
+#elif defined(USE_NEON)
+ return vorrq_u32(v1, v2);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+/*
+ * Return the result of subtracting the respective elements of the input
+ * vectors using saturation (i.e., if the operation would yield a value less
+ * than zero, zero is returned instead). For more information on saturation
+ * arithmetic, see https://en.wikipedia.org/wiki/Saturation_arithmetic
+ */
+#ifndef USE_NO_SIMD
+static inline Vector8
+vector8_ssub(const Vector8 v1, const Vector8 v2)
+{
+#ifdef USE_SSE2
+ return _mm_subs_epu8(v1, v2);
+#elif defined(USE_NEON)
+ return vqsubq_u8(v1, v2);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+/*
+ * Return a vector with all bits set in each lane where the corresponding
+ * lanes in the inputs are equal.
+ */
+#ifndef USE_NO_SIMD
+static inline Vector8
+vector8_eq(const Vector8 v1, const Vector8 v2)
+{
+#ifdef USE_SSE2
+ return _mm_cmpeq_epi8(v1, v2);
+#elif defined(USE_NEON)
+ return vceqq_u8(v1, v2);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+#ifndef USE_NO_SIMD
+static inline Vector32
+vector32_eq(const Vector32 v1, const Vector32 v2)
+{
+#ifdef USE_SSE2
+ return _mm_cmpeq_epi32(v1, v2);
+#elif defined(USE_NEON)
+ return vceqq_u32(v1, v2);
+#endif
+}
+#endif /* ! USE_NO_SIMD */
+
+#endif /* SIMD_H */
diff --git a/pgsql/include/server/port/solaris.h b/pgsql/include/server/port/solaris.h
new file mode 100644
index 0000000000000000000000000000000000000000..e63a3bd824d6dc6fa2d8cc35029ba76b61a03370
--- /dev/null
+++ b/pgsql/include/server/port/solaris.h
@@ -0,0 +1,26 @@
+/* src/include/port/solaris.h */
+
+/*
+ * Sort this out for all operating systems some time. The __xxx
+ * symbols are defined on both GCC and Solaris CC, although GCC
+ * doesn't document them. The __xxx__ symbols are only on GCC.
+ */
+#if defined(__i386) && !defined(__i386__)
+#define __i386__
+#endif
+
+#if defined(__amd64) && !defined(__amd64__)
+#define __amd64__
+#endif
+
+#if defined(__x86_64) && !defined(__x86_64__)
+#define __x86_64__
+#endif
+
+#if defined(__sparc) && !defined(__sparc__)
+#define __sparc__
+#endif
+
+#if defined(__i386__)
+#include
+#endif
diff --git a/pgsql/include/server/port/win32.h b/pgsql/include/server/port/win32.h
new file mode 100644
index 0000000000000000000000000000000000000000..d6c13d0bb8f08bb88ca23bf4df87b85242ab0338
--- /dev/null
+++ b/pgsql/include/server/port/win32.h
@@ -0,0 +1,59 @@
+/* src/include/port/win32.h */
+
+/*
+ * We always rely on the WIN32 macro being set by our build system,
+ * but _WIN32 is the compiler pre-defined macro. So make sure we define
+ * WIN32 whenever _WIN32 is set, to facilitate standalone building.
+ */
+#if defined(_WIN32) && !defined(WIN32)
+#define WIN32
+#endif
+
+/*
+ * Make sure _WIN32_WINNT has the minimum required value.
+ * Leave a higher value in place. The minimum requirement is Windows 10.
+ */
+#ifdef _WIN32_WINNT
+#undef _WIN32_WINNT
+#endif
+
+#define _WIN32_WINNT 0x0A00
+
+/*
+ * We need to prevent from defining a symbol conflicting with
+ * our errcode() function. Since it's likely to get included by standard
+ * system headers, pre-emptively include it now.
+ */
+#if defined(_MSC_VER) || defined(HAVE_CRTDEFS_H)
+#define errcode __msvc_errcode
+#include
+#undef errcode
+#endif
+
+/*
+ * defines for dynamic linking on Win32 platform
+ */
+
+/*
+ * Variables declared in the core backend and referenced by loadable
+ * modules need to be marked "dllimport" in the core build, but
+ * "dllexport" when the declaration is read in a loadable module.
+ * No special markings should be used when compiling frontend code.
+ */
+#ifndef FRONTEND
+#ifdef BUILDING_DLL
+#define PGDLLIMPORT __declspec (dllexport)
+#else
+#define PGDLLIMPORT __declspec (dllimport)
+#endif
+#endif
+
+/*
+ * Functions exported by a loadable module must be marked "dllexport".
+ *
+ * While mingw would otherwise fall back to
+ * __attribute__((visibility("default"))), that appears to only work as long
+ * as no symbols are declared with __declspec(dllexport). But we can end up
+ * with some, e.g. plpython's Py_Init.
+ */
+#define PGDLLEXPORT __declspec (dllexport)
diff --git a/pgsql/include/server/port/win32/arpa/inet.h b/pgsql/include/server/port/win32/arpa/inet.h
new file mode 100644
index 0000000000000000000000000000000000000000..ad1803179c7aea4717338ba920d26b3432d89eef
--- /dev/null
+++ b/pgsql/include/server/port/win32/arpa/inet.h
@@ -0,0 +1,3 @@
+/* src/include/port/win32/arpa/inet.h */
+
+#include
diff --git a/pgsql/include/server/port/win32/dlfcn.h b/pgsql/include/server/port/win32/dlfcn.h
new file mode 100644
index 0000000000000000000000000000000000000000..b6e43c091d620d0750f11de48f451ac98c117a2f
--- /dev/null
+++ b/pgsql/include/server/port/win32/dlfcn.h
@@ -0,0 +1 @@
+/* src/include/port/win32/dlfcn.h */
diff --git a/pgsql/include/server/port/win32/grp.h b/pgsql/include/server/port/win32/grp.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b4f21310e9ebeb9b7148ecb7c53dfd0e9811141
--- /dev/null
+++ b/pgsql/include/server/port/win32/grp.h
@@ -0,0 +1 @@
+/* src/include/port/win32/grp.h */
diff --git a/pgsql/include/server/port/win32/netdb.h b/pgsql/include/server/port/win32/netdb.h
new file mode 100644
index 0000000000000000000000000000000000000000..9ed13e457b8cdbdc2ee8b3f2886332559b4c1a74
--- /dev/null
+++ b/pgsql/include/server/port/win32/netdb.h
@@ -0,0 +1,7 @@
+/* src/include/port/win32/netdb.h */
+#ifndef WIN32_NETDB_H
+#define WIN32_NETDB_H
+
+#include
+
+#endif
diff --git a/pgsql/include/server/port/win32/netinet/in.h b/pgsql/include/server/port/win32/netinet/in.h
new file mode 100644
index 0000000000000000000000000000000000000000..a4e22f89f4961ad53b9b720813cbce8d6e8a1677
--- /dev/null
+++ b/pgsql/include/server/port/win32/netinet/in.h
@@ -0,0 +1,3 @@
+/* src/include/port/win32/netinet/in.h */
+
+#include
diff --git a/pgsql/include/server/port/win32/netinet/tcp.h b/pgsql/include/server/port/win32/netinet/tcp.h
new file mode 100644
index 0000000000000000000000000000000000000000..1d377b6adc242346e7fd1309558afb49ee1c8993
--- /dev/null
+++ b/pgsql/include/server/port/win32/netinet/tcp.h
@@ -0,0 +1,7 @@
+/* src/include/port/win32/netinet/tcp.h */
+#ifndef WIN32_NETINET_TCP_H
+#define WIN32_NETINET_TCP_H
+
+#include
+
+#endif
diff --git a/pgsql/include/server/port/win32/pwd.h b/pgsql/include/server/port/win32/pwd.h
new file mode 100644
index 0000000000000000000000000000000000000000..b8c7178fc06c082f4c41c11f84db94a0f24233be
--- /dev/null
+++ b/pgsql/include/server/port/win32/pwd.h
@@ -0,0 +1,3 @@
+/*
+ * src/include/port/win32/pwd.h
+ */
diff --git a/pgsql/include/server/port/win32/sys/resource.h b/pgsql/include/server/port/win32/sys/resource.h
new file mode 100644
index 0000000000000000000000000000000000000000..a14feeb5844636084b289ba6b80e421e45dd7794
--- /dev/null
+++ b/pgsql/include/server/port/win32/sys/resource.h
@@ -0,0 +1,20 @@
+/*
+ * Replacement for for Windows.
+ */
+#ifndef WIN32_SYS_RESOURCE_H
+#define WIN32_SYS_RESOURCE_H
+
+#include /* for struct timeval */
+
+#define RUSAGE_SELF 0
+#define RUSAGE_CHILDREN (-1)
+
+struct rusage
+{
+ struct timeval ru_utime; /* user time used */
+ struct timeval ru_stime; /* system time used */
+};
+
+extern int getrusage(int who, struct rusage *rusage);
+
+#endif /* WIN32_SYS_RESOURCE_H */
diff --git a/pgsql/include/server/port/win32/sys/select.h b/pgsql/include/server/port/win32/sys/select.h
new file mode 100644
index 0000000000000000000000000000000000000000..f8a877accd67c97820152dab7e152f516de53d80
--- /dev/null
+++ b/pgsql/include/server/port/win32/sys/select.h
@@ -0,0 +1,3 @@
+/*
+ * src/include/port/win32/sys/select.h
+ */
diff --git a/pgsql/include/server/port/win32/sys/socket.h b/pgsql/include/server/port/win32/sys/socket.h
new file mode 100644
index 0000000000000000000000000000000000000000..f2b475df5e5e0122f98d8eb009d8e2445c5af4fd
--- /dev/null
+++ b/pgsql/include/server/port/win32/sys/socket.h
@@ -0,0 +1,34 @@
+/*
+ * src/include/port/win32/sys/socket.h
+ */
+#ifndef WIN32_SYS_SOCKET_H
+#define WIN32_SYS_SOCKET_H
+
+/*
+ * Unfortunately, of VC++ also defines ERROR.
+ * To avoid the conflict, we include here and undefine ERROR
+ * immediately.
+ *
+ * Note: Don't include directly. It causes compile errors.
+ */
+#include
+#include
+#include
+
+#undef ERROR
+#undef small
+
+/* Restore old ERROR value */
+#ifdef PGERROR
+#define ERROR PGERROR
+#endif
+
+/*
+ * We don't use the Windows gai_strerror[A] function because it is not
+ * thread-safe. We define our own in src/port/win32gai_strerror.c.
+ */
+#undef gai_strerror
+
+extern const char *gai_strerror(int ecode);
+
+#endif /* WIN32_SYS_SOCKET_H */
diff --git a/pgsql/include/server/port/win32/sys/un.h b/pgsql/include/server/port/win32/sys/un.h
new file mode 100644
index 0000000000000000000000000000000000000000..4fc13a23fd1303fef3d74137d206ebd1cee29e38
--- /dev/null
+++ b/pgsql/include/server/port/win32/sys/un.h
@@ -0,0 +1,17 @@
+/*
+ * src/include/port/win32/sys/un.h
+ */
+#ifndef WIN32_SYS_UN_H
+#define WIN32_SYS_UN_H
+
+/*
+ * Windows defines this structure in , but not all tool chains have
+ * the header yet, so we define it here for now.
+ */
+struct sockaddr_un
+{
+ unsigned short sun_family;
+ char sun_path[108];
+};
+
+#endif
diff --git a/pgsql/include/server/port/win32/sys/wait.h b/pgsql/include/server/port/win32/sys/wait.h
new file mode 100644
index 0000000000000000000000000000000000000000..eaeb5661c98fa1f0b0e3a144dbcecb18013d8aa9
--- /dev/null
+++ b/pgsql/include/server/port/win32/sys/wait.h
@@ -0,0 +1,3 @@
+/*
+ * src/include/port/win32/sys/wait.h
+ */
diff --git a/pgsql/include/server/port/win32_msvc/dirent.h b/pgsql/include/server/port/win32_msvc/dirent.h
new file mode 100644
index 0000000000000000000000000000000000000000..62799db0014169a8125119771950896a918f8649
--- /dev/null
+++ b/pgsql/include/server/port/win32_msvc/dirent.h
@@ -0,0 +1,34 @@
+/*
+ * Headers for port/dirent.c, win32 native implementation of dirent functions
+ *
+ * src/include/port/win32_msvc/dirent.h
+ */
+
+#ifndef _WIN32VC_DIRENT_H
+#define _WIN32VC_DIRENT_H
+struct dirent
+{
+ long d_ino;
+ unsigned short d_reclen;
+ unsigned char d_type;
+ unsigned short d_namlen;
+ char d_name[MAX_PATH];
+};
+
+typedef struct DIR DIR;
+
+DIR *opendir(const char *);
+struct dirent *readdir(DIR *);
+int closedir(DIR *);
+
+/* File types for 'd_type'. */
+#define DT_UNKNOWN 0
+#define DT_FIFO 1
+#define DT_CHR 2
+#define DT_DIR 4
+#define DT_BLK 6
+#define DT_REG 8
+#define DT_LNK 10
+#define DT_SOCK 12
+#define DT_WHT 14
+#endif
diff --git a/pgsql/include/server/port/win32_msvc/sys/file.h b/pgsql/include/server/port/win32_msvc/sys/file.h
new file mode 100644
index 0000000000000000000000000000000000000000..76be3e77740ef0f057ea5b4cf9343e1b74f235a5
--- /dev/null
+++ b/pgsql/include/server/port/win32_msvc/sys/file.h
@@ -0,0 +1 @@
+/* src/include/port/win32_msvc/sys/file.h */
diff --git a/pgsql/include/server/port/win32_msvc/sys/param.h b/pgsql/include/server/port/win32_msvc/sys/param.h
new file mode 100644
index 0000000000000000000000000000000000000000..160df3b25e1af839b43736889f1d976c4a95db4f
--- /dev/null
+++ b/pgsql/include/server/port/win32_msvc/sys/param.h
@@ -0,0 +1 @@
+/* src/include/port/win32_msvc/sys/param.h */
diff --git a/pgsql/include/server/port/win32_msvc/sys/time.h b/pgsql/include/server/port/win32_msvc/sys/time.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d943ecc6fa4de213ad981dc74ace6c986d805e7
--- /dev/null
+++ b/pgsql/include/server/port/win32_msvc/sys/time.h
@@ -0,0 +1 @@
+/* src/include/port/win32_msvc/sys/time.h */
diff --git a/pgsql/include/server/port/win32_msvc/unistd.h b/pgsql/include/server/port/win32_msvc/unistd.h
new file mode 100644
index 0000000000000000000000000000000000000000..b7795ba03c4ed146f0d87445d6d3da878aabf37d
--- /dev/null
+++ b/pgsql/include/server/port/win32_msvc/unistd.h
@@ -0,0 +1,9 @@
+/* src/include/port/win32_msvc/unistd.h */
+
+/*
+ * MSVC does not define these, nor does _fileno(stdin) etc reliably work
+ * (returns -1 if stdin/out/err are closed).
+ */
+#define STDIN_FILENO 0
+#define STDOUT_FILENO 1
+#define STDERR_FILENO 2
diff --git a/pgsql/include/server/port/win32_msvc/utime.h b/pgsql/include/server/port/win32_msvc/utime.h
new file mode 100644
index 0000000000000000000000000000000000000000..c78e79c33d34fa6ea12287ec74e5194bf705491e
--- /dev/null
+++ b/pgsql/include/server/port/win32_msvc/utime.h
@@ -0,0 +1,3 @@
+/* src/include/port/win32_msvc/utime.h */
+
+#include /* for non-unicode version */
diff --git a/pgsql/include/server/port/win32_port.h b/pgsql/include/server/port/win32_port.h
new file mode 100644
index 0000000000000000000000000000000000000000..b957d5c598149d806d2b3d46ef719b75c61f24ee
--- /dev/null
+++ b/pgsql/include/server/port/win32_port.h
@@ -0,0 +1,594 @@
+/*-------------------------------------------------------------------------
+ *
+ * win32_port.h
+ * Windows-specific compatibility stuff.
+ *
+ * Note this is read in MinGW as well as native Windows builds,
+ * but not in Cygwin builds.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/win32_port.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_WIN32_PORT_H
+#define PG_WIN32_PORT_H
+
+/*
+ * Always build with SSPI support. Keep it as a #define in case
+ * we want a switch to disable it sometime in the future.
+ */
+#define ENABLE_SSPI 1
+
+/* undefine and redefine after #include */
+#undef mkdir
+
+#undef ERROR
+
+/*
+ * VS2013 and later issue warnings about using the old Winsock API,
+ * which we don't really want to hear about.
+ */
+#ifdef _MSC_VER
+#define _WINSOCK_DEPRECATED_NO_WARNINGS
+#endif
+
+/*
+ * The MinGW64 headers choke if this is already defined - they
+ * define it themselves.
+ */
+#if !defined(__MINGW64_VERSION_MAJOR) || defined(_MSC_VER)
+#define _WINSOCKAPI_
+#endif
+
+/*
+ * windows.h includes a lot of other headers, slowing down compilation
+ * significantly. WIN32_LEAN_AND_MEAN reduces that a bit. It'd be better to
+ * remove the include of windows.h (as well as indirect inclusions of it) from
+ * such a central place, but until then...
+ *
+ * To be able to include ntstatus.h tell windows.h to not declare NTSTATUS by
+ * temporarily defining UMDF_USING_NTSTATUS, otherwise we'll get warning about
+ * macro redefinitions, as windows.h also defines NTSTATUS (yuck). That in
+ * turn requires including ntstatus.h, winternl.h to get common symbols.
+ */
+#define WIN32_LEAN_AND_MEAN
+#define UMDF_USING_NTSTATUS
+
+#include
+#include
+#include
+#include
+#include
+
+#undef small
+#include
+#include
+#include
+#undef near
+
+/* needed before sys/stat hacking below: */
+#define fstat microsoft_native_fstat
+#define stat microsoft_native_stat
+#include
+#undef fstat
+#undef stat
+
+/* Must be here to avoid conflicting with prototype in windows.h */
+#define mkdir(a,b) mkdir(a)
+
+#define ftruncate(a,b) chsize(a,b)
+
+/* Windows doesn't have fsync() as such, use _commit() */
+#define fsync(fd) _commit(fd)
+
+/*
+ * For historical reasons, we allow setting wal_sync_method to
+ * fsync_writethrough on Windows, even though it's really identical to fsync
+ * (both code paths wind up at _commit()).
+ */
+#define HAVE_FSYNC_WRITETHROUGH
+#define FSYNC_WRITETHROUGH_IS_FSYNC
+
+#define USES_WINSOCK
+
+/*
+ * IPC defines
+ */
+#undef HAVE_UNION_SEMUN
+#define HAVE_UNION_SEMUN 1
+
+#define IPC_RMID 256
+#define IPC_CREAT 512
+#define IPC_EXCL 1024
+#define IPC_PRIVATE 234564
+#define IPC_NOWAIT 2048
+#define IPC_STAT 4096
+
+#define EACCESS 2048
+#ifndef EIDRM
+#define EIDRM 4096
+#endif
+
+#define SETALL 8192
+#define GETNCNT 16384
+#define GETVAL 65536
+#define SETVAL 131072
+#define GETPID 262144
+
+
+/*
+ * Signal stuff
+ *
+ * For WIN32, there is no wait() call so there are no wait() macros
+ * to interpret the return value of system(). Instead, system()
+ * return values < 0x100 are used for exit() termination, and higher
+ * values are used to indicate non-exit() termination, which is
+ * similar to a unix-style signal exit (think SIGSEGV ==
+ * STATUS_ACCESS_VIOLATION). Return values are broken up into groups:
+ *
+ * https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/using-ntstatus-values
+ *
+ * NT_SUCCESS 0 - 0x3FFFFFFF
+ * NT_INFORMATION 0x40000000 - 0x7FFFFFFF
+ * NT_WARNING 0x80000000 - 0xBFFFFFFF
+ * NT_ERROR 0xC0000000 - 0xFFFFFFFF
+ *
+ * Effectively, we don't care on the severity of the return value from
+ * system(), we just need to know if it was because of exit() or generated
+ * by the system, and it seems values >= 0x100 are system-generated.
+ * See this URL for a list of WIN32 STATUS_* values:
+ *
+ * Wine (URL used in our error messages) -
+ * http://source.winehq.org/source/include/ntstatus.h
+ * Descriptions -
+ * https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55
+ *
+ * The comprehensive exception list is included in ntstatus.h from the
+ * Windows Driver Kit (WDK). A subset of the list is also included in
+ * winnt.h from the Windows SDK. Defining WIN32_NO_STATUS before including
+ * windows.h helps to avoid any conflicts.
+ *
+ * Some day we might want to print descriptions for the most common
+ * exceptions, rather than printing an include file name. We could use
+ * RtlNtStatusToDosError() and pass to FormatMessage(), which can print
+ * the text of error values, but MinGW does not support
+ * RtlNtStatusToDosError().
+ */
+#define WIFEXITED(w) (((w) & 0XFFFFFF00) == 0)
+#define WIFSIGNALED(w) (!WIFEXITED(w))
+#define WEXITSTATUS(w) (w)
+#define WTERMSIG(w) (w)
+
+#define sigmask(sig) ( 1 << ((sig)-1) )
+
+/* Signal function return values */
+#undef SIG_DFL
+#undef SIG_ERR
+#undef SIG_IGN
+#define SIG_DFL ((pqsigfunc)0)
+#define SIG_ERR ((pqsigfunc)-1)
+#define SIG_IGN ((pqsigfunc)1)
+
+/* Some extra signals */
+#define SIGHUP 1
+#define SIGQUIT 3
+#define SIGTRAP 5
+#define SIGABRT 22 /* Set to match W32 value -- not UNIX value */
+#define SIGKILL 9
+#define SIGPIPE 13
+#define SIGALRM 14
+#define SIGSTOP 17
+#define SIGTSTP 18
+#define SIGCONT 19
+#define SIGCHLD 20
+#define SIGWINCH 28
+#define SIGUSR1 30
+#define SIGUSR2 31
+
+/* MinGW has gettimeofday(), but MSVC doesn't */
+#ifdef _MSC_VER
+/* Last parameter not used */
+extern int gettimeofday(struct timeval *tp, void *tzp);
+#endif
+
+/* for setitimer in backend/port/win32/timer.c */
+#define ITIMER_REAL 0
+struct itimerval
+{
+ struct timeval it_interval;
+ struct timeval it_value;
+};
+
+int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue);
+
+/* Convenience wrapper for GetFileType() */
+extern DWORD pgwin32_get_file_type(HANDLE hFile);
+
+/*
+ * WIN32 does not provide 64-bit off_t, but does provide the functions operating
+ * with 64-bit offsets. Also, fseek() might not give an error for unseekable
+ * streams, so harden that function with our version.
+ */
+#define pgoff_t __int64
+
+#ifdef _MSC_VER
+extern int _pgfseeko64(FILE *stream, pgoff_t offset, int origin);
+extern pgoff_t _pgftello64(FILE *stream);
+#define fseeko(stream, offset, origin) _pgfseeko64(stream, offset, origin)
+#define ftello(stream) _pgftello64(stream)
+#else
+#ifndef fseeko
+#define fseeko(stream, offset, origin) fseeko64(stream, offset, origin)
+#endif
+#ifndef ftello
+#define ftello(stream) ftello64(stream)
+#endif
+#endif
+
+/*
+ * Win32 also doesn't have symlinks, but we can emulate them with
+ * junction points on newer Win32 versions.
+ *
+ * Cygwin has its own symlinks which work on Win95/98/ME where
+ * junction points don't, so use those instead. We have no way of
+ * knowing what type of system Cygwin binaries will be run on.
+ * Note: Some CYGWIN includes might #define WIN32.
+ */
+extern int pgsymlink(const char *oldpath, const char *newpath);
+extern int pgreadlink(const char *path, char *buf, size_t size);
+
+#define symlink(oldpath, newpath) pgsymlink(oldpath, newpath)
+#define readlink(path, buf, size) pgreadlink(path, buf, size)
+
+/*
+ * Supplement to .
+ *
+ * Perl already has typedefs for uid_t and gid_t.
+ */
+#ifndef PLPERL_HAVE_UID_GID
+typedef int uid_t;
+typedef int gid_t;
+#endif
+typedef long key_t;
+
+#ifdef _MSC_VER
+typedef int pid_t;
+#endif
+
+/*
+ * Supplement to .
+ *
+ * We must pull in sys/stat.h before this part, else our overrides lose.
+ *
+ * stat() is not guaranteed to set the st_size field on win32, so we
+ * redefine it to our own implementation. See src/port/win32stat.c.
+ *
+ * The struct stat is 32 bit in MSVC, so we redefine it as a copy of
+ * struct __stat64. This also fixes the struct size for MINGW builds.
+ */
+struct stat /* This should match struct __stat64 */
+{
+ _dev_t st_dev;
+ _ino_t st_ino;
+ unsigned short st_mode;
+ short st_nlink;
+ short st_uid;
+ short st_gid;
+ _dev_t st_rdev;
+ __int64 st_size;
+ __time64_t st_atime;
+ __time64_t st_mtime;
+ __time64_t st_ctime;
+};
+
+extern int _pgfstat64(int fileno, struct stat *buf);
+extern int _pgstat64(const char *name, struct stat *buf);
+extern int _pglstat64(const char *name, struct stat *buf);
+
+#define fstat(fileno, sb) _pgfstat64(fileno, sb)
+#define stat(path, sb) _pgstat64(path, sb)
+#define lstat(path, sb) _pglstat64(path, sb)
+
+/* These macros are not provided by older MinGW, nor by MSVC */
+#ifndef S_IRUSR
+#define S_IRUSR _S_IREAD
+#endif
+#ifndef S_IWUSR
+#define S_IWUSR _S_IWRITE
+#endif
+#ifndef S_IXUSR
+#define S_IXUSR _S_IEXEC
+#endif
+#ifndef S_IRWXU
+#define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR)
+#endif
+#ifndef S_IRGRP
+#define S_IRGRP 0
+#endif
+#ifndef S_IWGRP
+#define S_IWGRP 0
+#endif
+#ifndef S_IXGRP
+#define S_IXGRP 0
+#endif
+#ifndef S_IRWXG
+#define S_IRWXG 0
+#endif
+#ifndef S_IROTH
+#define S_IROTH 0
+#endif
+#ifndef S_IWOTH
+#define S_IWOTH 0
+#endif
+#ifndef S_IXOTH
+#define S_IXOTH 0
+#endif
+#ifndef S_IRWXO
+#define S_IRWXO 0
+#endif
+#ifndef S_ISDIR
+#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
+#endif
+#ifndef S_ISREG
+#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
+#endif
+
+/*
+ * In order for lstat() to be able to report junction points as symlinks, we
+ * need to hijack a bit in st_mode, since neither MSVC nor MinGW provides
+ * S_ISLNK and there aren't any spare bits. We'll steal the one for character
+ * devices, because we don't otherwise make use of those.
+ */
+#ifdef S_ISLNK
+#error "S_ISLNK is already defined"
+#endif
+#ifdef S_IFLNK
+#error "S_IFLNK is already defined"
+#endif
+#define S_IFLNK S_IFCHR
+#define S_ISLNK(m) (((m) & S_IFLNK) == S_IFLNK)
+
+/*
+ * Supplement to .
+ * This is the same value as _O_NOINHERIT in the MS header file. This is
+ * to ensure that we don't collide with a future definition. It means
+ * we cannot use _O_NOINHERIT ourselves.
+ */
+#define O_DSYNC 0x0080
+
+/*
+ * Our open() replacement does not create inheritable handles, so it is safe to
+ * ignore O_CLOEXEC. (If we were using Windows' own open(), it might be
+ * necessary to convert this to _O_NOINHERIT.)
+ */
+#define O_CLOEXEC 0
+
+/*
+ * Supplement to .
+ *
+ * We redefine network-related Berkeley error symbols as the corresponding WSA
+ * constants. This allows strerror.c to recognize them as being in the Winsock
+ * error code range and pass them off to win32_socket_strerror(), since
+ * Windows' version of plain strerror() won't cope. Note that this will break
+ * if these names are used for anything else besides Windows Sockets errors.
+ * See TranslateSocketError() when changing this list.
+ */
+#undef EAGAIN
+#define EAGAIN WSAEWOULDBLOCK
+#undef EINTR
+#define EINTR WSAEINTR
+#undef EMSGSIZE
+#define EMSGSIZE WSAEMSGSIZE
+#undef EAFNOSUPPORT
+#define EAFNOSUPPORT WSAEAFNOSUPPORT
+#undef EWOULDBLOCK
+#define EWOULDBLOCK WSAEWOULDBLOCK
+#undef ECONNABORTED
+#define ECONNABORTED WSAECONNABORTED
+#undef ECONNRESET
+#define ECONNRESET WSAECONNRESET
+#undef EINPROGRESS
+#define EINPROGRESS WSAEINPROGRESS
+#undef EISCONN
+#define EISCONN WSAEISCONN
+#undef ENOBUFS
+#define ENOBUFS WSAENOBUFS
+#undef EPROTONOSUPPORT
+#define EPROTONOSUPPORT WSAEPROTONOSUPPORT
+#undef ECONNREFUSED
+#define ECONNREFUSED WSAECONNREFUSED
+#undef ENOTSOCK
+#define ENOTSOCK WSAENOTSOCK
+#undef EOPNOTSUPP
+#define EOPNOTSUPP WSAEOPNOTSUPP
+#undef EADDRINUSE
+#define EADDRINUSE WSAEADDRINUSE
+#undef EADDRNOTAVAIL
+#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
+#undef EHOSTDOWN
+#define EHOSTDOWN WSAEHOSTDOWN
+#undef EHOSTUNREACH
+#define EHOSTUNREACH WSAEHOSTUNREACH
+#undef ENETDOWN
+#define ENETDOWN WSAENETDOWN
+#undef ENETRESET
+#define ENETRESET WSAENETRESET
+#undef ENETUNREACH
+#define ENETUNREACH WSAENETUNREACH
+#undef ENOTCONN
+#define ENOTCONN WSAENOTCONN
+#undef ETIMEDOUT
+#define ETIMEDOUT WSAETIMEDOUT
+
+/*
+ * Locale stuff.
+ *
+ * Extended locale functions with gratuitous underscore prefixes.
+ * (These APIs are nevertheless fully documented by Microsoft.)
+ */
+#define locale_t _locale_t
+#define tolower_l _tolower_l
+#define toupper_l _toupper_l
+#define towlower_l _towlower_l
+#define towupper_l _towupper_l
+#define isdigit_l _isdigit_l
+#define iswdigit_l _iswdigit_l
+#define isalpha_l _isalpha_l
+#define iswalpha_l _iswalpha_l
+#define isalnum_l _isalnum_l
+#define iswalnum_l _iswalnum_l
+#define isupper_l _isupper_l
+#define iswupper_l _iswupper_l
+#define islower_l _islower_l
+#define iswlower_l _iswlower_l
+#define isgraph_l _isgraph_l
+#define iswgraph_l _iswgraph_l
+#define isprint_l _isprint_l
+#define iswprint_l _iswprint_l
+#define ispunct_l _ispunct_l
+#define iswpunct_l _iswpunct_l
+#define isspace_l _isspace_l
+#define iswspace_l _iswspace_l
+#define strcoll_l _strcoll_l
+#define strxfrm_l _strxfrm_l
+#define wcscoll_l _wcscoll_l
+#define wcstombs_l _wcstombs_l
+#define mbstowcs_l _mbstowcs_l
+
+/*
+ * Versions of libintl >= 0.18? try to replace setlocale() with a macro
+ * to their own versions. Remove the macro, if it exists, because it
+ * ends up calling the wrong version when the backend and libintl use
+ * different versions of msvcrt.
+ */
+#if defined(setlocale)
+#undef setlocale
+#endif
+
+/*
+ * Define our own wrapper macro around setlocale() to work around bugs in
+ * Windows' native setlocale() function.
+ */
+extern char *pgwin32_setlocale(int category, const char *locale);
+
+#define setlocale(a,b) pgwin32_setlocale(a,b)
+
+
+/* In backend/port/win32/signal.c */
+extern PGDLLIMPORT volatile int pg_signal_queue;
+extern PGDLLIMPORT int pg_signal_mask;
+extern PGDLLIMPORT HANDLE pgwin32_signal_event;
+extern PGDLLIMPORT HANDLE pgwin32_initial_signal_pipe;
+
+#define UNBLOCKED_SIGNAL_QUEUE() (pg_signal_queue & ~pg_signal_mask)
+#define PG_SIGNAL_COUNT 32
+
+extern void pgwin32_signal_initialize(void);
+extern HANDLE pgwin32_create_signal_listener(pid_t pid);
+extern void pgwin32_dispatch_queued_signals(void);
+extern void pg_queue_signal(int signum);
+
+/* In src/port/kill.c */
+#define kill(pid,sig) pgkill(pid,sig)
+extern int pgkill(int pid, int sig);
+
+/* In backend/port/win32/socket.c */
+#ifndef FRONTEND
+#define socket(af, type, protocol) pgwin32_socket(af, type, protocol)
+#define bind(s, addr, addrlen) pgwin32_bind(s, addr, addrlen)
+#define listen(s, backlog) pgwin32_listen(s, backlog)
+#define accept(s, addr, addrlen) pgwin32_accept(s, addr, addrlen)
+#define connect(s, name, namelen) pgwin32_connect(s, name, namelen)
+#define select(n, r, w, e, timeout) pgwin32_select(n, r, w, e, timeout)
+#define recv(s, buf, len, flags) pgwin32_recv(s, buf, len, flags)
+#define send(s, buf, len, flags) pgwin32_send(s, buf, len, flags)
+
+extern SOCKET pgwin32_socket(int af, int type, int protocol);
+extern int pgwin32_bind(SOCKET s, struct sockaddr *addr, int addrlen);
+extern int pgwin32_listen(SOCKET s, int backlog);
+extern SOCKET pgwin32_accept(SOCKET s, struct sockaddr *addr, int *addrlen);
+extern int pgwin32_connect(SOCKET s, const struct sockaddr *name, int namelen);
+extern int pgwin32_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timeval *timeout);
+extern int pgwin32_recv(SOCKET s, char *buf, int len, int flags);
+extern int pgwin32_send(SOCKET s, const void *buf, int len, int flags);
+extern int pgwin32_waitforsinglesocket(SOCKET s, int what, int timeout);
+
+extern PGDLLIMPORT int pgwin32_noblock;
+
+#endif /* FRONTEND */
+
+/* in backend/port/win32_shmem.c */
+extern int pgwin32_ReserveSharedMemoryRegion(HANDLE);
+
+/* in backend/port/win32/crashdump.c */
+extern void pgwin32_install_crashdump_handler(void);
+
+/* in port/win32dlopen.c */
+extern void *dlopen(const char *file, int mode);
+extern void *dlsym(void *handle, const char *symbol);
+extern int dlclose(void *handle);
+extern char *dlerror(void);
+
+#define RTLD_NOW 1
+#define RTLD_GLOBAL 0
+
+/* in port/win32error.c */
+extern void _dosmaperr(unsigned long);
+
+/* in port/win32env.c */
+extern int pgwin32_putenv(const char *);
+extern int pgwin32_setenv(const char *name, const char *value, int overwrite);
+extern int pgwin32_unsetenv(const char *name);
+
+#define putenv(x) pgwin32_putenv(x)
+#define setenv(x,y,z) pgwin32_setenv(x,y,z)
+#define unsetenv(x) pgwin32_unsetenv(x)
+
+/* in port/win32security.c */
+extern int pgwin32_is_service(void);
+extern int pgwin32_is_admin(void);
+
+/* Windows security token manipulation (in src/common/exec.c) */
+extern BOOL AddUserToTokenDacl(HANDLE hToken);
+
+/* Things that exist in MinGW headers, but need to be added to MSVC */
+#ifdef _MSC_VER
+
+#ifndef _WIN64
+typedef long ssize_t;
+#else
+typedef __int64 ssize_t;
+#endif
+
+typedef unsigned short mode_t;
+
+#define F_OK 0
+#define W_OK 2
+#define R_OK 4
+
+#endif /* _MSC_VER */
+
+#if defined(__MINGW32__) || defined(__MINGW64__)
+/*
+ * Mingw claims to have a strtof, and my reading of its source code suggests
+ * that it ought to work (and not need this hack), but the regression test
+ * results disagree with me; whether this is a version issue or not is not
+ * clear. However, using our wrapper (and the misrounded-input variant file,
+ * already required for supporting ancient systems) can't make things any
+ * worse, except for a tiny performance loss when reading zeros.
+ *
+ * See also cygwin.h for another instance of this.
+ */
+#define HAVE_BUGGY_STRTOF 1
+#endif
+
+/* in port/win32pread.c */
+extern ssize_t pg_pread(int fd, void *buf, size_t nbyte, off_t offset);
+
+/* in port/win32pwrite.c */
+extern ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset);
+
+#endif /* PG_WIN32_PORT_H */
diff --git a/pgsql/include/server/port/win32ntdll.h b/pgsql/include/server/port/win32ntdll.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ce9360ec125e8e2312eace2ce5f63b195537f54
--- /dev/null
+++ b/pgsql/include/server/port/win32ntdll.h
@@ -0,0 +1,34 @@
+/*-------------------------------------------------------------------------
+ *
+ * win32ntdll.h
+ * Dynamically loaded Windows NT functions.
+ *
+ * Portions Copyright (c) 2021-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/win32ntdll.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef WIN32NTDLL_H
+#define WIN32NTDLL_H
+
+#include
+#include
+
+#ifndef FLUSH_FLAGS_FILE_DATA_SYNC_ONLY
+#define FLUSH_FLAGS_FILE_DATA_SYNC_ONLY 0x4
+#endif
+
+typedef NTSTATUS (__stdcall * RtlGetLastNtStatus_t) (void);
+typedef ULONG (__stdcall * RtlNtStatusToDosError_t) (NTSTATUS);
+typedef NTSTATUS (__stdcall * NtFlushBuffersFileEx_t) (HANDLE, ULONG, PVOID, ULONG, PIO_STATUS_BLOCK);
+
+extern PGDLLIMPORT RtlGetLastNtStatus_t pg_RtlGetLastNtStatus;
+extern PGDLLIMPORT RtlNtStatusToDosError_t pg_RtlNtStatusToDosError;
+extern PGDLLIMPORT NtFlushBuffersFileEx_t pg_NtFlushBuffersFileEx;
+
+extern int initialize_ntdll(void);
+
+#endif /* WIN32NTDLL_H */
diff --git a/pgsql/include/server/portability/instr_time.h b/pgsql/include/server/portability/instr_time.h
new file mode 100644
index 0000000000000000000000000000000000000000..cc85138e21faa03ab0f44b2ea2536707c5242453
--- /dev/null
+++ b/pgsql/include/server/portability/instr_time.h
@@ -0,0 +1,197 @@
+/*-------------------------------------------------------------------------
+ *
+ * instr_time.h
+ * portable high-precision interval timing
+ *
+ * This file provides an abstraction layer to hide portability issues in
+ * interval timing. On Unix we use clock_gettime(), and on Windows we use
+ * QueryPerformanceCounter(). These macros also give some breathing room to
+ * use other high-precision-timing APIs.
+ *
+ * The basic data type is instr_time, which all callers should treat as an
+ * opaque typedef. instr_time can store either an absolute time (of
+ * unspecified reference time) or an interval. The operations provided
+ * for it are:
+ *
+ * INSTR_TIME_IS_ZERO(t) is t equal to zero?
+ *
+ * INSTR_TIME_SET_ZERO(t) set t to zero (memset is acceptable too)
+ *
+ * INSTR_TIME_SET_CURRENT(t) set t to current time
+ *
+ * INSTR_TIME_SET_CURRENT_LAZY(t) set t to current time if t is zero,
+ * evaluates to whether t changed
+ *
+ * INSTR_TIME_ADD(x, y) x += y
+ *
+ * INSTR_TIME_SUBTRACT(x, y) x -= y
+ *
+ * INSTR_TIME_ACCUM_DIFF(x, y, z) x += (y - z)
+ *
+ * INSTR_TIME_GET_DOUBLE(t) convert t to double (in seconds)
+ *
+ * INSTR_TIME_GET_MILLISEC(t) convert t to double (in milliseconds)
+ *
+ * INSTR_TIME_GET_MICROSEC(t) convert t to uint64 (in microseconds)
+ *
+ * INSTR_TIME_GET_NANOSEC(t) convert t to uint64 (in nanoseconds)
+ *
+ * Note that INSTR_TIME_SUBTRACT and INSTR_TIME_ACCUM_DIFF convert
+ * absolute times to intervals. The INSTR_TIME_GET_xxx operations are
+ * only useful on intervals.
+ *
+ * When summing multiple measurements, it's recommended to leave the
+ * running sum in instr_time form (ie, use INSTR_TIME_ADD or
+ * INSTR_TIME_ACCUM_DIFF) and convert to a result format only at the end.
+ *
+ * Beware of multiple evaluations of the macro arguments.
+ *
+ *
+ * Copyright (c) 2001-2023, PostgreSQL Global Development Group
+ *
+ * src/include/portability/instr_time.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef INSTR_TIME_H
+#define INSTR_TIME_H
+
+
+/*
+ * We store interval times as an int64 integer on all platforms, as int64 is
+ * cheap to add/subtract, the most common operation for instr_time. The
+ * acquisition of time and converting to specific units of time is platform
+ * specific.
+ *
+ * To avoid users of the API relying on the integer representation, we wrap
+ * the 64bit integer in a struct.
+ */
+typedef struct instr_time
+{
+ int64 ticks; /* in platforms specific unit */
+} instr_time;
+
+
+/* helpers macros used in platform specific code below */
+
+#define NS_PER_S INT64CONST(1000000000)
+#define NS_PER_MS INT64CONST(1000000)
+#define NS_PER_US INT64CONST(1000)
+
+
+#ifndef WIN32
+
+
+/* Use clock_gettime() */
+
+#include
+
+/*
+ * The best clockid to use according to the POSIX spec is CLOCK_MONOTONIC,
+ * since that will give reliable interval timing even in the face of changes
+ * to the system clock. However, POSIX doesn't require implementations to
+ * provide anything except CLOCK_REALTIME, so fall back to that if we don't
+ * find CLOCK_MONOTONIC.
+ *
+ * Also, some implementations have nonstandard clockids with better properties
+ * than CLOCK_MONOTONIC. In particular, as of macOS 10.12, Apple provides
+ * CLOCK_MONOTONIC_RAW which is both faster to read and higher resolution than
+ * their version of CLOCK_MONOTONIC.
+ */
+#if defined(__darwin__) && defined(CLOCK_MONOTONIC_RAW)
+#define PG_INSTR_CLOCK CLOCK_MONOTONIC_RAW
+#elif defined(CLOCK_MONOTONIC)
+#define PG_INSTR_CLOCK CLOCK_MONOTONIC
+#else
+#define PG_INSTR_CLOCK CLOCK_REALTIME
+#endif
+
+/* helper for INSTR_TIME_SET_CURRENT */
+static inline instr_time
+pg_clock_gettime_ns(void)
+{
+ instr_time now;
+ struct timespec tmp;
+
+ clock_gettime(PG_INSTR_CLOCK, &tmp);
+ now.ticks = tmp.tv_sec * NS_PER_S + tmp.tv_nsec;
+
+ return now;
+}
+
+#define INSTR_TIME_SET_CURRENT(t) \
+ ((t) = pg_clock_gettime_ns())
+
+#define INSTR_TIME_GET_NANOSEC(t) \
+ ((int64) (t).ticks)
+
+
+#else /* WIN32 */
+
+
+/* Use QueryPerformanceCounter() */
+
+/* helper for INSTR_TIME_SET_CURRENT */
+static inline instr_time
+pg_query_performance_counter(void)
+{
+ instr_time now;
+ LARGE_INTEGER tmp;
+
+ QueryPerformanceCounter(&tmp);
+ now.ticks = tmp.QuadPart;
+
+ return now;
+}
+
+static inline double
+GetTimerFrequency(void)
+{
+ LARGE_INTEGER f;
+
+ QueryPerformanceFrequency(&f);
+ return (double) f.QuadPart;
+}
+
+#define INSTR_TIME_SET_CURRENT(t) \
+ ((t) = pg_query_performance_counter())
+
+#define INSTR_TIME_GET_NANOSEC(t) \
+ ((int64) ((t).ticks * ((double) NS_PER_S / GetTimerFrequency())))
+
+#endif /* WIN32 */
+
+
+/*
+ * Common macros
+ */
+
+#define INSTR_TIME_IS_ZERO(t) ((t).ticks == 0)
+
+
+#define INSTR_TIME_SET_ZERO(t) ((t).ticks = 0)
+
+#define INSTR_TIME_SET_CURRENT_LAZY(t) \
+ (INSTR_TIME_IS_ZERO(t) ? INSTR_TIME_SET_CURRENT(t), true : false)
+
+
+#define INSTR_TIME_ADD(x,y) \
+ ((x).ticks += (y).ticks)
+
+#define INSTR_TIME_SUBTRACT(x,y) \
+ ((x).ticks -= (y).ticks)
+
+#define INSTR_TIME_ACCUM_DIFF(x,y,z) \
+ ((x).ticks += (y).ticks - (z).ticks)
+
+
+#define INSTR_TIME_GET_DOUBLE(t) \
+ ((double) INSTR_TIME_GET_NANOSEC(t) / NS_PER_S)
+
+#define INSTR_TIME_GET_MILLISEC(t) \
+ ((double) INSTR_TIME_GET_NANOSEC(t) / NS_PER_MS)
+
+#define INSTR_TIME_GET_MICROSEC(t) \
+ (INSTR_TIME_GET_NANOSEC(t) / NS_PER_US)
+
+#endif /* INSTR_TIME_H */
diff --git a/pgsql/include/server/portability/mem.h b/pgsql/include/server/portability/mem.h
new file mode 100644
index 0000000000000000000000000000000000000000..92c56225ae7317aa941a94364f3a7d26f95d3ef5
--- /dev/null
+++ b/pgsql/include/server/portability/mem.h
@@ -0,0 +1,48 @@
+/*-------------------------------------------------------------------------
+ *
+ * mem.h
+ * portability definitions for various memory operations
+ *
+ * Copyright (c) 2001-2023, PostgreSQL Global Development Group
+ *
+ * src/include/portability/mem.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MEM_H
+#define MEM_H
+
+#define IPCProtection (0600) /* access/modify by user only */
+
+#ifdef SHM_SHARE_MMU /* use intimate shared memory on Solaris */
+#define PG_SHMAT_FLAGS SHM_SHARE_MMU
+#else
+#define PG_SHMAT_FLAGS 0
+#endif
+
+/* Linux prefers MAP_ANONYMOUS, but the flag is called MAP_ANON on other systems. */
+#ifndef MAP_ANONYMOUS
+#define MAP_ANONYMOUS MAP_ANON
+#endif
+
+/* BSD-derived systems have MAP_HASSEMAPHORE, but it's not present (or needed) on Linux. */
+#ifndef MAP_HASSEMAPHORE
+#define MAP_HASSEMAPHORE 0
+#endif
+
+/*
+ * BSD-derived systems use the MAP_NOSYNC flag to prevent dirty mmap(2)
+ * pages from being gratuitously flushed to disk.
+ */
+#ifndef MAP_NOSYNC
+#define MAP_NOSYNC 0
+#endif
+
+#define PG_MMAP_FLAGS (MAP_SHARED|MAP_ANONYMOUS|MAP_HASSEMAPHORE)
+
+/* Some really old systems don't define MAP_FAILED. */
+#ifndef MAP_FAILED
+#define MAP_FAILED ((void *) -1)
+#endif
+
+#endif /* MEM_H */
diff --git a/pgsql/include/server/postmaster/autovacuum.h b/pgsql/include/server/postmaster/autovacuum.h
new file mode 100644
index 0000000000000000000000000000000000000000..65afd1ea1e8f4232ad80f5ba6b7684e7f4faab02
--- /dev/null
+++ b/pgsql/include/server/postmaster/autovacuum.h
@@ -0,0 +1,80 @@
+/*-------------------------------------------------------------------------
+ *
+ * autovacuum.h
+ * header file for integrated autovacuum daemon
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/postmaster/autovacuum.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef AUTOVACUUM_H
+#define AUTOVACUUM_H
+
+#include "storage/block.h"
+
+/*
+ * Other processes can request specific work from autovacuum, identified by
+ * AutoVacuumWorkItem elements.
+ */
+typedef enum
+{
+ AVW_BRINSummarizeRange
+} AutoVacuumWorkItemType;
+
+
+/* GUC variables */
+extern PGDLLIMPORT bool autovacuum_start_daemon;
+extern PGDLLIMPORT int autovacuum_max_workers;
+extern PGDLLIMPORT int autovacuum_work_mem;
+extern PGDLLIMPORT int autovacuum_naptime;
+extern PGDLLIMPORT int autovacuum_vac_thresh;
+extern PGDLLIMPORT double autovacuum_vac_scale;
+extern PGDLLIMPORT int autovacuum_vac_ins_thresh;
+extern PGDLLIMPORT double autovacuum_vac_ins_scale;
+extern PGDLLIMPORT int autovacuum_anl_thresh;
+extern PGDLLIMPORT double autovacuum_anl_scale;
+extern PGDLLIMPORT int autovacuum_freeze_max_age;
+extern PGDLLIMPORT int autovacuum_multixact_freeze_max_age;
+extern PGDLLIMPORT double autovacuum_vac_cost_delay;
+extern PGDLLIMPORT int autovacuum_vac_cost_limit;
+
+/* autovacuum launcher PID, only valid when worker is shutting down */
+extern PGDLLIMPORT int AutovacuumLauncherPid;
+
+extern PGDLLIMPORT int Log_autovacuum_min_duration;
+
+/* Status inquiry functions */
+extern bool AutoVacuumingActive(void);
+extern bool IsAutoVacuumLauncherProcess(void);
+extern bool IsAutoVacuumWorkerProcess(void);
+
+#define IsAnyAutoVacuumProcess() \
+ (IsAutoVacuumLauncherProcess() || IsAutoVacuumWorkerProcess())
+
+/* Functions to start autovacuum process, called from postmaster */
+extern void autovac_init(void);
+extern int StartAutoVacLauncher(void);
+extern int StartAutoVacWorker(void);
+
+/* called from postmaster when a worker could not be forked */
+extern void AutoVacWorkerFailed(void);
+
+#ifdef EXEC_BACKEND
+extern void AutoVacLauncherMain(int argc, char *argv[]) pg_attribute_noreturn();
+extern void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn();
+extern void AutovacuumWorkerIAm(void);
+extern void AutovacuumLauncherIAm(void);
+#endif
+
+extern bool AutoVacuumRequestWork(AutoVacuumWorkItemType type,
+ Oid relationId, BlockNumber blkno);
+
+/* shared memory stuff */
+extern Size AutoVacuumShmemSize(void);
+extern void AutoVacuumShmemInit(void);
+
+#endif /* AUTOVACUUM_H */
diff --git a/pgsql/include/server/postmaster/auxprocess.h b/pgsql/include/server/postmaster/auxprocess.h
new file mode 100644
index 0000000000000000000000000000000000000000..5c2d6527ff62f47ddd34a144863a4df5b9c76a82
--- /dev/null
+++ b/pgsql/include/server/postmaster/auxprocess.h
@@ -0,0 +1,20 @@
+/*-------------------------------------------------------------------------
+ * auxprocess.h
+ * include file for functions related to auxiliary processes.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/postmaster/auxprocess.h
+ *-------------------------------------------------------------------------
+ */
+#ifndef AUXPROCESS_H
+#define AUXPROCESS_H
+
+#include "miscadmin.h"
+
+extern void AuxiliaryProcessMain(AuxProcType auxtype) pg_attribute_noreturn();
+
+#endif /* AUXPROCESS_H */
diff --git a/pgsql/include/server/postmaster/bgworker.h b/pgsql/include/server/postmaster/bgworker.h
new file mode 100644
index 0000000000000000000000000000000000000000..845d4498e65dd33c1e911aa1e1d1b39e0fef3f67
--- /dev/null
+++ b/pgsql/include/server/postmaster/bgworker.h
@@ -0,0 +1,162 @@
+/*--------------------------------------------------------------------
+ * bgworker.h
+ * POSTGRES pluggable background workers interface
+ *
+ * A background worker is a process able to run arbitrary, user-supplied code,
+ * including normal transactions.
+ *
+ * Any external module loaded via shared_preload_libraries can register a
+ * worker. Workers can also be registered dynamically at runtime. In either
+ * case, the worker process is forked from the postmaster and runs the
+ * user-supplied "main" function. This code may connect to a database and
+ * run transactions. Workers can remain active indefinitely, but will be
+ * terminated if a shutdown or crash occurs.
+ *
+ * If the fork() call fails in the postmaster, it will try again later. Note
+ * that the failure can only be transient (fork failure due to high load,
+ * memory pressure, too many processes, etc); more permanent problems, like
+ * failure to connect to a database, are detected later in the worker and dealt
+ * with just by having the worker exit normally. A worker which exits with
+ * a return code of 0 will never be restarted and will be removed from worker
+ * list. A worker which exits with a return code of 1 will be restarted after
+ * the configured restart interval (unless that interval is BGW_NEVER_RESTART).
+ * The TerminateBackgroundWorker() function can be used to terminate a
+ * dynamically registered background worker; the worker will be sent a SIGTERM
+ * and will not be restarted after it exits. Whenever the postmaster knows
+ * that a worker will not be restarted, it unregisters the worker, freeing up
+ * that worker's slot for use by a new worker.
+ *
+ * Note that there might be more than one worker in a database concurrently,
+ * and the same module may request more than one worker running the same (or
+ * different) code.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/postmaster/bgworker.h
+ *--------------------------------------------------------------------
+ */
+#ifndef BGWORKER_H
+#define BGWORKER_H
+
+/*---------------------------------------------------------------------
+ * External module API.
+ *---------------------------------------------------------------------
+ */
+
+/*
+ * Pass this flag to have your worker be able to connect to shared memory.
+ * This flag is required.
+ */
+#define BGWORKER_SHMEM_ACCESS 0x0001
+
+/*
+ * This flag means the bgworker requires a database connection. The connection
+ * is not established automatically; the worker must establish it later.
+ * It requires that BGWORKER_SHMEM_ACCESS was passed too.
+ */
+#define BGWORKER_BACKEND_DATABASE_CONNECTION 0x0002
+
+/*
+ * This class is used internally for parallel queries, to keep track of the
+ * number of active parallel workers and make sure we never launch more than
+ * max_parallel_workers parallel workers at the same time. Third party
+ * background workers should not use this class.
+ */
+#define BGWORKER_CLASS_PARALLEL 0x0010
+/* add additional bgworker classes here */
+
+
+typedef void (*bgworker_main_type) (Datum main_arg);
+
+/*
+ * Points in time at which a bgworker can request to be started
+ */
+typedef enum
+{
+ BgWorkerStart_PostmasterStart,
+ BgWorkerStart_ConsistentState,
+ BgWorkerStart_RecoveryFinished
+} BgWorkerStartTime;
+
+#define BGW_DEFAULT_RESTART_INTERVAL 60
+#define BGW_NEVER_RESTART -1
+#define BGW_MAXLEN 96
+#define BGW_EXTRALEN 128
+
+typedef struct BackgroundWorker
+{
+ char bgw_name[BGW_MAXLEN];
+ char bgw_type[BGW_MAXLEN];
+ int bgw_flags;
+ BgWorkerStartTime bgw_start_time;
+ int bgw_restart_time; /* in seconds, or BGW_NEVER_RESTART */
+ char bgw_library_name[BGW_MAXLEN];
+ char bgw_function_name[BGW_MAXLEN];
+ Datum bgw_main_arg;
+ char bgw_extra[BGW_EXTRALEN];
+ pid_t bgw_notify_pid; /* SIGUSR1 this backend on start/stop */
+} BackgroundWorker;
+
+typedef enum BgwHandleStatus
+{
+ BGWH_STARTED, /* worker is running */
+ BGWH_NOT_YET_STARTED, /* worker hasn't been started yet */
+ BGWH_STOPPED, /* worker has exited */
+ BGWH_POSTMASTER_DIED /* postmaster died; worker status unclear */
+} BgwHandleStatus;
+
+struct BackgroundWorkerHandle;
+typedef struct BackgroundWorkerHandle BackgroundWorkerHandle;
+
+/* Register a new bgworker during shared_preload_libraries */
+extern void RegisterBackgroundWorker(BackgroundWorker *worker);
+
+/* Register a new bgworker from a regular backend */
+extern bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker,
+ BackgroundWorkerHandle **handle);
+
+/* Query the status of a bgworker */
+extern BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle,
+ pid_t *pidp);
+extern BgwHandleStatus WaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle, pid_t *pidp);
+extern BgwHandleStatus
+ WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *);
+extern const char *GetBackgroundWorkerTypeByPid(pid_t pid);
+
+/* Terminate a bgworker */
+extern void TerminateBackgroundWorker(BackgroundWorkerHandle *handle);
+
+/* This is valid in a running worker */
+extern PGDLLIMPORT BackgroundWorker *MyBgworkerEntry;
+
+/*
+ * Connect to the specified database, as the specified user. Only a worker
+ * that passed BGWORKER_BACKEND_DATABASE_CONNECTION during registration may
+ * call this.
+ *
+ * If username is NULL, bootstrapping superuser is used.
+ * If dbname is NULL, connection is made to no specific database;
+ * only shared catalogs can be accessed.
+ */
+extern void BackgroundWorkerInitializeConnection(const char *dbname, const char *username, uint32 flags);
+
+/* Just like the above, but specifying database and user by OID. */
+extern void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags);
+
+/*
+ * Flags to BackgroundWorkerInitializeConnection et al
+ *
+ *
+ * Allow bypassing datallowconn restrictions when connecting to database
+ */
+#define BGWORKER_BYPASS_ALLOWCONN 1
+
+
+/* Block/unblock signals in a background worker process */
+extern void BackgroundWorkerBlockSignals(void);
+extern void BackgroundWorkerUnblockSignals(void);
+
+#endif /* BGWORKER_H */
diff --git a/pgsql/include/server/postmaster/bgworker_internals.h b/pgsql/include/server/postmaster/bgworker_internals.h
new file mode 100644
index 0000000000000000000000000000000000000000..4ad63fd9bd7f918c3decc154557c7aaee9d117fe
--- /dev/null
+++ b/pgsql/include/server/postmaster/bgworker_internals.h
@@ -0,0 +1,64 @@
+/*--------------------------------------------------------------------
+ * bgworker_internals.h
+ * POSTGRES pluggable background workers internals
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/postmaster/bgworker_internals.h
+ *--------------------------------------------------------------------
+ */
+#ifndef BGWORKER_INTERNALS_H
+#define BGWORKER_INTERNALS_H
+
+#include "datatype/timestamp.h"
+#include "lib/ilist.h"
+#include "postmaster/bgworker.h"
+
+/* GUC options */
+
+/*
+ * Maximum possible value of parallel workers.
+ */
+#define MAX_PARALLEL_WORKER_LIMIT 1024
+
+/*
+ * List of background workers, private to postmaster.
+ *
+ * A worker that requests a database connection during registration will have
+ * rw_backend set, and will be present in BackendList. Note: do not rely on
+ * rw_backend being non-NULL for shmem-connected workers!
+ */
+typedef struct RegisteredBgWorker
+{
+ BackgroundWorker rw_worker; /* its registry entry */
+ struct bkend *rw_backend; /* its BackendList entry, or NULL */
+ pid_t rw_pid; /* 0 if not running */
+ int rw_child_slot;
+ TimestampTz rw_crashed_at; /* if not 0, time it last crashed */
+ int rw_shmem_slot;
+ bool rw_terminate;
+ slist_node rw_lnode; /* list link */
+} RegisteredBgWorker;
+
+extern PGDLLIMPORT slist_head BackgroundWorkerList;
+
+extern Size BackgroundWorkerShmemSize(void);
+extern void BackgroundWorkerShmemInit(void);
+extern void BackgroundWorkerStateChange(bool allow_new_workers);
+extern void ForgetBackgroundWorker(slist_mutable_iter *cur);
+extern void ReportBackgroundWorkerPID(RegisteredBgWorker *);
+extern void ReportBackgroundWorkerExit(slist_mutable_iter *cur);
+extern void BackgroundWorkerStopNotifications(pid_t pid);
+extern void ForgetUnstartedBackgroundWorkers(void);
+extern void ResetBackgroundWorkerCrashTimes(void);
+
+/* Function to start a background worker, called from postmaster.c */
+extern void StartBackgroundWorker(void) pg_attribute_noreturn();
+
+#ifdef EXEC_BACKEND
+extern BackgroundWorker *BackgroundWorkerEntry(int slotno);
+#endif
+
+#endif /* BGWORKER_INTERNALS_H */
diff --git a/pgsql/include/server/postmaster/bgwriter.h b/pgsql/include/server/postmaster/bgwriter.h
new file mode 100644
index 0000000000000000000000000000000000000000..a66722873f4262e5c436ff2702ead0f663abb9ee
--- /dev/null
+++ b/pgsql/include/server/postmaster/bgwriter.h
@@ -0,0 +1,45 @@
+/*-------------------------------------------------------------------------
+ *
+ * bgwriter.h
+ * Exports from postmaster/bgwriter.c and postmaster/checkpointer.c.
+ *
+ * The bgwriter process used to handle checkpointing duties too. Now
+ * there is a separate process, but we did not bother to split this header.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/postmaster/bgwriter.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _BGWRITER_H
+#define _BGWRITER_H
+
+#include "storage/block.h"
+#include "storage/relfilelocator.h"
+#include "storage/smgr.h"
+#include "storage/sync.h"
+
+
+/* GUC options */
+extern PGDLLIMPORT int BgWriterDelay;
+extern PGDLLIMPORT int CheckPointTimeout;
+extern PGDLLIMPORT int CheckPointWarning;
+extern PGDLLIMPORT double CheckPointCompletionTarget;
+
+extern void BackgroundWriterMain(void) pg_attribute_noreturn();
+extern void CheckpointerMain(void) pg_attribute_noreturn();
+
+extern void RequestCheckpoint(int flags);
+extern void CheckpointWriteDelay(int flags, double progress);
+
+extern bool ForwardSyncRequest(const FileTag *ftag, SyncRequestType type);
+
+extern void AbsorbSyncRequests(void);
+
+extern Size CheckpointerShmemSize(void);
+extern void CheckpointerShmemInit(void);
+
+extern bool FirstCallSinceLastCheckpoint(void);
+
+#endif /* _BGWRITER_H */
diff --git a/pgsql/include/server/postmaster/fork_process.h b/pgsql/include/server/postmaster/fork_process.h
new file mode 100644
index 0000000000000000000000000000000000000000..12decc8133bc97c55bbc0eca33dd143ea98af251
--- /dev/null
+++ b/pgsql/include/server/postmaster/fork_process.h
@@ -0,0 +1,17 @@
+/*-------------------------------------------------------------------------
+ *
+ * fork_process.h
+ * Exports from postmaster/fork_process.c.
+ *
+ * Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/postmaster/fork_process.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FORK_PROCESS_H
+#define FORK_PROCESS_H
+
+extern pid_t fork_process(void);
+
+#endif /* FORK_PROCESS_H */
diff --git a/pgsql/include/server/postmaster/interrupt.h b/pgsql/include/server/postmaster/interrupt.h
new file mode 100644
index 0000000000000000000000000000000000000000..218f5ea3b12b612fb8d3abe6dc2c0b445aa19fee
--- /dev/null
+++ b/pgsql/include/server/postmaster/interrupt.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * interrupt.h
+ * Interrupt handling routines.
+ *
+ * Responses to interrupts are fairly varied and many types of backends
+ * have their own implementations, but we provide a few generic things
+ * here to facilitate code reuse.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/postmaster/interrupt.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef INTERRUPT_H
+#define INTERRUPT_H
+
+#include
+
+extern PGDLLIMPORT volatile sig_atomic_t ConfigReloadPending;
+extern PGDLLIMPORT volatile sig_atomic_t ShutdownRequestPending;
+
+extern void HandleMainLoopInterrupts(void);
+extern void SignalHandlerForConfigReload(SIGNAL_ARGS);
+extern void SignalHandlerForCrashExit(SIGNAL_ARGS);
+extern void SignalHandlerForShutdownRequest(SIGNAL_ARGS);
+
+#endif
diff --git a/pgsql/include/server/postmaster/pgarch.h b/pgsql/include/server/postmaster/pgarch.h
new file mode 100644
index 0000000000000000000000000000000000000000..3bd4fac71e524c7b21bd0236c3a8ce29ee3d1de8
--- /dev/null
+++ b/pgsql/include/server/postmaster/pgarch.h
@@ -0,0 +1,36 @@
+/*-------------------------------------------------------------------------
+ *
+ * pgarch.h
+ * Exports from postmaster/pgarch.c.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/postmaster/pgarch.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PGARCH_H
+#define _PGARCH_H
+
+/* ----------
+ * Archiver control info.
+ *
+ * We expect that archivable files within pg_wal will have names between
+ * MIN_XFN_CHARS and MAX_XFN_CHARS in length, consisting only of characters
+ * appearing in VALID_XFN_CHARS. The status files in archive_status have
+ * corresponding names with ".ready" or ".done" appended.
+ * ----------
+ */
+#define MIN_XFN_CHARS 16
+#define MAX_XFN_CHARS 40
+#define VALID_XFN_CHARS "0123456789ABCDEF.history.backup.partial"
+
+extern Size PgArchShmemSize(void);
+extern void PgArchShmemInit(void);
+extern bool PgArchCanRestart(void);
+extern void PgArchiverMain(void) pg_attribute_noreturn();
+extern void PgArchWakeup(void);
+extern void PgArchForceDirScan(void);
+
+#endif /* _PGARCH_H */
diff --git a/pgsql/include/server/postmaster/postmaster.h b/pgsql/include/server/postmaster/postmaster.h
new file mode 100644
index 0000000000000000000000000000000000000000..3b3889c58c049be0aec3d89c7532a7b5da914862
--- /dev/null
+++ b/pgsql/include/server/postmaster/postmaster.h
@@ -0,0 +1,81 @@
+/*-------------------------------------------------------------------------
+ *
+ * postmaster.h
+ * Exports from postmaster/postmaster.c.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/postmaster/postmaster.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _POSTMASTER_H
+#define _POSTMASTER_H
+
+/* GUC options */
+extern PGDLLIMPORT bool EnableSSL;
+extern PGDLLIMPORT int SuperuserReservedConnections;
+extern PGDLLIMPORT int ReservedConnections;
+extern PGDLLIMPORT int PostPortNumber;
+extern PGDLLIMPORT int Unix_socket_permissions;
+extern PGDLLIMPORT char *Unix_socket_group;
+extern PGDLLIMPORT char *Unix_socket_directories;
+extern PGDLLIMPORT char *ListenAddresses;
+extern PGDLLIMPORT bool ClientAuthInProgress;
+extern PGDLLIMPORT int PreAuthDelay;
+extern PGDLLIMPORT int AuthenticationTimeout;
+extern PGDLLIMPORT bool Log_connections;
+extern PGDLLIMPORT bool log_hostname;
+extern PGDLLIMPORT bool enable_bonjour;
+extern PGDLLIMPORT char *bonjour_name;
+extern PGDLLIMPORT bool restart_after_crash;
+extern PGDLLIMPORT bool remove_temp_files_after_crash;
+extern PGDLLIMPORT bool send_abort_for_crash;
+extern PGDLLIMPORT bool send_abort_for_kill;
+
+#ifdef WIN32
+extern PGDLLIMPORT HANDLE PostmasterHandle;
+#else
+extern PGDLLIMPORT int postmaster_alive_fds[2];
+
+/*
+ * Constants that represent which of postmaster_alive_fds is held by
+ * postmaster, and which is used in children to check for postmaster death.
+ */
+#define POSTMASTER_FD_WATCH 0 /* used in children to check for
+ * postmaster death */
+#define POSTMASTER_FD_OWN 1 /* kept open by postmaster only */
+#endif
+
+extern PGDLLIMPORT const char *progname;
+
+extern void PostmasterMain(int argc, char *argv[]) pg_attribute_noreturn();
+extern void ClosePostmasterPorts(bool am_syslogger);
+extern void InitProcessGlobals(void);
+
+extern int MaxLivePostmasterChildren(void);
+
+extern bool PostmasterMarkPIDForWorkerNotify(int);
+
+#ifdef EXEC_BACKEND
+extern pid_t postmaster_forkexec(int argc, char *argv[]);
+extern void SubPostmasterMain(int argc, char *argv[]) pg_attribute_noreturn();
+
+extern Size ShmemBackendArraySize(void);
+extern void ShmemBackendArrayAllocation(void);
+#endif
+
+/*
+ * Note: MAX_BACKENDS is limited to 2^18-1 because that's the width reserved
+ * for buffer references in buf_internals.h. This limitation could be lifted
+ * by using a 64bit state; but it's unlikely to be worthwhile as 2^18-1
+ * backends exceed currently realistic configurations. Even if that limitation
+ * were removed, we still could not a) exceed 2^23-1 because inval.c stores
+ * the backend ID as a 3-byte signed integer, b) INT_MAX/4 because some places
+ * compute 4*MaxBackends without any overflow check. This is rechecked in the
+ * relevant GUC check hooks and in RegisterBackgroundWorker().
+ */
+#define MAX_BACKENDS 0x3FFFF
+
+#endif /* _POSTMASTER_H */
diff --git a/pgsql/include/server/postmaster/startup.h b/pgsql/include/server/postmaster/startup.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a2e4c4526be6fb0ffed11df02ad587c198d23de
--- /dev/null
+++ b/pgsql/include/server/postmaster/startup.h
@@ -0,0 +1,41 @@
+/*-------------------------------------------------------------------------
+ *
+ * startup.h
+ * Exports from postmaster/startup.c.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/postmaster/startup.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _STARTUP_H
+#define _STARTUP_H
+
+/*
+ * Log the startup progress message if a timer has expired.
+ */
+#define ereport_startup_progress(msg, ...) \
+ do { \
+ long secs; \
+ int usecs; \
+ if (has_startup_progress_timeout_expired(&secs, &usecs)) \
+ ereport(LOG, errmsg(msg, secs, (usecs / 10000), __VA_ARGS__ )); \
+ } while(0)
+
+extern PGDLLIMPORT int log_startup_progress_interval;
+
+extern void HandleStartupProcInterrupts(void);
+extern void StartupProcessMain(void) pg_attribute_noreturn();
+extern void PreRestoreCommand(void);
+extern void PostRestoreCommand(void);
+extern bool IsPromoteSignaled(void);
+extern void ResetPromoteSignaled(void);
+
+extern void enable_startup_progress_timeout(void);
+extern void disable_startup_progress_timeout(void);
+extern void begin_startup_progress_phase(void);
+extern void startup_progress_timeout_handler(void);
+extern bool has_startup_progress_timeout_expired(long *secs, int *usecs);
+
+#endif /* _STARTUP_H */
diff --git a/pgsql/include/server/postmaster/syslogger.h b/pgsql/include/server/postmaster/syslogger.h
new file mode 100644
index 0000000000000000000000000000000000000000..34da778f1efae6fa7b8bdc3017bb898722e664b0
--- /dev/null
+++ b/pgsql/include/server/postmaster/syslogger.h
@@ -0,0 +1,103 @@
+/*-------------------------------------------------------------------------
+ *
+ * syslogger.h
+ * Exports from postmaster/syslogger.c.
+ *
+ * Copyright (c) 2004-2023, PostgreSQL Global Development Group
+ *
+ * src/include/postmaster/syslogger.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _SYSLOGGER_H
+#define _SYSLOGGER_H
+
+#include /* for PIPE_BUF */
+
+
+/*
+ * Primitive protocol structure for writing to syslogger pipe(s). The idea
+ * here is to divide long messages into chunks that are not more than
+ * PIPE_BUF bytes long, which according to POSIX spec must be written into
+ * the pipe atomically. The pipe reader then uses the protocol headers to
+ * reassemble the parts of a message into a single string. The reader can
+ * also cope with non-protocol data coming down the pipe, though we cannot
+ * guarantee long strings won't get split apart.
+ *
+ * We use non-nul bytes in is_last to make the protocol a tiny bit
+ * more robust against finding a false double nul byte prologue. But
+ * we still might find it in the len and/or pid bytes unless we're careful.
+ */
+
+#ifdef PIPE_BUF
+/* Are there any systems with PIPE_BUF > 64K? Unlikely, but ... */
+#if PIPE_BUF > 65536
+#define PIPE_CHUNK_SIZE 65536
+#else
+#define PIPE_CHUNK_SIZE ((int) PIPE_BUF)
+#endif
+#else /* not defined */
+/* POSIX says the value of PIPE_BUF must be at least 512, so use that */
+#define PIPE_CHUNK_SIZE 512
+#endif
+
+typedef struct
+{
+ char nuls[2]; /* always \0\0 */
+ uint16 len; /* size of this chunk (counts data only) */
+ int32 pid; /* writer's pid */
+ bits8 flags; /* bitmask of PIPE_PROTO_* */
+ char data[FLEXIBLE_ARRAY_MEMBER]; /* data payload starts here */
+} PipeProtoHeader;
+
+typedef union
+{
+ PipeProtoHeader proto;
+ char filler[PIPE_CHUNK_SIZE];
+} PipeProtoChunk;
+
+#define PIPE_HEADER_SIZE offsetof(PipeProtoHeader, data)
+#define PIPE_MAX_PAYLOAD ((int) (PIPE_CHUNK_SIZE - PIPE_HEADER_SIZE))
+
+/* flag bits for PipeProtoHeader->flags */
+#define PIPE_PROTO_IS_LAST 0x01 /* last chunk of message? */
+/* log destinations */
+#define PIPE_PROTO_DEST_STDERR 0x10
+#define PIPE_PROTO_DEST_CSVLOG 0x20
+#define PIPE_PROTO_DEST_JSONLOG 0x40
+
+/* GUC options */
+extern PGDLLIMPORT bool Logging_collector;
+extern PGDLLIMPORT int Log_RotationAge;
+extern PGDLLIMPORT int Log_RotationSize;
+extern PGDLLIMPORT char *Log_directory;
+extern PGDLLIMPORT char *Log_filename;
+extern PGDLLIMPORT bool Log_truncate_on_rotation;
+extern PGDLLIMPORT int Log_file_mode;
+
+#ifndef WIN32
+extern PGDLLIMPORT int syslogPipe[2];
+#else
+extern PGDLLIMPORT HANDLE syslogPipe[2];
+#endif
+
+
+extern int SysLogger_Start(void);
+
+extern void write_syslogger_file(const char *buffer, int count, int destination);
+
+#ifdef EXEC_BACKEND
+extern void SysLoggerMain(int argc, char *argv[]) pg_attribute_noreturn();
+#endif
+
+extern bool CheckLogrotateSignal(void);
+extern void RemoveLogrotateSignalFiles(void);
+
+/*
+ * Name of files saving meta-data information about the log
+ * files currently in use by the syslogger
+ */
+#define LOG_METAINFO_DATAFILE "current_logfiles"
+#define LOG_METAINFO_DATAFILE_TMP LOG_METAINFO_DATAFILE ".tmp"
+
+#endif /* _SYSLOGGER_H */
diff --git a/pgsql/include/server/postmaster/walwriter.h b/pgsql/include/server/postmaster/walwriter.h
new file mode 100644
index 0000000000000000000000000000000000000000..6eba7ad79cf8bf76ae495730d4cb3a2d68271e51
--- /dev/null
+++ b/pgsql/include/server/postmaster/walwriter.h
@@ -0,0 +1,23 @@
+/*-------------------------------------------------------------------------
+ *
+ * walwriter.h
+ * Exports from postmaster/walwriter.c.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/postmaster/walwriter.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _WALWRITER_H
+#define _WALWRITER_H
+
+#define DEFAULT_WAL_WRITER_FLUSH_AFTER ((1024 * 1024) / XLOG_BLCKSZ)
+
+/* GUC options */
+extern PGDLLIMPORT int WalWriterDelay;
+extern PGDLLIMPORT int WalWriterFlushAfter;
+
+extern void WalWriterMain(void) pg_attribute_noreturn();
+
+#endif /* _WALWRITER_H */
diff --git a/pgsql/include/server/regex/regcustom.h b/pgsql/include/server/regex/regcustom.h
new file mode 100644
index 0000000000000000000000000000000000000000..af0fe97c796d2a5f3c47cb174a5c567299b901ad
--- /dev/null
+++ b/pgsql/include/server/regex/regcustom.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved.
+ *
+ * Development of this software was funded, in part, by Cray Research Inc.,
+ * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics
+ * Corporation, none of whom are responsible for the results. The author
+ * thanks all of them.
+ *
+ * Redistribution and use in source and binary forms -- with or without
+ * modification -- are permitted for any purpose, provided that
+ * redistributions in source form retain this entire copyright notice and
+ * indicate the origin and nature of any modifications.
+ *
+ * I'd appreciate being given credit for this package in the documentation
+ * of software which uses it, but that is not a requirement.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+ * HENRY SPENCER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * src/include/regex/regcustom.h
+ */
+
+/* headers if any */
+
+/*
+ * It's against Postgres coding conventions to include postgres.h in a
+ * header file, but we allow the violation here because the regexp library
+ * files specifically intend this file to supply application-dependent
+ * headers, and are careful to include this file before anything else.
+ */
+#include "postgres.h"
+
+#include
+#include
+#include
+
+#include "mb/pg_wchar.h"
+
+#include "miscadmin.h" /* needed by rstacktoodeep */
+
+
+/* overrides for regguts.h definitions, if any */
+#define FUNCPTR(name, args) (*name) args
+#define MALLOC(n) palloc_extended((n), MCXT_ALLOC_NO_OOM)
+#define FREE(p) pfree(VS(p))
+#define REALLOC(p,n) repalloc_extended(VS(p),(n), MCXT_ALLOC_NO_OOM)
+#define INTERRUPT(re) CHECK_FOR_INTERRUPTS()
+#define assert(x) Assert(x)
+
+/* internal character type and related */
+typedef pg_wchar chr; /* the type itself */
+typedef unsigned uchr; /* unsigned type that will hold a chr */
+
+#define CHR(c) ((unsigned char) (c)) /* turn char literal into chr literal */
+#define DIGITVAL(c) ((c)-'0') /* turn chr digit into its value */
+#define CHRBITS 32 /* bits in a chr; must not use sizeof */
+#define CHR_MIN 0x00000000 /* smallest and largest chr; the value */
+#define CHR_MAX 0x7ffffffe /* CHR_MAX-CHR_MIN+1 must fit in an int, and
+ * CHR_MAX+1 must fit in a chr variable */
+
+/*
+ * Check if a chr value is in range. Ideally we'd just write this as
+ * ((c) >= CHR_MIN && (c) <= CHR_MAX)
+ * However, if chr is unsigned and CHR_MIN is zero, the first part of that
+ * is a no-op, and certain overly-nannyish compilers give warnings about it.
+ * So we leave that out here. If you want to make chr signed and/or CHR_MIN
+ * not zero, redefine this macro as above. Callers should assume that the
+ * macro may multiply evaluate its argument, even though it does not today.
+ */
+#define CHR_IS_IN_RANGE(c) ((c) <= CHR_MAX)
+
+/*
+ * MAX_SIMPLE_CHR is the cutoff between "simple" and "complicated" processing
+ * in the color map logic. It should usually be chosen high enough to ensure
+ * that all common characters are <= MAX_SIMPLE_CHR. However, very large
+ * values will be counterproductive since they cause more regex setup time.
+ * Also, small values can be helpful for testing the high-color-map logic
+ * with plain old ASCII input.
+ */
+#define MAX_SIMPLE_CHR 0x7FF /* suitable value for Unicode */
+
+/* functions operating on chr */
+#define iscalnum(x) pg_wc_isalnum(x)
+#define iscalpha(x) pg_wc_isalpha(x)
+#define iscdigit(x) pg_wc_isdigit(x)
+#define iscspace(x) pg_wc_isspace(x)
+
+/* and pick up the standard header */
+#include "regex.h"
diff --git a/pgsql/include/server/regex/regerrs.h b/pgsql/include/server/regex/regerrs.h
new file mode 100644
index 0000000000000000000000000000000000000000..2c8873eb81038a4e02d18215d6509271d5e27747
--- /dev/null
+++ b/pgsql/include/server/regex/regerrs.h
@@ -0,0 +1,83 @@
+/*
+ * src/include/regex/regerrs.h
+ */
+
+{
+ REG_OKAY, "REG_OKAY", "no errors detected"
+},
+
+{
+ REG_NOMATCH, "REG_NOMATCH", "failed to match"
+},
+
+{
+ REG_BADPAT, "REG_BADPAT", "invalid regexp (reg version 0.8)"
+},
+
+{
+ REG_ECOLLATE, "REG_ECOLLATE", "invalid collating element"
+},
+
+{
+ REG_ECTYPE, "REG_ECTYPE", "invalid character class"
+},
+
+{
+ REG_EESCAPE, "REG_EESCAPE", "invalid escape \\ sequence"
+},
+
+{
+ REG_ESUBREG, "REG_ESUBREG", "invalid backreference number"
+},
+
+{
+ REG_EBRACK, "REG_EBRACK", "brackets [] not balanced"
+},
+
+{
+ REG_EPAREN, "REG_EPAREN", "parentheses () not balanced"
+},
+
+{
+ REG_EBRACE, "REG_EBRACE", "braces {} not balanced"
+},
+
+{
+ REG_BADBR, "REG_BADBR", "invalid repetition count(s)"
+},
+
+{
+ REG_ERANGE, "REG_ERANGE", "invalid character range"
+},
+
+{
+ REG_ESPACE, "REG_ESPACE", "out of memory"
+},
+
+{
+ REG_BADRPT, "REG_BADRPT", "quantifier operand invalid"
+},
+
+{
+ REG_ASSERT, "REG_ASSERT", "\"cannot happen\" -- you found a bug"
+},
+
+{
+ REG_INVARG, "REG_INVARG", "invalid argument to regex function"
+},
+
+{
+ REG_MIXED, "REG_MIXED", "character widths of regex and string differ"
+},
+
+{
+ REG_BADOPT, "REG_BADOPT", "invalid embedded option"
+},
+
+{
+ REG_ETOOBIG, "REG_ETOOBIG", "regular expression is too complex"
+},
+
+{
+ REG_ECOLORS, "REG_ECOLORS", "too many colors"
+},
diff --git a/pgsql/include/server/regex/regex.h b/pgsql/include/server/regex/regex.h
new file mode 100644
index 0000000000000000000000000000000000000000..d08113724f6c90b99ea7f3ac7563ece483cb27a1
--- /dev/null
+++ b/pgsql/include/server/regex/regex.h
@@ -0,0 +1,189 @@
+#ifndef _REGEX_H_
+#define _REGEX_H_ /* never again */
+/*
+ * regular expressions
+ *
+ * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved.
+ *
+ * Development of this software was funded, in part, by Cray Research Inc.,
+ * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics
+ * Corporation, none of whom are responsible for the results. The author
+ * thanks all of them.
+ *
+ * Redistribution and use in source and binary forms -- with or without
+ * modification -- are permitted for any purpose, provided that
+ * redistributions in source form retain this entire copyright notice and
+ * indicate the origin and nature of any modifications.
+ *
+ * I'd appreciate being given credit for this package in the documentation
+ * of software which uses it, but that is not a requirement.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+ * HENRY SPENCER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * src/include/regex/regex.h
+ */
+
+/*
+ * Add your own defines, if needed, here.
+ */
+#include "mb/pg_wchar.h"
+
+/*
+ * interface types etc.
+ */
+
+/*
+ * regoff_t has to be large enough to hold either off_t or ssize_t,
+ * and must be signed; it's only a guess that long is suitable.
+ */
+typedef long regoff_t;
+
+/*
+ * other interface types
+ */
+
+/* the biggie, a compiled RE (or rather, a front end to same) */
+typedef struct
+{
+ int re_magic; /* magic number */
+ size_t re_nsub; /* number of subexpressions */
+ long re_info; /* bitmask of the following flags: */
+#define REG_UBACKREF 000001 /* has back-reference (\n) */
+#define REG_ULOOKAROUND 000002 /* has lookahead/lookbehind constraint */
+#define REG_UBOUNDS 000004 /* has bounded quantifier ({m,n}) */
+#define REG_UBRACES 000010 /* has { that doesn't begin a quantifier */
+#define REG_UBSALNUM 000020 /* has backslash-alphanumeric in non-ARE */
+#define REG_UPBOTCH 000040 /* has unmatched right paren in ERE (legal
+ * per spec, but that was a mistake) */
+#define REG_UBBS 000100 /* has backslash within bracket expr */
+#define REG_UNONPOSIX 000200 /* has any construct that extends POSIX */
+#define REG_UUNSPEC 000400 /* has any case disallowed by POSIX, e.g.
+ * an empty branch */
+#define REG_UUNPORT 001000 /* has numeric character code dependency */
+#define REG_ULOCALE 002000 /* has locale dependency */
+#define REG_UEMPTYMATCH 004000 /* can match a zero-length string */
+#define REG_UIMPOSSIBLE 010000 /* provably cannot match anything */
+#define REG_USHORTEST 020000 /* has non-greedy quantifier */
+ int re_csize; /* sizeof(character) */
+ char *re_endp; /* backward compatibility kludge */
+ Oid re_collation; /* Collation that defines LC_CTYPE behavior */
+ /* the rest is opaque pointers to hidden innards */
+ char *re_guts; /* `char *' is more portable than `void *' */
+ char *re_fns;
+} regex_t;
+
+/* result reporting (may acquire more fields later) */
+typedef struct
+{
+ regoff_t rm_so; /* start of substring */
+ regoff_t rm_eo; /* end of substring */
+} regmatch_t;
+
+/* supplementary control and reporting */
+typedef struct
+{
+ regmatch_t rm_extend; /* see REG_EXPECT */
+} rm_detail_t;
+
+
+
+/*
+ * regex compilation flags
+ */
+#define REG_BASIC 000000 /* BREs (convenience) */
+#define REG_EXTENDED 000001 /* EREs */
+#define REG_ADVF 000002 /* advanced features in EREs */
+#define REG_ADVANCED 000003 /* AREs (which are also EREs) */
+#define REG_QUOTE 000004 /* no special characters, none */
+#define REG_NOSPEC REG_QUOTE /* historical synonym */
+#define REG_ICASE 000010 /* ignore case */
+#define REG_NOSUB 000020 /* caller doesn't need subexpr match data */
+#define REG_EXPANDED 000040 /* expanded format, white space & comments */
+#define REG_NLSTOP 000100 /* \n doesn't match . or [^ ] */
+#define REG_NLANCH 000200 /* ^ matches after \n, $ before */
+#define REG_NEWLINE 000300 /* newlines are line terminators */
+#define REG_PEND 000400 /* ugh -- backward-compatibility hack */
+#define REG_EXPECT 001000 /* report details on partial/limited matches */
+#define REG_BOSONLY 002000 /* temporary kludge for BOS-only matches */
+#define REG_DUMP 004000 /* none of your business :-) */
+#define REG_FAKE 010000 /* none of your business :-) */
+#define REG_PROGRESS 020000 /* none of your business :-) */
+
+
+
+/*
+ * regex execution flags
+ */
+#define REG_NOTBOL 0001 /* BOS is not BOL */
+#define REG_NOTEOL 0002 /* EOS is not EOL */
+#define REG_STARTEND 0004 /* backward compatibility kludge */
+#define REG_FTRACE 0010 /* none of your business */
+#define REG_MTRACE 0020 /* none of your business */
+#define REG_SMALL 0040 /* none of your business */
+
+
+/*
+ * error reporting
+ * Be careful if modifying the list of error codes -- the table used by
+ * regerror() is generated automatically from this file!
+ */
+#define REG_OKAY 0 /* no errors detected */
+#define REG_NOMATCH 1 /* failed to match */
+#define REG_BADPAT 2 /* invalid regexp */
+#define REG_ECOLLATE 3 /* invalid collating element */
+#define REG_ECTYPE 4 /* invalid character class */
+#define REG_EESCAPE 5 /* invalid escape \ sequence */
+#define REG_ESUBREG 6 /* invalid backreference number */
+#define REG_EBRACK 7 /* brackets [] not balanced */
+#define REG_EPAREN 8 /* parentheses () not balanced */
+#define REG_EBRACE 9 /* braces {} not balanced */
+#define REG_BADBR 10 /* invalid repetition count(s) */
+#define REG_ERANGE 11 /* invalid character range */
+#define REG_ESPACE 12 /* out of memory */
+#define REG_BADRPT 13 /* quantifier operand invalid */
+#define REG_ASSERT 15 /* "can't happen" -- you found a bug */
+#define REG_INVARG 16 /* invalid argument to regex function */
+#define REG_MIXED 17 /* character widths of regex and string differ */
+#define REG_BADOPT 18 /* invalid embedded option */
+#define REG_ETOOBIG 19 /* regular expression is too complex */
+#define REG_ECOLORS 20 /* too many colors */
+/* two specials for debugging and testing */
+#define REG_ATOI 101 /* convert error-code name to number */
+#define REG_ITOA 102 /* convert error-code number to name */
+/* non-error result codes for pg_regprefix */
+#define REG_PREFIX (-1) /* identified a common prefix */
+#define REG_EXACT (-2) /* identified an exact match */
+
+
+
+/*
+ * the prototypes for exported functions
+ */
+
+/* regcomp.c */
+extern int pg_regcomp(regex_t *re, const pg_wchar *string, size_t len,
+ int flags, Oid collation);
+extern int pg_regexec(regex_t *re, const pg_wchar *string, size_t len,
+ size_t search_start, rm_detail_t *details,
+ size_t nmatch, regmatch_t pmatch[], int flags);
+extern int pg_regprefix(regex_t *re, pg_wchar **string, size_t *slength);
+extern void pg_regfree(regex_t *re);
+extern size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf,
+ size_t errbuf_size);
+
+/* regexp.c */
+extern regex_t *RE_compile_and_cache(text *text_re, int cflags, Oid collation);
+extern bool RE_compile_and_execute(text *text_re, char *dat, int dat_len,
+ int cflags, Oid collation,
+ int nmatch, regmatch_t *pmatch);
+
+#endif /* _REGEX_H_ */
diff --git a/pgsql/include/server/regex/regexport.h b/pgsql/include/server/regex/regexport.h
new file mode 100644
index 0000000000000000000000000000000000000000..8fdddc18805d34e1045a81663a9516ccb36fe348
--- /dev/null
+++ b/pgsql/include/server/regex/regexport.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * regexport.h
+ * Declarations for exporting info about a regex's NFA (nondeterministic
+ * finite automaton)
+ *
+ * The functions declared here provide accessors to extract the NFA state
+ * graph and color character sets of a successfully-compiled regex.
+ *
+ * An NFA contains one or more states, numbered 0..N-1. There is an initial
+ * state, as well as a final state --- reaching the final state denotes
+ * successful matching of an input string. Each state except the final one
+ * has some out-arcs that lead to successor states, each arc being labeled
+ * with a color that represents one or more concrete character codes.
+ * (The colors of a state's out-arcs need not be distinct, since this is an
+ * NFA not a DFA.) There are also "pseudocolors" representing start/end of
+ * line and start/end of string. Colors are numbered 0..C-1, but note that
+ * color 0 is "white" (all unused characters) and can generally be ignored.
+ *
+ * Portions Copyright (c) 2013-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1998, 1999 Henry Spencer
+ *
+ * IDENTIFICATION
+ * src/include/regex/regexport.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _REGEXPORT_H_
+#define _REGEXPORT_H_
+
+#include "regex/regex.h"
+
+/* These macros must match corresponding ones in regguts.h: */
+#define COLOR_WHITE 0 /* color for chars not appearing in regex */
+#define COLOR_RAINBOW (-2) /* represents all colors except pseudocolors */
+
+/* information about one arc of a regex's NFA */
+typedef struct
+{
+ int co; /* label (character-set color) of arc */
+ int to; /* next state number */
+} regex_arc_t;
+
+
+/* Functions for gathering information about NFA states and arcs */
+extern int pg_reg_getnumstates(const regex_t *regex);
+extern int pg_reg_getinitialstate(const regex_t *regex);
+extern int pg_reg_getfinalstate(const regex_t *regex);
+extern int pg_reg_getnumoutarcs(const regex_t *regex, int st);
+extern void pg_reg_getoutarcs(const regex_t *regex, int st,
+ regex_arc_t *arcs, int arcs_len);
+
+/* Functions for gathering information about colors */
+extern int pg_reg_getnumcolors(const regex_t *regex);
+extern int pg_reg_colorisbegin(const regex_t *regex, int co);
+extern int pg_reg_colorisend(const regex_t *regex, int co);
+extern int pg_reg_getnumcharacters(const regex_t *regex, int co);
+extern void pg_reg_getcharacters(const regex_t *regex, int co,
+ pg_wchar *chars, int chars_len);
+
+#endif /* _REGEXPORT_H_ */
diff --git a/pgsql/include/server/regex/regguts.h b/pgsql/include/server/regex/regguts.h
new file mode 100644
index 0000000000000000000000000000000000000000..3ca3647e118ea7ace436e3d39273fbda05f69236
--- /dev/null
+++ b/pgsql/include/server/regex/regguts.h
@@ -0,0 +1,548 @@
+/*
+ * Internal interface definitions, etc., for the reg package
+ *
+ * Copyright (c) 1998, 1999 Henry Spencer. All rights reserved.
+ *
+ * Development of this software was funded, in part, by Cray Research Inc.,
+ * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics
+ * Corporation, none of whom are responsible for the results. The author
+ * thanks all of them.
+ *
+ * Redistribution and use in source and binary forms -- with or without
+ * modification -- are permitted for any purpose, provided that
+ * redistributions in source form retain this entire copyright notice and
+ * indicate the origin and nature of any modifications.
+ *
+ * I'd appreciate being given credit for this package in the documentation
+ * of software which uses it, but that is not a requirement.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+ * HENRY SPENCER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * src/include/regex/regguts.h
+ */
+
+
+
+/*
+ * Environmental customization. It should not (I hope) be necessary to
+ * alter the file you are now reading -- regcustom.h should handle it all,
+ * given care here and elsewhere.
+ */
+#include "regcustom.h"
+
+
+
+/*
+ * Things that regcustom.h might override.
+ */
+
+/* assertions */
+#ifndef assert
+#ifndef REG_DEBUG
+#define NDEBUG /* no assertions */
+#endif
+#include
+#endif
+
+/* voids */
+#ifndef DISCARD
+#define DISCARD void /* for throwing values away */
+#endif
+#ifndef VS
+#define VS(x) ((void *)(x)) /* cast something to generic ptr */
+#endif
+
+/* function-pointer declarator */
+#ifndef FUNCPTR
+#define FUNCPTR(name, args) (*(name)) args
+#endif
+
+/* memory allocation */
+#ifndef MALLOC
+#define MALLOC(n) malloc(n)
+#endif
+#ifndef REALLOC
+#define REALLOC(p, n) realloc(VS(p), n)
+#endif
+#ifndef FREE
+#define FREE(p) free(VS(p))
+#endif
+
+/* interruption */
+#ifndef INTERRUPT
+#define INTERRUPT(re)
+#endif
+
+/* want size of a char in bits, and max value in bounded quantifiers */
+#ifndef _POSIX2_RE_DUP_MAX
+#define _POSIX2_RE_DUP_MAX 255 /* normally from */
+#endif
+
+
+
+/*
+ * misc
+ */
+
+#define NOTREACHED 0
+
+#define DUPMAX _POSIX2_RE_DUP_MAX
+#define DUPINF (DUPMAX+1)
+
+#define REMAGIC 0xfed7 /* magic number for main struct */
+
+/* Type codes for lookaround constraints */
+#define LATYPE_AHEAD_POS 03 /* positive lookahead */
+#define LATYPE_AHEAD_NEG 02 /* negative lookahead */
+#define LATYPE_BEHIND_POS 01 /* positive lookbehind */
+#define LATYPE_BEHIND_NEG 00 /* negative lookbehind */
+#define LATYPE_IS_POS(la) ((la) & 01)
+#define LATYPE_IS_AHEAD(la) ((la) & 02)
+
+
+/*
+ * debugging facilities
+ */
+#ifdef REG_DEBUG
+/* FDEBUG does finite-state tracing */
+#define FDEBUG(arglist) { if (v->eflags®_FTRACE) printf arglist; }
+/* MDEBUG does higher-level tracing */
+#define MDEBUG(arglist) { if (v->eflags®_MTRACE) printf arglist; }
+#else
+#define FDEBUG(arglist) {}
+#define MDEBUG(arglist) {}
+#endif
+
+
+
+/*
+ * bitmap manipulation
+ */
+#define UBITS (CHAR_BIT * sizeof(unsigned))
+#define BSET(uv, sn) ((uv)[(sn)/UBITS] |= (unsigned)1 << ((sn)%UBITS))
+#define ISBSET(uv, sn) ((uv)[(sn)/UBITS] & ((unsigned)1 << ((sn)%UBITS)))
+
+
+/*
+ * known character classes
+ */
+enum char_classes
+{
+ CC_ALNUM, CC_ALPHA, CC_ASCII, CC_BLANK, CC_CNTRL, CC_DIGIT, CC_GRAPH,
+ CC_LOWER, CC_PRINT, CC_PUNCT, CC_SPACE, CC_UPPER, CC_XDIGIT, CC_WORD
+};
+
+#define NUM_CCLASSES 14
+
+
+/*
+ * As soon as possible, we map chrs into equivalence classes -- "colors" --
+ * which are of much more manageable number.
+ *
+ * To further reduce the number of arcs in NFAs and DFAs, we also have a
+ * special RAINBOW "color" that can be assigned to an arc. This is not a
+ * real color, in that it has no entry in color maps.
+ */
+typedef short color; /* colors of characters */
+
+#define MAX_COLOR 32767 /* max color (must fit in 'color' datatype) */
+#define COLORLESS (-1) /* impossible color */
+#define RAINBOW (-2) /* represents all colors except pseudocolors */
+#define WHITE 0 /* default color, parent of all others */
+/* Note: various places in the code know that WHITE is zero */
+
+
+/*
+ * Per-color data structure for the compile-time color machinery
+ *
+ * If "sub" is not NOSUB then it is the number of the color's current
+ * subcolor, i.e. we are in process of dividing this color (character
+ * equivalence class) into two colors. See src/backend/regex/README for
+ * discussion of subcolors.
+ *
+ * Currently-unused colors have the FREECOL bit set and are linked into a
+ * freelist using their "sub" fields, but only if their color numbers are
+ * less than colormap.max. Any array entries beyond "max" are just garbage.
+ */
+struct colordesc
+{
+ int nschrs; /* number of simple chars of this color */
+ int nuchrs; /* number of upper map entries of this color */
+ color sub; /* open subcolor, if any; or free-chain ptr */
+#define NOSUB COLORLESS /* value of "sub" when no open subcolor */
+ struct arc *arcs; /* chain of all arcs of this color */
+ chr firstchr; /* simple char first assigned to this color */
+ int flags; /* bitmask of the following flags: */
+#define FREECOL 01 /* currently free */
+#define PSEUDO 02 /* pseudocolor, no real chars */
+#define COLMARK 04 /* temporary marker used in some functions */
+};
+
+#define UNUSEDCOLOR(cd) ((cd)->flags & FREECOL)
+
+/*
+ * The color map itself
+ *
+ * This struct holds both data used only at compile time, and the chr to
+ * color mapping information, used at both compile and run time. The latter
+ * is the bulk of the space, so it's not really worth separating out the
+ * compile-only portion.
+ *
+ * Ideally, the mapping data would just be an array of colors indexed by
+ * chr codes; but for large character sets that's impractical. Fortunately,
+ * common characters have smaller codes, so we can use a simple array for chr
+ * codes up to MAX_SIMPLE_CHR, and do something more complex for codes above
+ * that, without much loss of performance. The "something more complex" is a
+ * 2-D array of color entries, where row indexes correspond to individual chrs
+ * or chr ranges that have been mentioned in the regex (with row zero
+ * representing all other chrs), and column indexes correspond to different
+ * sets of locale-dependent character classes such as "isalpha". The
+ * classbits[k] entry is zero if we do not care about the k'th character class
+ * in this regex, and otherwise it is the bit to be OR'd into the column index
+ * if the character in question is a member of that class. We find the color
+ * of a high-valued chr by identifying which colormaprange it is in to get
+ * the row index (use row zero if it's in none of them), identifying which of
+ * the interesting cclasses it's in to get the column index, and then indexing
+ * into the 2-D hicolormap array.
+ *
+ * The colormapranges are required to be nonempty, nonoverlapping, and to
+ * appear in increasing chr-value order.
+ */
+
+typedef struct colormaprange
+{
+ chr cmin; /* range represents cmin..cmax inclusive */
+ chr cmax;
+ int rownum; /* row index in hicolormap array (>= 1) */
+} colormaprange;
+
+struct colormap
+{
+ int magic;
+#define CMMAGIC 0x876
+ struct vars *v; /* for compile error reporting */
+ size_t ncds; /* allocated length of colordescs array */
+ size_t max; /* highest color number currently in use */
+ color free; /* beginning of free chain (if non-0) */
+ struct colordesc *cd; /* pointer to array of colordescs */
+#define CDEND(cm) (&(cm)->cd[(cm)->max + 1])
+
+ /* mapping data for chrs <= MAX_SIMPLE_CHR: */
+ color *locolormap; /* simple array indexed by chr code */
+
+ /* mapping data for chrs > MAX_SIMPLE_CHR: */
+ int classbits[NUM_CCLASSES]; /* see comment above */
+ int numcmranges; /* number of colormapranges */
+ colormaprange *cmranges; /* ranges of high chrs */
+ color *hicolormap; /* 2-D array of color entries */
+ int maxarrayrows; /* number of array rows allocated */
+ int hiarrayrows; /* number of array rows in use */
+ int hiarraycols; /* number of array columns (2^N) */
+
+ /* If we need up to NINLINECDS, we store them here to save a malloc */
+#define NINLINECDS ((size_t) 10)
+ struct colordesc cdspace[NINLINECDS];
+};
+
+/* fetch color for chr; beware of multiple evaluation of c argument */
+#define GETCOLOR(cm, c) \
+ ((c) <= MAX_SIMPLE_CHR ? (cm)->locolormap[(c) - CHR_MIN] : pg_reg_getcolor(cm, c))
+
+
+/*
+ * Interface definitions for locale-interface functions in regc_locale.c.
+ */
+
+/*
+ * Representation of a set of characters. chrs[] represents individual
+ * code points, ranges[] represents ranges in the form min..max inclusive.
+ *
+ * If the cvec represents a locale-specific character class, eg [[:alpha:]],
+ * then the chrs[] and ranges[] arrays contain only members of that class
+ * up to MAX_SIMPLE_CHR (inclusive). cclasscode is set to regc_locale.c's
+ * code for the class, rather than being -1 as it is in an ordinary cvec.
+ *
+ * Note that in cvecs gotten from newcvec() and intended to be freed by
+ * freecvec(), both arrays of chrs are after the end of the struct, not
+ * separately malloc'd; so chrspace and rangespace are effectively immutable.
+ */
+struct cvec
+{
+ int nchrs; /* number of chrs */
+ int chrspace; /* number of chrs allocated in chrs[] */
+ chr *chrs; /* pointer to vector of chrs */
+ int nranges; /* number of ranges (chr pairs) */
+ int rangespace; /* number of ranges allocated in ranges[] */
+ chr *ranges; /* pointer to vector of chr pairs */
+ int cclasscode; /* value of "enum classes", or -1 */
+};
+
+
+/*
+ * definitions for NFA internal representation
+ */
+struct state;
+
+struct arc
+{
+ int type; /* 0 if free, else an NFA arc type code */
+ color co; /* color the arc matches (possibly RAINBOW) */
+ struct state *from; /* where it's from */
+ struct state *to; /* where it's to */
+ struct arc *outchain; /* link in *from's outs chain or free chain */
+ struct arc *outchainRev; /* back-link in *from's outs chain */
+#define freechain outchain /* we do not maintain "freechainRev" */
+ struct arc *inchain; /* link in *to's ins chain */
+ struct arc *inchainRev; /* back-link in *to's ins chain */
+ /* these fields are not used when co == RAINBOW: */
+ struct arc *colorchain; /* link in color's arc chain */
+ struct arc *colorchainRev; /* back-link in color's arc chain */
+};
+
+struct arcbatch
+{ /* for bulk allocation of arcs */
+ struct arcbatch *next; /* chain link */
+ size_t narcs; /* number of arcs allocated in this arcbatch */
+ struct arc a[FLEXIBLE_ARRAY_MEMBER];
+};
+#define ARCBATCHSIZE(n) ((n) * sizeof(struct arc) + offsetof(struct arcbatch, a))
+/* first batch will have FIRSTABSIZE arcs; then double it until MAXABSIZE */
+#define FIRSTABSIZE 64
+#define MAXABSIZE 1024
+
+struct state
+{
+ int no; /* state number, zero and up; or FREESTATE */
+#define FREESTATE (-1)
+ char flag; /* marks special states */
+ int nins; /* number of inarcs */
+ int nouts; /* number of outarcs */
+ struct arc *ins; /* chain of inarcs */
+ struct arc *outs; /* chain of outarcs */
+ struct state *tmp; /* temporary for traversal algorithms */
+ struct state *next; /* chain for traversing all live states */
+ /* the "next" field is also used to chain free states together */
+ struct state *prev; /* back-link in chain of all live states */
+};
+
+struct statebatch
+{ /* for bulk allocation of states */
+ struct statebatch *next; /* chain link */
+ size_t nstates; /* number of states allocated in this batch */
+ struct state s[FLEXIBLE_ARRAY_MEMBER];
+};
+#define STATEBATCHSIZE(n) ((n) * sizeof(struct state) + offsetof(struct statebatch, s))
+/* first batch will have FIRSTSBSIZE states; then double it until MAXSBSIZE */
+#define FIRSTSBSIZE 32
+#define MAXSBSIZE 1024
+
+struct nfa
+{
+ struct state *pre; /* pre-initial state */
+ struct state *init; /* initial state */
+ struct state *final; /* final state */
+ struct state *post; /* post-final state */
+ int nstates; /* for numbering states */
+ struct state *states; /* chain of live states */
+ struct state *slast; /* tail of the chain */
+ struct state *freestates; /* chain of free states */
+ struct arc *freearcs; /* chain of free arcs */
+ struct statebatch *lastsb; /* chain of statebatches */
+ struct arcbatch *lastab; /* chain of arcbatches */
+ size_t lastsbused; /* number of states consumed from *lastsb */
+ size_t lastabused; /* number of arcs consumed from *lastab */
+ struct colormap *cm; /* the color map */
+ color bos[2]; /* colors, if any, assigned to BOS and BOL */
+ color eos[2]; /* colors, if any, assigned to EOS and EOL */
+ int flags; /* flags to pass forward to cNFA */
+ int minmatchall; /* min number of chrs to match, if matchall */
+ int maxmatchall; /* max number of chrs to match, or DUPINF */
+ struct vars *v; /* simplifies compile error reporting */
+ struct nfa *parent; /* parent NFA, if any */
+};
+
+
+
+/*
+ * definitions for compacted NFA
+ *
+ * The main space savings in a compacted NFA is from making the arcs as small
+ * as possible. We store only the transition color and next-state number for
+ * each arc. The list of out arcs for each state is an array beginning at
+ * cnfa.states[statenumber], and terminated by a dummy carc struct with
+ * co == COLORLESS.
+ *
+ * The non-dummy carc structs are of two types: plain arcs and LACON arcs.
+ * Plain arcs just store the transition color number as "co". LACON arcs
+ * store the lookaround constraint number plus cnfa.ncolors as "co". LACON
+ * arcs can be distinguished from plain by testing for co >= cnfa.ncolors.
+ *
+ * Note that in a plain arc, "co" can be RAINBOW; since that's negative,
+ * it doesn't break the rule about how to recognize LACON arcs.
+ *
+ * We have special markings for "trivial" NFAs that can match any string
+ * (possibly with limits on the number of characters therein). In such a
+ * case, flags & MATCHALL is set (and HASLACONS can't be set). Then the
+ * fields minmatchall and maxmatchall give the minimum and maximum numbers
+ * of characters to match. For example, ".*" produces minmatchall = 0
+ * and maxmatchall = DUPINF, while ".+" produces minmatchall = 1 and
+ * maxmatchall = DUPINF.
+ */
+struct carc
+{
+ color co; /* COLORLESS is list terminator */
+ int to; /* next-state number */
+};
+
+struct cnfa
+{
+ int nstates; /* number of states */
+ int ncolors; /* number of colors (max color in use + 1) */
+ int flags; /* bitmask of the following flags: */
+#define HASLACONS 01 /* uses lookaround constraints */
+#define MATCHALL 02 /* matches all strings of a range of lengths */
+ int pre; /* setup state number */
+ int post; /* teardown state number */
+ color bos[2]; /* colors, if any, assigned to BOS and BOL */
+ color eos[2]; /* colors, if any, assigned to EOS and EOL */
+ char *stflags; /* vector of per-state flags bytes */
+#define CNFA_NOPROGRESS 01 /* flag bit for a no-progress state */
+ struct carc **states; /* vector of pointers to outarc lists */
+ /* states[n] are pointers into a single malloc'd array of arcs */
+ struct carc *arcs; /* the area for the lists */
+ /* these fields are used only in a MATCHALL NFA (else they're -1): */
+ int minmatchall; /* min number of chrs to match */
+ int maxmatchall; /* max number of chrs to match, or DUPINF */
+};
+
+/*
+ * When debugging, it's helpful if an un-filled CNFA is all-zeroes.
+ * In production, though, we only require nstates to be zero.
+ */
+#ifdef REG_DEBUG
+#define ZAPCNFA(cnfa) memset(&(cnfa), 0, sizeof(cnfa))
+#else
+#define ZAPCNFA(cnfa) ((cnfa).nstates = 0)
+#endif
+#define NULLCNFA(cnfa) ((cnfa).nstates == 0)
+
+/*
+ * This symbol limits the transient heap space used by the regex compiler,
+ * and thereby also the maximum complexity of NFAs that we'll deal with.
+ * Currently we only count NFA states and arcs against this; the other
+ * transient data is generally not large enough to notice compared to those.
+ * Note that we do not charge anything for the final output data structures
+ * (the compacted NFA and the colormap).
+ * The scaling here is based on an empirical measurement that very large
+ * NFAs tend to have about 4 arcs/state.
+ */
+#ifndef REG_MAX_COMPILE_SPACE
+#define REG_MAX_COMPILE_SPACE \
+ (500000 * (sizeof(struct state) + 4 * sizeof(struct arc)))
+#endif
+
+/*
+ * subexpression tree
+ *
+ * "op" is one of:
+ * '=' plain regex without interesting substructure (implemented as DFA)
+ * 'b' back-reference (has no substructure either)
+ * '(' no-op capture node: captures the match of its single child
+ * '.' concatenation: matches a match for first child, then second child
+ * '|' alternation: matches a match for any of its children
+ * '*' iteration: matches some number of matches of its single child
+ *
+ * An alternation node can have any number of children (but at least two),
+ * linked through their sibling fields.
+ *
+ * A concatenation node must have exactly two children. It might be useful
+ * to support more, but that would complicate the executor. Note that it is
+ * the first child's greediness that determines the node's preference for
+ * where to split a match.
+ *
+ * Note: when a backref is directly quantified, we stick the min/max counts
+ * into the backref rather than plastering an iteration node on top. This is
+ * for efficiency: there is no need to search for possible division points.
+ */
+struct subre
+{
+ char op; /* see type codes above */
+ char flags;
+#define LONGER 01 /* prefers longer match */
+#define SHORTER 02 /* prefers shorter match */
+#define MIXED 04 /* mixed preference below */
+#define CAP 010 /* capturing parens here or below */
+#define BACKR 020 /* back reference here or below */
+#define BRUSE 040 /* is referenced by a back reference */
+#define INUSE 0100 /* in use in final tree */
+#define UPPROP (MIXED|CAP|BACKR) /* flags which should propagate up */
+#define LMIX(f) ((f)<<2) /* LONGER -> MIXED */
+#define SMIX(f) ((f)<<1) /* SHORTER -> MIXED */
+#define UP(f) (((f)&UPPROP) | (LMIX(f) & SMIX(f) & MIXED))
+#define MESSY(f) ((f)&(MIXED|CAP|BACKR))
+#define PREF(f) ((f)&(LONGER|SHORTER))
+#define PREF2(f1, f2) ((PREF(f1) != 0) ? PREF(f1) : PREF(f2))
+#define COMBINE(f1, f2) (UP((f1)|(f2)) | PREF2(f1, f2))
+ char latype; /* LATYPE code, if lookaround constraint */
+ int id; /* ID of subre (1..ntree-1) */
+ int capno; /* if capture node, subno to capture into */
+ int backno; /* if backref node, subno it refers to */
+ short min; /* min repetitions for iteration or backref */
+ short max; /* max repetitions for iteration or backref */
+ struct subre *child; /* first child, if any (also freelist chain) */
+ struct subre *sibling; /* next child of same parent, if any */
+ struct state *begin; /* outarcs from here... */
+ struct state *end; /* ...ending in inarcs here */
+ struct cnfa cnfa; /* compacted NFA, if any */
+ struct subre *chain; /* for bookkeeping and error cleanup */
+};
+
+
+
+/*
+ * table of function pointers for generic manipulation functions
+ * A regex_t's re_fns points to one of these.
+ */
+struct fns
+{
+ void FUNCPTR(free, (regex_t *));
+ int FUNCPTR(stack_too_deep, (void));
+};
+
+#define STACK_TOO_DEEP(re) \
+ ((*((struct fns *) (re)->re_fns)->stack_too_deep) ())
+
+
+/*
+ * the insides of a regex_t, hidden behind a void *
+ */
+struct guts
+{
+ int magic;
+#define GUTSMAGIC 0xfed9
+ int cflags; /* copy of compile flags */
+ long info; /* copy of re_info */
+ size_t nsub; /* copy of re_nsub */
+ struct subre *tree;
+ struct cnfa search; /* for fast preliminary search */
+ int ntree; /* number of subre's, plus one */
+ struct colormap cmap;
+ int FUNCPTR(compare, (const chr *, const chr *, size_t));
+ struct subre *lacons; /* lookaround-constraint vector */
+ int nlacons; /* size of lacons[]; note that only slots
+ * numbered 1 .. nlacons-1 are used */
+};
+
+
+/* prototypes for functions that are exported from regcomp.c to regexec.c */
+extern void pg_set_regex_collation(Oid collation);
+extern color pg_reg_getcolor(struct colormap *cm, chr c);
diff --git a/pgsql/include/server/replication/decode.h b/pgsql/include/server/replication/decode.h
new file mode 100644
index 0000000000000000000000000000000000000000..14fa921ab4773acd873bc30067883090d2ebc818
--- /dev/null
+++ b/pgsql/include/server/replication/decode.h
@@ -0,0 +1,34 @@
+/*-------------------------------------------------------------------------
+ * decode.h
+ * PostgreSQL WAL to logical transformation
+ *
+ * Portions Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DECODE_H
+#define DECODE_H
+
+#include "access/xlogreader.h"
+#include "access/xlogrecord.h"
+#include "replication/logical.h"
+#include "replication/reorderbuffer.h"
+
+typedef struct XLogRecordBuffer
+{
+ XLogRecPtr origptr;
+ XLogRecPtr endptr;
+ XLogReaderState *record;
+} XLogRecordBuffer;
+
+extern void xlog_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf);
+extern void heap_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf);
+extern void heap2_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf);
+extern void xact_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf);
+extern void standby_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf);
+extern void logicalmsg_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf);
+
+extern void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx,
+ XLogReaderState *record);
+
+#endif
diff --git a/pgsql/include/server/replication/logical.h b/pgsql/include/server/replication/logical.h
new file mode 100644
index 0000000000000000000000000000000000000000..5f49554ea05336dc6c17d4b4b0175ba2c73d2003
--- /dev/null
+++ b/pgsql/include/server/replication/logical.h
@@ -0,0 +1,148 @@
+/*-------------------------------------------------------------------------
+ * logical.h
+ * PostgreSQL logical decoding coordination
+ *
+ * Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOGICAL_H
+#define LOGICAL_H
+
+#include "access/xlog.h"
+#include "access/xlogreader.h"
+#include "replication/output_plugin.h"
+#include "replication/slot.h"
+
+struct LogicalDecodingContext;
+
+typedef void (*LogicalOutputPluginWriterWrite) (struct LogicalDecodingContext *lr,
+ XLogRecPtr Ptr,
+ TransactionId xid,
+ bool last_write
+);
+
+typedef LogicalOutputPluginWriterWrite LogicalOutputPluginWriterPrepareWrite;
+
+typedef void (*LogicalOutputPluginWriterUpdateProgress) (struct LogicalDecodingContext *lr,
+ XLogRecPtr Ptr,
+ TransactionId xid,
+ bool skipped_xact
+);
+
+typedef struct LogicalDecodingContext
+{
+ /* memory context this is all allocated in */
+ MemoryContext context;
+
+ /* The associated replication slot */
+ ReplicationSlot *slot;
+
+ /* infrastructure pieces for decoding */
+ XLogReaderState *reader;
+ struct ReorderBuffer *reorder;
+ struct SnapBuild *snapshot_builder;
+
+ /*
+ * Marks the logical decoding context as fast forward decoding one. Such a
+ * context does not have plugin loaded so most of the following properties
+ * are unused.
+ */
+ bool fast_forward;
+
+ OutputPluginCallbacks callbacks;
+ OutputPluginOptions options;
+
+ /*
+ * User specified options
+ */
+ List *output_plugin_options;
+
+ /*
+ * User-Provided callback for writing/streaming out data.
+ */
+ LogicalOutputPluginWriterPrepareWrite prepare_write;
+ LogicalOutputPluginWriterWrite write;
+ LogicalOutputPluginWriterUpdateProgress update_progress;
+
+ /*
+ * Output buffer.
+ */
+ StringInfo out;
+
+ /*
+ * Private data pointer of the output plugin.
+ */
+ void *output_plugin_private;
+
+ /*
+ * Private data pointer for the data writer.
+ */
+ void *output_writer_private;
+
+ /*
+ * Does the output plugin support streaming, and is it enabled?
+ */
+ bool streaming;
+
+ /*
+ * Does the output plugin support two-phase decoding, and is it enabled?
+ */
+ bool twophase;
+
+ /*
+ * Is two-phase option given by output plugin?
+ *
+ * This flag indicates that the plugin passed in the two-phase option as
+ * part of the START_STREAMING command. We can't rely solely on the
+ * twophase flag which only tells whether the plugin provided all the
+ * necessary two-phase callbacks.
+ */
+ bool twophase_opt_given;
+
+ /*
+ * State for writing output.
+ */
+ bool accept_writes;
+ bool prepared_write;
+ XLogRecPtr write_location;
+ TransactionId write_xid;
+ /* Are we processing the end LSN of a transaction? */
+ bool end_xact;
+} LogicalDecodingContext;
+
+
+extern void CheckLogicalDecodingRequirements(void);
+
+extern LogicalDecodingContext *CreateInitDecodingContext(const char *plugin,
+ List *output_plugin_options,
+ bool need_full_snapshot,
+ XLogRecPtr restart_lsn,
+ XLogReaderRoutine *xl_routine,
+ LogicalOutputPluginWriterPrepareWrite prepare_write,
+ LogicalOutputPluginWriterWrite do_write,
+ LogicalOutputPluginWriterUpdateProgress update_progress);
+extern LogicalDecodingContext *CreateDecodingContext(XLogRecPtr start_lsn,
+ List *output_plugin_options,
+ bool fast_forward,
+ XLogReaderRoutine *xl_routine,
+ LogicalOutputPluginWriterPrepareWrite prepare_write,
+ LogicalOutputPluginWriterWrite do_write,
+ LogicalOutputPluginWriterUpdateProgress update_progress);
+extern void DecodingContextFindStartpoint(LogicalDecodingContext *ctx);
+extern bool DecodingContextReady(LogicalDecodingContext *ctx);
+extern void FreeDecodingContext(LogicalDecodingContext *ctx);
+
+extern void LogicalIncreaseXminForSlot(XLogRecPtr current_lsn,
+ TransactionId xmin);
+extern void LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn,
+ XLogRecPtr restart_lsn);
+extern void LogicalConfirmReceivedLocation(XLogRecPtr lsn);
+
+extern bool filter_prepare_cb_wrapper(LogicalDecodingContext *ctx,
+ TransactionId xid, const char *gid);
+extern bool filter_by_origin_cb_wrapper(LogicalDecodingContext *ctx, RepOriginId origin_id);
+extern void ResetLogicalStreamingState(void);
+extern void UpdateDecodingStats(LogicalDecodingContext *ctx);
+
+#endif
diff --git a/pgsql/include/server/replication/logicallauncher.h b/pgsql/include/server/replication/logicallauncher.h
new file mode 100644
index 0000000000000000000000000000000000000000..a07c9cb311a75c895a6dfb941e8034f7e0793f7f
--- /dev/null
+++ b/pgsql/include/server/replication/logicallauncher.h
@@ -0,0 +1,34 @@
+/*-------------------------------------------------------------------------
+ *
+ * logicallauncher.h
+ * Exports for logical replication launcher.
+ *
+ * Portions Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/logicallauncher.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOGICALLAUNCHER_H
+#define LOGICALLAUNCHER_H
+
+extern PGDLLIMPORT int max_logical_replication_workers;
+extern PGDLLIMPORT int max_sync_workers_per_subscription;
+extern PGDLLIMPORT int max_parallel_apply_workers_per_subscription;
+
+extern void ApplyLauncherRegister(void);
+extern void ApplyLauncherMain(Datum main_arg);
+
+extern Size ApplyLauncherShmemSize(void);
+extern void ApplyLauncherShmemInit(void);
+
+extern void ApplyLauncherForgetWorkerStartTime(Oid subid);
+
+extern void ApplyLauncherWakeupAtCommit(void);
+extern void AtEOXact_ApplyLauncher(bool isCommit);
+
+extern bool IsLogicalLauncher(void);
+
+extern pid_t GetLeaderApplyWorkerPid(pid_t pid);
+
+#endif /* LOGICALLAUNCHER_H */
diff --git a/pgsql/include/server/replication/logicalproto.h b/pgsql/include/server/replication/logicalproto.h
new file mode 100644
index 0000000000000000000000000000000000000000..c5be981eae66e272747ef129e6e4dc1fcc38c2a0
--- /dev/null
+++ b/pgsql/include/server/replication/logicalproto.h
@@ -0,0 +1,274 @@
+/*-------------------------------------------------------------------------
+ *
+ * logicalproto.h
+ * logical replication protocol
+ *
+ * Copyright (c) 2015-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/replication/logicalproto.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOGICAL_PROTO_H
+#define LOGICAL_PROTO_H
+
+#include "access/xact.h"
+#include "executor/tuptable.h"
+#include "replication/reorderbuffer.h"
+#include "utils/rel.h"
+
+/*
+ * Protocol capabilities
+ *
+ * LOGICALREP_PROTO_VERSION_NUM is our native protocol.
+ * LOGICALREP_PROTO_MAX_VERSION_NUM is the greatest version we can support.
+ * LOGICALREP_PROTO_MIN_VERSION_NUM is the oldest version we
+ * have backwards compatibility for. The client requests protocol version at
+ * connect time.
+ *
+ * LOGICALREP_PROTO_STREAM_VERSION_NUM is the minimum protocol version with
+ * support for streaming large transactions. Introduced in PG14.
+ *
+ * LOGICALREP_PROTO_TWOPHASE_VERSION_NUM is the minimum protocol version with
+ * support for two-phase commit decoding (at prepare time). Introduced in PG15.
+ *
+ * LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM is the minimum protocol version
+ * where we support applying large streaming transactions in parallel.
+ * Introduced in PG16.
+ */
+#define LOGICALREP_PROTO_MIN_VERSION_NUM 1
+#define LOGICALREP_PROTO_VERSION_NUM 1
+#define LOGICALREP_PROTO_STREAM_VERSION_NUM 2
+#define LOGICALREP_PROTO_TWOPHASE_VERSION_NUM 3
+#define LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM 4
+#define LOGICALREP_PROTO_MAX_VERSION_NUM LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM
+
+/*
+ * Logical message types
+ *
+ * Used by logical replication wire protocol.
+ *
+ * Note: though this is an enum, the values are used to identify message types
+ * in logical replication protocol, which uses a single byte to identify a
+ * message type. Hence the values should be single-byte wide and preferably
+ * human-readable characters.
+ */
+typedef enum LogicalRepMsgType
+{
+ LOGICAL_REP_MSG_BEGIN = 'B',
+ LOGICAL_REP_MSG_COMMIT = 'C',
+ LOGICAL_REP_MSG_ORIGIN = 'O',
+ LOGICAL_REP_MSG_INSERT = 'I',
+ LOGICAL_REP_MSG_UPDATE = 'U',
+ LOGICAL_REP_MSG_DELETE = 'D',
+ LOGICAL_REP_MSG_TRUNCATE = 'T',
+ LOGICAL_REP_MSG_RELATION = 'R',
+ LOGICAL_REP_MSG_TYPE = 'Y',
+ LOGICAL_REP_MSG_MESSAGE = 'M',
+ LOGICAL_REP_MSG_BEGIN_PREPARE = 'b',
+ LOGICAL_REP_MSG_PREPARE = 'P',
+ LOGICAL_REP_MSG_COMMIT_PREPARED = 'K',
+ LOGICAL_REP_MSG_ROLLBACK_PREPARED = 'r',
+ LOGICAL_REP_MSG_STREAM_START = 'S',
+ LOGICAL_REP_MSG_STREAM_STOP = 'E',
+ LOGICAL_REP_MSG_STREAM_COMMIT = 'c',
+ LOGICAL_REP_MSG_STREAM_ABORT = 'A',
+ LOGICAL_REP_MSG_STREAM_PREPARE = 'p'
+} LogicalRepMsgType;
+
+/*
+ * This struct stores a tuple received via logical replication.
+ * Keep in mind that the columns correspond to the *remote* table.
+ */
+typedef struct LogicalRepTupleData
+{
+ /* Array of StringInfos, one per column; some may be unused */
+ StringInfoData *colvalues;
+ /* Array of markers for null/unchanged/text/binary, one per column */
+ char *colstatus;
+ /* Length of above arrays */
+ int ncols;
+} LogicalRepTupleData;
+
+/* Possible values for LogicalRepTupleData.colstatus[colnum] */
+/* These values are also used in the on-the-wire protocol */
+#define LOGICALREP_COLUMN_NULL 'n'
+#define LOGICALREP_COLUMN_UNCHANGED 'u'
+#define LOGICALREP_COLUMN_TEXT 't'
+#define LOGICALREP_COLUMN_BINARY 'b' /* added in PG14 */
+
+typedef uint32 LogicalRepRelId;
+
+/* Relation information */
+typedef struct LogicalRepRelation
+{
+ /* Info coming from the remote side. */
+ LogicalRepRelId remoteid; /* unique id of the relation */
+ char *nspname; /* schema name */
+ char *relname; /* relation name */
+ int natts; /* number of columns */
+ char **attnames; /* column names */
+ Oid *atttyps; /* column types */
+ char replident; /* replica identity */
+ char relkind; /* remote relation kind */
+ Bitmapset *attkeys; /* Bitmap of key columns */
+} LogicalRepRelation;
+
+/* Type mapping info */
+typedef struct LogicalRepTyp
+{
+ Oid remoteid; /* unique id of the remote type */
+ char *nspname; /* schema name of remote type */
+ char *typname; /* name of the remote type */
+} LogicalRepTyp;
+
+/* Transaction info */
+typedef struct LogicalRepBeginData
+{
+ XLogRecPtr final_lsn;
+ TimestampTz committime;
+ TransactionId xid;
+} LogicalRepBeginData;
+
+typedef struct LogicalRepCommitData
+{
+ XLogRecPtr commit_lsn;
+ XLogRecPtr end_lsn;
+ TimestampTz committime;
+} LogicalRepCommitData;
+
+/*
+ * Prepared transaction protocol information for begin_prepare, and prepare.
+ */
+typedef struct LogicalRepPreparedTxnData
+{
+ XLogRecPtr prepare_lsn;
+ XLogRecPtr end_lsn;
+ TimestampTz prepare_time;
+ TransactionId xid;
+ char gid[GIDSIZE];
+} LogicalRepPreparedTxnData;
+
+/*
+ * Prepared transaction protocol information for commit prepared.
+ */
+typedef struct LogicalRepCommitPreparedTxnData
+{
+ XLogRecPtr commit_lsn;
+ XLogRecPtr end_lsn;
+ TimestampTz commit_time;
+ TransactionId xid;
+ char gid[GIDSIZE];
+} LogicalRepCommitPreparedTxnData;
+
+/*
+ * Rollback Prepared transaction protocol information. The prepare information
+ * prepare_end_lsn and prepare_time are used to check if the downstream has
+ * received this prepared transaction in which case it can apply the rollback,
+ * otherwise, it can skip the rollback operation. The gid alone is not
+ * sufficient because the downstream node can have a prepared transaction with
+ * same identifier.
+ */
+typedef struct LogicalRepRollbackPreparedTxnData
+{
+ XLogRecPtr prepare_end_lsn;
+ XLogRecPtr rollback_end_lsn;
+ TimestampTz prepare_time;
+ TimestampTz rollback_time;
+ TransactionId xid;
+ char gid[GIDSIZE];
+} LogicalRepRollbackPreparedTxnData;
+
+/*
+ * Transaction protocol information for stream abort.
+ */
+typedef struct LogicalRepStreamAbortData
+{
+ TransactionId xid;
+ TransactionId subxid;
+ XLogRecPtr abort_lsn;
+ TimestampTz abort_time;
+} LogicalRepStreamAbortData;
+
+extern void logicalrep_write_begin(StringInfo out, ReorderBufferTXN *txn);
+extern void logicalrep_read_begin(StringInfo in,
+ LogicalRepBeginData *begin_data);
+extern void logicalrep_write_commit(StringInfo out, ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+extern void logicalrep_read_commit(StringInfo in,
+ LogicalRepCommitData *commit_data);
+extern void logicalrep_write_begin_prepare(StringInfo out, ReorderBufferTXN *txn);
+extern void logicalrep_read_begin_prepare(StringInfo in,
+ LogicalRepPreparedTxnData *begin_data);
+extern void logicalrep_write_prepare(StringInfo out, ReorderBufferTXN *txn,
+ XLogRecPtr prepare_lsn);
+extern void logicalrep_read_prepare(StringInfo in,
+ LogicalRepPreparedTxnData *prepare_data);
+extern void logicalrep_write_commit_prepared(StringInfo out, ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+extern void logicalrep_read_commit_prepared(StringInfo in,
+ LogicalRepCommitPreparedTxnData *prepare_data);
+extern void logicalrep_write_rollback_prepared(StringInfo out, ReorderBufferTXN *txn,
+ XLogRecPtr prepare_end_lsn,
+ TimestampTz prepare_time);
+extern void logicalrep_read_rollback_prepared(StringInfo in,
+ LogicalRepRollbackPreparedTxnData *rollback_data);
+extern void logicalrep_write_stream_prepare(StringInfo out, ReorderBufferTXN *txn,
+ XLogRecPtr prepare_lsn);
+extern void logicalrep_read_stream_prepare(StringInfo in,
+ LogicalRepPreparedTxnData *prepare_data);
+
+extern void logicalrep_write_origin(StringInfo out, const char *origin,
+ XLogRecPtr origin_lsn);
+extern char *logicalrep_read_origin(StringInfo in, XLogRecPtr *origin_lsn);
+extern void logicalrep_write_insert(StringInfo out, TransactionId xid,
+ Relation rel,
+ TupleTableSlot *newslot,
+ bool binary, Bitmapset *columns);
+extern LogicalRepRelId logicalrep_read_insert(StringInfo in, LogicalRepTupleData *newtup);
+extern void logicalrep_write_update(StringInfo out, TransactionId xid,
+ Relation rel,
+ TupleTableSlot *oldslot,
+ TupleTableSlot *newslot, bool binary, Bitmapset *columns);
+extern LogicalRepRelId logicalrep_read_update(StringInfo in,
+ bool *has_oldtuple, LogicalRepTupleData *oldtup,
+ LogicalRepTupleData *newtup);
+extern void logicalrep_write_delete(StringInfo out, TransactionId xid,
+ Relation rel, TupleTableSlot *oldslot,
+ bool binary, Bitmapset *columns);
+extern LogicalRepRelId logicalrep_read_delete(StringInfo in,
+ LogicalRepTupleData *oldtup);
+extern void logicalrep_write_truncate(StringInfo out, TransactionId xid,
+ int nrelids, Oid relids[],
+ bool cascade, bool restart_seqs);
+extern List *logicalrep_read_truncate(StringInfo in,
+ bool *cascade, bool *restart_seqs);
+extern void logicalrep_write_message(StringInfo out, TransactionId xid, XLogRecPtr lsn,
+ bool transactional, const char *prefix, Size sz, const char *message);
+extern void logicalrep_write_rel(StringInfo out, TransactionId xid,
+ Relation rel, Bitmapset *columns);
+extern LogicalRepRelation *logicalrep_read_rel(StringInfo in);
+extern void logicalrep_write_typ(StringInfo out, TransactionId xid,
+ Oid typoid);
+extern void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp);
+extern void logicalrep_write_stream_start(StringInfo out, TransactionId xid,
+ bool first_segment);
+extern TransactionId logicalrep_read_stream_start(StringInfo in,
+ bool *first_segment);
+extern void logicalrep_write_stream_stop(StringInfo out);
+extern void logicalrep_write_stream_commit(StringInfo out, ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+extern TransactionId logicalrep_read_stream_commit(StringInfo in,
+ LogicalRepCommitData *commit_data);
+extern void logicalrep_write_stream_abort(StringInfo out, TransactionId xid,
+ TransactionId subxid,
+ XLogRecPtr abort_lsn,
+ TimestampTz abort_time,
+ bool write_abort_info);
+extern void logicalrep_read_stream_abort(StringInfo in,
+ LogicalRepStreamAbortData *abort_data,
+ bool read_abort_info);
+extern const char *logicalrep_message_type(LogicalRepMsgType action);
+
+#endif /* LOGICAL_PROTO_H */
diff --git a/pgsql/include/server/replication/logicalrelation.h b/pgsql/include/server/replication/logicalrelation.h
new file mode 100644
index 0000000000000000000000000000000000000000..3f4d906d7416b138329765f11a8a24e0770632e5
--- /dev/null
+++ b/pgsql/include/server/replication/logicalrelation.h
@@ -0,0 +1,54 @@
+/*-------------------------------------------------------------------------
+ *
+ * logicalrelation.h
+ * Relation definitions for logical replication relation mapping.
+ *
+ * Portions Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/logicalrelation.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOGICALRELATION_H
+#define LOGICALRELATION_H
+
+#include "access/attmap.h"
+#include "catalog/index.h"
+#include "replication/logicalproto.h"
+
+typedef struct LogicalRepRelMapEntry
+{
+ LogicalRepRelation remoterel; /* key is remoterel.remoteid */
+
+ /*
+ * Validity flag -- when false, revalidate all derived info at next
+ * logicalrep_rel_open. (While the localrel is open, we assume our lock
+ * on that rel ensures the info remains good.)
+ */
+ bool localrelvalid;
+
+ /* Mapping to local relation. */
+ Oid localreloid; /* local relation id */
+ Relation localrel; /* relcache entry (NULL when closed) */
+ AttrMap *attrmap; /* map of local attributes to remote ones */
+ bool updatable; /* Can apply updates/deletes? */
+ Oid localindexoid; /* which index to use, or InvalidOid if none */
+
+ /* Sync state. */
+ char state;
+ XLogRecPtr statelsn;
+} LogicalRepRelMapEntry;
+
+extern void logicalrep_relmap_update(LogicalRepRelation *remoterel);
+extern void logicalrep_partmap_reset_relmap(LogicalRepRelation *remoterel);
+
+extern LogicalRepRelMapEntry *logicalrep_rel_open(LogicalRepRelId remoteid,
+ LOCKMODE lockmode);
+extern LogicalRepRelMapEntry *logicalrep_partition_open(LogicalRepRelMapEntry *root,
+ Relation partrel, AttrMap *map);
+extern void logicalrep_rel_close(LogicalRepRelMapEntry *rel,
+ LOCKMODE lockmode);
+extern bool IsIndexUsableForReplicaIdentityFull(IndexInfo *indexInfo, AttrMap *attrmap);
+extern Oid GetRelationIdentityOrPK(Relation rel);
+
+#endif /* LOGICALRELATION_H */
diff --git a/pgsql/include/server/replication/logicalworker.h b/pgsql/include/server/replication/logicalworker.h
new file mode 100644
index 0000000000000000000000000000000000000000..39588da79fd54f3e8a3ff525795592964cafe1a2
--- /dev/null
+++ b/pgsql/include/server/replication/logicalworker.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * logicalworker.h
+ * Exports for logical replication workers.
+ *
+ * Portions Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/logicalworker.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOGICALWORKER_H
+#define LOGICALWORKER_H
+
+#include
+
+extern PGDLLIMPORT volatile sig_atomic_t ParallelApplyMessagePending;
+
+extern void ApplyWorkerMain(Datum main_arg);
+extern void ParallelApplyWorkerMain(Datum main_arg);
+
+extern bool IsLogicalWorker(void);
+extern bool IsLogicalParallelApplyWorker(void);
+
+extern void HandleParallelApplyMessageInterrupt(void);
+extern void HandleParallelApplyMessages(void);
+
+extern void LogicalRepWorkersWakeupAtCommit(Oid subid);
+
+extern void AtEOXact_LogicalRepWorkers(bool isCommit);
+
+#endif /* LOGICALWORKER_H */
diff --git a/pgsql/include/server/replication/message.h b/pgsql/include/server/replication/message.h
new file mode 100644
index 0000000000000000000000000000000000000000..6ce7f2038b226a5a644068317bac8cbec6341826
--- /dev/null
+++ b/pgsql/include/server/replication/message.h
@@ -0,0 +1,41 @@
+/*-------------------------------------------------------------------------
+ * message.h
+ * Exports from replication/logical/message.c
+ *
+ * Copyright (c) 2013-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/message.h
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_LOGICAL_MESSAGE_H
+#define PG_LOGICAL_MESSAGE_H
+
+#include "access/xlog.h"
+#include "access/xlogdefs.h"
+#include "access/xlogreader.h"
+
+/*
+ * Generic logical decoding message wal record.
+ */
+typedef struct xl_logical_message
+{
+ Oid dbId; /* database Oid emitted from */
+ bool transactional; /* is message transactional? */
+ Size prefix_size; /* length of prefix */
+ Size message_size; /* size of the message */
+ /* payload, including null-terminated prefix of length prefix_size */
+ char message[FLEXIBLE_ARRAY_MEMBER];
+} xl_logical_message;
+
+#define SizeOfLogicalMessage (offsetof(xl_logical_message, message))
+
+extern XLogRecPtr LogLogicalMessage(const char *prefix, const char *message,
+ size_t size, bool transactional);
+
+/* RMGR API */
+#define XLOG_LOGICAL_MESSAGE 0x00
+extern void logicalmsg_redo(XLogReaderState *record);
+extern void logicalmsg_desc(StringInfo buf, XLogReaderState *record);
+extern const char *logicalmsg_identify(uint8 info);
+
+#endif /* PG_LOGICAL_MESSAGE_H */
diff --git a/pgsql/include/server/replication/origin.h b/pgsql/include/server/replication/origin.h
new file mode 100644
index 0000000000000000000000000000000000000000..531351093e6b808247d1e3c6a102260e12911fde
--- /dev/null
+++ b/pgsql/include/server/replication/origin.h
@@ -0,0 +1,73 @@
+/*-------------------------------------------------------------------------
+ * origin.h
+ * Exports from replication/logical/origin.c
+ *
+ * Copyright (c) 2013-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/origin.h
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_ORIGIN_H
+#define PG_ORIGIN_H
+
+#include "access/xlog.h"
+#include "access/xlogdefs.h"
+#include "access/xlogreader.h"
+#include "catalog/pg_replication_origin.h"
+
+typedef struct xl_replorigin_set
+{
+ XLogRecPtr remote_lsn;
+ RepOriginId node_id;
+ bool force;
+} xl_replorigin_set;
+
+typedef struct xl_replorigin_drop
+{
+ RepOriginId node_id;
+} xl_replorigin_drop;
+
+#define XLOG_REPLORIGIN_SET 0x00
+#define XLOG_REPLORIGIN_DROP 0x10
+
+#define InvalidRepOriginId 0
+#define DoNotReplicateId PG_UINT16_MAX
+
+extern PGDLLIMPORT RepOriginId replorigin_session_origin;
+extern PGDLLIMPORT XLogRecPtr replorigin_session_origin_lsn;
+extern PGDLLIMPORT TimestampTz replorigin_session_origin_timestamp;
+
+/* API for querying & manipulating replication origins */
+extern RepOriginId replorigin_by_name(const char *roname, bool missing_ok);
+extern RepOriginId replorigin_create(const char *roname);
+extern void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait);
+extern bool replorigin_by_oid(RepOriginId roident, bool missing_ok,
+ char **roname);
+
+/* API for querying & manipulating replication progress tracking */
+extern void replorigin_advance(RepOriginId node,
+ XLogRecPtr remote_commit,
+ XLogRecPtr local_commit,
+ bool go_backward, bool wal_log);
+extern XLogRecPtr replorigin_get_progress(RepOriginId node, bool flush);
+
+extern void replorigin_session_advance(XLogRecPtr remote_commit,
+ XLogRecPtr local_commit);
+extern void replorigin_session_setup(RepOriginId node, int acquired_by);
+extern void replorigin_session_reset(void);
+extern XLogRecPtr replorigin_session_get_progress(bool flush);
+
+/* Checkpoint/Startup integration */
+extern void CheckPointReplicationOrigin(void);
+extern void StartupReplicationOrigin(void);
+
+/* WAL logging */
+extern void replorigin_redo(XLogReaderState *record);
+extern void replorigin_desc(StringInfo buf, XLogReaderState *record);
+extern const char *replorigin_identify(uint8 info);
+
+/* shared memory allocation */
+extern Size ReplicationOriginShmemSize(void);
+extern void ReplicationOriginShmemInit(void);
+
+#endif /* PG_ORIGIN_H */
diff --git a/pgsql/include/server/replication/output_plugin.h b/pgsql/include/server/replication/output_plugin.h
new file mode 100644
index 0000000000000000000000000000000000000000..3ac67293861d1bf8be8a2ca3069c4f184f18bcf0
--- /dev/null
+++ b/pgsql/include/server/replication/output_plugin.h
@@ -0,0 +1,250 @@
+/*-------------------------------------------------------------------------
+ * output_plugin.h
+ * PostgreSQL Logical Decode Plugin Interface
+ *
+ * Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef OUTPUT_PLUGIN_H
+#define OUTPUT_PLUGIN_H
+
+#include "replication/reorderbuffer.h"
+
+struct LogicalDecodingContext;
+struct OutputPluginCallbacks;
+
+typedef enum OutputPluginOutputType
+{
+ OUTPUT_PLUGIN_BINARY_OUTPUT,
+ OUTPUT_PLUGIN_TEXTUAL_OUTPUT
+} OutputPluginOutputType;
+
+/*
+ * Options set by the output plugin, in the startup callback.
+ */
+typedef struct OutputPluginOptions
+{
+ OutputPluginOutputType output_type;
+ bool receive_rewrites;
+} OutputPluginOptions;
+
+/*
+ * Type of the shared library symbol _PG_output_plugin_init that is looked up
+ * when loading an output plugin shared library.
+ */
+typedef void (*LogicalOutputPluginInit) (struct OutputPluginCallbacks *cb);
+
+extern PGDLLEXPORT void _PG_output_plugin_init(struct OutputPluginCallbacks *cb);
+
+/*
+ * Callback that gets called in a user-defined plugin. ctx->private_data can
+ * be set to some private data.
+ *
+ * "is_init" will be set to "true" if the decoding slot just got defined. When
+ * the same slot is used from there one, it will be "false".
+ */
+typedef void (*LogicalDecodeStartupCB) (struct LogicalDecodingContext *ctx,
+ OutputPluginOptions *options,
+ bool is_init);
+
+/*
+ * Callback called for every (explicit or implicit) BEGIN of a successful
+ * transaction.
+ */
+typedef void (*LogicalDecodeBeginCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn);
+
+/*
+ * Callback for every individual change in a successful transaction.
+ */
+typedef void (*LogicalDecodeChangeCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ Relation relation,
+ ReorderBufferChange *change);
+
+/*
+ * Callback for every TRUNCATE in a successful transaction.
+ */
+typedef void (*LogicalDecodeTruncateCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ int nrelations,
+ Relation relations[],
+ ReorderBufferChange *change);
+
+/*
+ * Called for every (explicit or implicit) COMMIT of a successful transaction.
+ */
+typedef void (*LogicalDecodeCommitCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+
+/*
+ * Called for the generic logical decoding messages.
+ */
+typedef void (*LogicalDecodeMessageCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr message_lsn,
+ bool transactional,
+ const char *prefix,
+ Size message_size,
+ const char *message);
+
+/*
+ * Filter changes by origin.
+ */
+typedef bool (*LogicalDecodeFilterByOriginCB) (struct LogicalDecodingContext *ctx,
+ RepOriginId origin_id);
+
+/*
+ * Called to shutdown an output plugin.
+ */
+typedef void (*LogicalDecodeShutdownCB) (struct LogicalDecodingContext *ctx);
+
+/*
+ * Called before decoding of PREPARE record to decide whether this
+ * transaction should be decoded with separate calls to prepare and
+ * commit_prepared/rollback_prepared callbacks or wait till COMMIT PREPARED
+ * and sent as usual transaction.
+ */
+typedef bool (*LogicalDecodeFilterPrepareCB) (struct LogicalDecodingContext *ctx,
+ TransactionId xid,
+ const char *gid);
+
+/*
+ * Callback called for every BEGIN of a prepared transaction.
+ */
+typedef void (*LogicalDecodeBeginPrepareCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn);
+
+/*
+ * Called for PREPARE record unless it was filtered by filter_prepare()
+ * callback.
+ */
+typedef void (*LogicalDecodePrepareCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr prepare_lsn);
+
+/*
+ * Called for COMMIT PREPARED.
+ */
+typedef void (*LogicalDecodeCommitPreparedCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+
+/*
+ * Called for ROLLBACK PREPARED.
+ */
+typedef void (*LogicalDecodeRollbackPreparedCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr prepare_end_lsn,
+ TimestampTz prepare_time);
+
+
+/*
+ * Called when starting to stream a block of changes from in-progress
+ * transaction (may be called repeatedly, if it's streamed in multiple
+ * chunks).
+ */
+typedef void (*LogicalDecodeStreamStartCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn);
+
+/*
+ * Called when stopping to stream a block of changes from in-progress
+ * transaction to a remote node (may be called repeatedly, if it's streamed
+ * in multiple chunks).
+ */
+typedef void (*LogicalDecodeStreamStopCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn);
+
+/*
+ * Called to discard changes streamed to remote node from in-progress
+ * transaction.
+ */
+typedef void (*LogicalDecodeStreamAbortCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr abort_lsn);
+
+/*
+ * Called to prepare changes streamed to remote node from in-progress
+ * transaction. This is called as part of a two-phase commit.
+ */
+typedef void (*LogicalDecodeStreamPrepareCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr prepare_lsn);
+
+/*
+ * Called to apply changes streamed to remote node from in-progress
+ * transaction.
+ */
+typedef void (*LogicalDecodeStreamCommitCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+
+/*
+ * Callback for streaming individual changes from in-progress transactions.
+ */
+typedef void (*LogicalDecodeStreamChangeCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ Relation relation,
+ ReorderBufferChange *change);
+
+/*
+ * Callback for streaming generic logical decoding messages from in-progress
+ * transactions.
+ */
+typedef void (*LogicalDecodeStreamMessageCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ XLogRecPtr message_lsn,
+ bool transactional,
+ const char *prefix,
+ Size message_size,
+ const char *message);
+
+/*
+ * Callback for streaming truncates from in-progress transactions.
+ */
+typedef void (*LogicalDecodeStreamTruncateCB) (struct LogicalDecodingContext *ctx,
+ ReorderBufferTXN *txn,
+ int nrelations,
+ Relation relations[],
+ ReorderBufferChange *change);
+
+/*
+ * Output plugin callbacks
+ */
+typedef struct OutputPluginCallbacks
+{
+ LogicalDecodeStartupCB startup_cb;
+ LogicalDecodeBeginCB begin_cb;
+ LogicalDecodeChangeCB change_cb;
+ LogicalDecodeTruncateCB truncate_cb;
+ LogicalDecodeCommitCB commit_cb;
+ LogicalDecodeMessageCB message_cb;
+ LogicalDecodeFilterByOriginCB filter_by_origin_cb;
+ LogicalDecodeShutdownCB shutdown_cb;
+
+ /* streaming of changes at prepare time */
+ LogicalDecodeFilterPrepareCB filter_prepare_cb;
+ LogicalDecodeBeginPrepareCB begin_prepare_cb;
+ LogicalDecodePrepareCB prepare_cb;
+ LogicalDecodeCommitPreparedCB commit_prepared_cb;
+ LogicalDecodeRollbackPreparedCB rollback_prepared_cb;
+
+ /* streaming of changes */
+ LogicalDecodeStreamStartCB stream_start_cb;
+ LogicalDecodeStreamStopCB stream_stop_cb;
+ LogicalDecodeStreamAbortCB stream_abort_cb;
+ LogicalDecodeStreamPrepareCB stream_prepare_cb;
+ LogicalDecodeStreamCommitCB stream_commit_cb;
+ LogicalDecodeStreamChangeCB stream_change_cb;
+ LogicalDecodeStreamMessageCB stream_message_cb;
+ LogicalDecodeStreamTruncateCB stream_truncate_cb;
+} OutputPluginCallbacks;
+
+/* Functions in replication/logical/logical.c */
+extern void OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write);
+extern void OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write);
+extern void OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx, bool skipped_xact);
+
+#endif /* OUTPUT_PLUGIN_H */
diff --git a/pgsql/include/server/replication/pgoutput.h b/pgsql/include/server/replication/pgoutput.h
new file mode 100644
index 0000000000000000000000000000000000000000..b4a8015403b5022a1879bde8228e944dbd1b9c72
--- /dev/null
+++ b/pgsql/include/server/replication/pgoutput.h
@@ -0,0 +1,35 @@
+/*-------------------------------------------------------------------------
+ *
+ * pgoutput.h
+ * Logical Replication output plugin
+ *
+ * Copyright (c) 2015-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/replication/pgoutput.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PGOUTPUT_H
+#define PGOUTPUT_H
+
+#include "nodes/pg_list.h"
+
+typedef struct PGOutputData
+{
+ MemoryContext context; /* private memory context for transient
+ * allocations */
+ MemoryContext cachectx; /* private memory context for cache data */
+
+ /* client-supplied info: */
+ uint32 protocol_version;
+ List *publication_names;
+ List *publications;
+ bool binary;
+ char streaming;
+ bool messages;
+ bool two_phase;
+ char *origin;
+} PGOutputData;
+
+#endif /* PGOUTPUT_H */
diff --git a/pgsql/include/server/replication/reorderbuffer.h b/pgsql/include/server/replication/reorderbuffer.h
new file mode 100644
index 0000000000000000000000000000000000000000..3cb03168de246ce32ebd78068a30a36d6cd397d4
--- /dev/null
+++ b/pgsql/include/server/replication/reorderbuffer.h
@@ -0,0 +1,753 @@
+/*
+ * reorderbuffer.h
+ * PostgreSQL logical replay/reorder buffer management.
+ *
+ * Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/reorderbuffer.h
+ */
+#ifndef REORDERBUFFER_H
+#define REORDERBUFFER_H
+
+#include "access/htup_details.h"
+#include "lib/ilist.h"
+#include "storage/sinval.h"
+#include "utils/hsearch.h"
+#include "utils/relcache.h"
+#include "utils/snapshot.h"
+#include "utils/timestamp.h"
+
+/* GUC variables */
+extern PGDLLIMPORT int logical_decoding_work_mem;
+extern PGDLLIMPORT int debug_logical_replication_streaming;
+
+/* possible values for debug_logical_replication_streaming */
+typedef enum
+{
+ DEBUG_LOGICAL_REP_STREAMING_BUFFERED,
+ DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE
+} DebugLogicalRepStreamingMode;
+
+/* an individual tuple, stored in one chunk of memory */
+typedef struct ReorderBufferTupleBuf
+{
+ /* position in preallocated list */
+ slist_node node;
+
+ /* tuple header, the interesting bit for users of logical decoding */
+ HeapTupleData tuple;
+
+ /* pre-allocated size of tuple buffer, different from tuple size */
+ Size alloc_tuple_size;
+
+ /* actual tuple data follows */
+} ReorderBufferTupleBuf;
+
+/* pointer to the data stored in a TupleBuf */
+#define ReorderBufferTupleBufData(p) \
+ ((HeapTupleHeader) MAXALIGN(((char *) p) + sizeof(ReorderBufferTupleBuf)))
+
+/*
+ * Types of the change passed to a 'change' callback.
+ *
+ * For efficiency and simplicity reasons we want to keep Snapshots, CommandIds
+ * and ComboCids in the same list with the user visible INSERT/UPDATE/DELETE
+ * changes. Users of the decoding facilities will never see changes with
+ * *_INTERNAL_* actions.
+ *
+ * The INTERNAL_SPEC_INSERT and INTERNAL_SPEC_CONFIRM, and INTERNAL_SPEC_ABORT
+ * changes concern "speculative insertions", their confirmation, and abort
+ * respectively. They're used by INSERT .. ON CONFLICT .. UPDATE. Users of
+ * logical decoding don't have to care about these.
+ */
+typedef enum ReorderBufferChangeType
+{
+ REORDER_BUFFER_CHANGE_INSERT,
+ REORDER_BUFFER_CHANGE_UPDATE,
+ REORDER_BUFFER_CHANGE_DELETE,
+ REORDER_BUFFER_CHANGE_MESSAGE,
+ REORDER_BUFFER_CHANGE_INVALIDATION,
+ REORDER_BUFFER_CHANGE_INTERNAL_SNAPSHOT,
+ REORDER_BUFFER_CHANGE_INTERNAL_COMMAND_ID,
+ REORDER_BUFFER_CHANGE_INTERNAL_TUPLECID,
+ REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT,
+ REORDER_BUFFER_CHANGE_INTERNAL_SPEC_CONFIRM,
+ REORDER_BUFFER_CHANGE_INTERNAL_SPEC_ABORT,
+ REORDER_BUFFER_CHANGE_TRUNCATE
+} ReorderBufferChangeType;
+
+/* forward declaration */
+struct ReorderBufferTXN;
+
+/*
+ * a single 'change', can be an insert (with one tuple), an update (old, new),
+ * or a delete (old).
+ *
+ * The same struct is also used internally for other purposes but that should
+ * never be visible outside reorderbuffer.c.
+ */
+typedef struct ReorderBufferChange
+{
+ XLogRecPtr lsn;
+
+ /* The type of change. */
+ ReorderBufferChangeType action;
+
+ /* Transaction this change belongs to. */
+ struct ReorderBufferTXN *txn;
+
+ RepOriginId origin_id;
+
+ /*
+ * Context data for the change. Which part of the union is valid depends
+ * on action.
+ */
+ union
+ {
+ /* Old, new tuples when action == *_INSERT|UPDATE|DELETE */
+ struct
+ {
+ /* relation that has been changed */
+ RelFileLocator rlocator;
+
+ /* no previously reassembled toast chunks are necessary anymore */
+ bool clear_toast_afterwards;
+
+ /* valid for DELETE || UPDATE */
+ ReorderBufferTupleBuf *oldtuple;
+ /* valid for INSERT || UPDATE */
+ ReorderBufferTupleBuf *newtuple;
+ } tp;
+
+ /*
+ * Truncate data for REORDER_BUFFER_CHANGE_TRUNCATE representing one
+ * set of relations to be truncated.
+ */
+ struct
+ {
+ Size nrelids;
+ bool cascade;
+ bool restart_seqs;
+ Oid *relids;
+ } truncate;
+
+ /* Message with arbitrary data. */
+ struct
+ {
+ char *prefix;
+ Size message_size;
+ char *message;
+ } msg;
+
+ /* New snapshot, set when action == *_INTERNAL_SNAPSHOT */
+ Snapshot snapshot;
+
+ /*
+ * New command id for existing snapshot in a catalog changing tx. Set
+ * when action == *_INTERNAL_COMMAND_ID.
+ */
+ CommandId command_id;
+
+ /*
+ * New cid mapping for catalog changing transaction, set when action
+ * == *_INTERNAL_TUPLECID.
+ */
+ struct
+ {
+ RelFileLocator locator;
+ ItemPointerData tid;
+ CommandId cmin;
+ CommandId cmax;
+ CommandId combocid;
+ } tuplecid;
+
+ /* Invalidation. */
+ struct
+ {
+ uint32 ninvalidations; /* Number of messages */
+ SharedInvalidationMessage *invalidations; /* invalidation message */
+ } inval;
+ } data;
+
+ /*
+ * While in use this is how a change is linked into a transactions,
+ * otherwise it's the preallocated list.
+ */
+ dlist_node node;
+} ReorderBufferChange;
+
+/* ReorderBufferTXN txn_flags */
+#define RBTXN_HAS_CATALOG_CHANGES 0x0001
+#define RBTXN_IS_SUBXACT 0x0002
+#define RBTXN_IS_SERIALIZED 0x0004
+#define RBTXN_IS_SERIALIZED_CLEAR 0x0008
+#define RBTXN_IS_STREAMED 0x0010
+#define RBTXN_HAS_PARTIAL_CHANGE 0x0020
+#define RBTXN_PREPARE 0x0040
+#define RBTXN_SKIPPED_PREPARE 0x0080
+#define RBTXN_HAS_STREAMABLE_CHANGE 0x0100
+
+/* Does the transaction have catalog changes? */
+#define rbtxn_has_catalog_changes(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_HAS_CATALOG_CHANGES) != 0 \
+)
+
+/* Is the transaction known as a subxact? */
+#define rbtxn_is_known_subxact(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_IS_SUBXACT) != 0 \
+)
+
+/* Has this transaction been spilled to disk? */
+#define rbtxn_is_serialized(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_IS_SERIALIZED) != 0 \
+)
+
+/* Has this transaction ever been spilled to disk? */
+#define rbtxn_is_serialized_clear(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_IS_SERIALIZED_CLEAR) != 0 \
+)
+
+/* Has this transaction contains partial changes? */
+#define rbtxn_has_partial_change(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_HAS_PARTIAL_CHANGE) != 0 \
+)
+
+/* Does this transaction contain streamable changes? */
+#define rbtxn_has_streamable_change(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_HAS_STREAMABLE_CHANGE) != 0 \
+)
+
+/*
+ * Has this transaction been streamed to downstream?
+ *
+ * (It's not possible to deduce this from nentries and nentries_mem for
+ * various reasons. For example, all changes may be in subtransactions in
+ * which case we'd have nentries==0 for the toplevel one, which would say
+ * nothing about the streaming. So we maintain this flag, but only for the
+ * toplevel transaction.)
+ */
+#define rbtxn_is_streamed(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_IS_STREAMED) != 0 \
+)
+
+/* Has this transaction been prepared? */
+#define rbtxn_prepared(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_PREPARE) != 0 \
+)
+
+/* prepare for this transaction skipped? */
+#define rbtxn_skip_prepared(txn) \
+( \
+ ((txn)->txn_flags & RBTXN_SKIPPED_PREPARE) != 0 \
+)
+
+/* Is this a top-level transaction? */
+#define rbtxn_is_toptxn(txn) \
+( \
+ (txn)->toptxn == NULL \
+)
+
+/* Is this a subtransaction? */
+#define rbtxn_is_subtxn(txn) \
+( \
+ (txn)->toptxn != NULL \
+)
+
+/* Get the top-level transaction of this (sub)transaction. */
+#define rbtxn_get_toptxn(txn) \
+( \
+ rbtxn_is_subtxn(txn) ? (txn)->toptxn : (txn) \
+)
+
+typedef struct ReorderBufferTXN
+{
+ /* See above */
+ bits32 txn_flags;
+
+ /* The transaction's transaction id, can be a toplevel or sub xid. */
+ TransactionId xid;
+
+ /* Xid of top-level transaction, if known */
+ TransactionId toplevel_xid;
+
+ /*
+ * Global transaction id required for identification of prepared
+ * transactions.
+ */
+ char *gid;
+
+ /*
+ * LSN of the first data carrying, WAL record with knowledge about this
+ * xid. This is allowed to *not* be first record adorned with this xid, if
+ * the previous records aren't relevant for logical decoding.
+ */
+ XLogRecPtr first_lsn;
+
+ /* ----
+ * LSN of the record that lead to this xact to be prepared or committed or
+ * aborted. This can be a
+ * * plain commit record
+ * * plain commit record, of a parent transaction
+ * * prepared transaction
+ * * prepared transaction commit
+ * * plain abort record
+ * * prepared transaction abort
+ *
+ * This can also become set to earlier values than transaction end when
+ * a transaction is spilled to disk; specifically it's set to the LSN of
+ * the latest change written to disk so far.
+ * ----
+ */
+ XLogRecPtr final_lsn;
+
+ /*
+ * LSN pointing to the end of the commit record + 1.
+ */
+ XLogRecPtr end_lsn;
+
+ /* Toplevel transaction for this subxact (NULL for top-level). */
+ struct ReorderBufferTXN *toptxn;
+
+ /*
+ * LSN of the last lsn at which snapshot information reside, so we can
+ * restart decoding from there and fully recover this transaction from
+ * WAL.
+ */
+ XLogRecPtr restart_decoding_lsn;
+
+ /* origin of the change that caused this transaction */
+ RepOriginId origin_id;
+ XLogRecPtr origin_lsn;
+
+ /*
+ * Commit or Prepare time, only known when we read the actual commit or
+ * prepare record.
+ */
+ union
+ {
+ TimestampTz commit_time;
+ TimestampTz prepare_time;
+ TimestampTz abort_time;
+ } xact_time;
+
+ /*
+ * The base snapshot is used to decode all changes until either this
+ * transaction modifies the catalog, or another catalog-modifying
+ * transaction commits.
+ */
+ Snapshot base_snapshot;
+ XLogRecPtr base_snapshot_lsn;
+ dlist_node base_snapshot_node; /* link in txns_by_base_snapshot_lsn */
+
+ /*
+ * Snapshot/CID from the previous streaming run. Only valid for already
+ * streamed transactions (NULL/InvalidCommandId otherwise).
+ */
+ Snapshot snapshot_now;
+ CommandId command_id;
+
+ /*
+ * How many ReorderBufferChange's do we have in this txn.
+ *
+ * Changes in subtransactions are *not* included but tracked separately.
+ */
+ uint64 nentries;
+
+ /*
+ * How many of the above entries are stored in memory in contrast to being
+ * spilled to disk.
+ */
+ uint64 nentries_mem;
+
+ /*
+ * List of ReorderBufferChange structs, including new Snapshots, new
+ * CommandIds and command invalidation messages.
+ */
+ dlist_head changes;
+
+ /*
+ * List of (relation, ctid) => (cmin, cmax) mappings for catalog tuples.
+ * Those are always assigned to the toplevel transaction. (Keep track of
+ * #entries to create a hash of the right size)
+ */
+ dlist_head tuplecids;
+ uint64 ntuplecids;
+
+ /*
+ * On-demand built hash for looking up the above values.
+ */
+ HTAB *tuplecid_hash;
+
+ /*
+ * Hash containing (potentially partial) toast entries. NULL if no toast
+ * tuples have been found for the current change.
+ */
+ HTAB *toast_hash;
+
+ /*
+ * non-hierarchical list of subtransactions that are *not* aborted. Only
+ * used in toplevel transactions.
+ */
+ dlist_head subtxns;
+ uint32 nsubtxns;
+
+ /*
+ * Stored cache invalidations. This is not a linked list because we get
+ * all the invalidations at once.
+ */
+ uint32 ninvalidations;
+ SharedInvalidationMessage *invalidations;
+
+ /* ---
+ * Position in one of three lists:
+ * * list of subtransactions if we are *known* to be subxact
+ * * list of toplevel xacts (can be an as-yet unknown subxact)
+ * * list of preallocated ReorderBufferTXNs (if unused)
+ * ---
+ */
+ dlist_node node;
+
+ /*
+ * A node in the list of catalog modifying transactions
+ */
+ dlist_node catchange_node;
+
+ /*
+ * Size of this transaction (changes currently in memory, in bytes).
+ */
+ Size size;
+
+ /* Size of top-transaction including sub-transactions. */
+ Size total_size;
+
+ /* If we have detected concurrent abort then ignore future changes. */
+ bool concurrent_abort;
+
+ /*
+ * Private data pointer of the output plugin.
+ */
+ void *output_plugin_private;
+} ReorderBufferTXN;
+
+/* so we can define the callbacks used inside struct ReorderBuffer itself */
+typedef struct ReorderBuffer ReorderBuffer;
+
+/* change callback signature */
+typedef void (*ReorderBufferApplyChangeCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ Relation relation,
+ ReorderBufferChange *change);
+
+/* truncate callback signature */
+typedef void (*ReorderBufferApplyTruncateCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ int nrelations,
+ Relation relations[],
+ ReorderBufferChange *change);
+
+/* begin callback signature */
+typedef void (*ReorderBufferBeginCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn);
+
+/* commit callback signature */
+typedef void (*ReorderBufferCommitCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+
+/* message callback signature */
+typedef void (*ReorderBufferMessageCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr message_lsn,
+ bool transactional,
+ const char *prefix, Size sz,
+ const char *message);
+
+/* begin prepare callback signature */
+typedef void (*ReorderBufferBeginPrepareCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn);
+
+/* prepare callback signature */
+typedef void (*ReorderBufferPrepareCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr prepare_lsn);
+
+/* commit prepared callback signature */
+typedef void (*ReorderBufferCommitPreparedCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+
+/* rollback prepared callback signature */
+typedef void (*ReorderBufferRollbackPreparedCB) (ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr prepare_end_lsn,
+ TimestampTz prepare_time);
+
+/* start streaming transaction callback signature */
+typedef void (*ReorderBufferStreamStartCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr first_lsn);
+
+/* stop streaming transaction callback signature */
+typedef void (*ReorderBufferStreamStopCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr last_lsn);
+
+/* discard streamed transaction callback signature */
+typedef void (*ReorderBufferStreamAbortCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr abort_lsn);
+
+/* prepare streamed transaction callback signature */
+typedef void (*ReorderBufferStreamPrepareCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr prepare_lsn);
+
+/* commit streamed transaction callback signature */
+typedef void (*ReorderBufferStreamCommitCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr commit_lsn);
+
+/* stream change callback signature */
+typedef void (*ReorderBufferStreamChangeCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ Relation relation,
+ ReorderBufferChange *change);
+
+/* stream message callback signature */
+typedef void (*ReorderBufferStreamMessageCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr message_lsn,
+ bool transactional,
+ const char *prefix, Size sz,
+ const char *message);
+
+/* stream truncate callback signature */
+typedef void (*ReorderBufferStreamTruncateCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ int nrelations,
+ Relation relations[],
+ ReorderBufferChange *change);
+
+/* update progress txn callback signature */
+typedef void (*ReorderBufferUpdateProgressTxnCB) (
+ ReorderBuffer *rb,
+ ReorderBufferTXN *txn,
+ XLogRecPtr lsn);
+
+struct ReorderBuffer
+{
+ /*
+ * xid => ReorderBufferTXN lookup table
+ */
+ HTAB *by_txn;
+
+ /*
+ * Transactions that could be a toplevel xact, ordered by LSN of the first
+ * record bearing that xid.
+ */
+ dlist_head toplevel_by_lsn;
+
+ /*
+ * Transactions and subtransactions that have a base snapshot, ordered by
+ * LSN of the record which caused us to first obtain the base snapshot.
+ * This is not the same as toplevel_by_lsn, because we only set the base
+ * snapshot on the first logical-decoding-relevant record (eg. heap
+ * writes), whereas the initial LSN could be set by other operations.
+ */
+ dlist_head txns_by_base_snapshot_lsn;
+
+ /*
+ * Transactions and subtransactions that have modified system catalogs.
+ */
+ dclist_head catchange_txns;
+
+ /*
+ * one-entry sized cache for by_txn. Very frequently the same txn gets
+ * looked up over and over again.
+ */
+ TransactionId by_txn_last_xid;
+ ReorderBufferTXN *by_txn_last_txn;
+
+ /*
+ * Callbacks to be called when a transactions commits.
+ */
+ ReorderBufferBeginCB begin;
+ ReorderBufferApplyChangeCB apply_change;
+ ReorderBufferApplyTruncateCB apply_truncate;
+ ReorderBufferCommitCB commit;
+ ReorderBufferMessageCB message;
+
+ /*
+ * Callbacks to be called when streaming a transaction at prepare time.
+ */
+ ReorderBufferBeginCB begin_prepare;
+ ReorderBufferPrepareCB prepare;
+ ReorderBufferCommitPreparedCB commit_prepared;
+ ReorderBufferRollbackPreparedCB rollback_prepared;
+
+ /*
+ * Callbacks to be called when streaming a transaction.
+ */
+ ReorderBufferStreamStartCB stream_start;
+ ReorderBufferStreamStopCB stream_stop;
+ ReorderBufferStreamAbortCB stream_abort;
+ ReorderBufferStreamPrepareCB stream_prepare;
+ ReorderBufferStreamCommitCB stream_commit;
+ ReorderBufferStreamChangeCB stream_change;
+ ReorderBufferStreamMessageCB stream_message;
+ ReorderBufferStreamTruncateCB stream_truncate;
+
+ /*
+ * Callback to be called when updating progress during sending data of a
+ * transaction (and its subtransactions) to the output plugin.
+ */
+ ReorderBufferUpdateProgressTxnCB update_progress_txn;
+
+ /*
+ * Pointer that will be passed untouched to the callbacks.
+ */
+ void *private_data;
+
+ /*
+ * Saved output plugin option
+ */
+ bool output_rewrites;
+
+ /*
+ * Private memory context.
+ */
+ MemoryContext context;
+
+ /*
+ * Memory contexts for specific types objects
+ */
+ MemoryContext change_context;
+ MemoryContext txn_context;
+ MemoryContext tup_context;
+
+ XLogRecPtr current_restart_decoding_lsn;
+
+ /* buffer for disk<->memory conversions */
+ char *outbuf;
+ Size outbufsize;
+
+ /* memory accounting */
+ Size size;
+
+ /*
+ * Statistics about transactions spilled to disk.
+ *
+ * A single transaction may be spilled repeatedly, which is why we keep
+ * two different counters. For spilling, the transaction counter includes
+ * both toplevel transactions and subtransactions.
+ */
+ int64 spillTxns; /* number of transactions spilled to disk */
+ int64 spillCount; /* spill-to-disk invocation counter */
+ int64 spillBytes; /* amount of data spilled to disk */
+
+ /* Statistics about transactions streamed to the decoding output plugin */
+ int64 streamTxns; /* number of transactions streamed */
+ int64 streamCount; /* streaming invocation counter */
+ int64 streamBytes; /* amount of data decoded */
+
+ /*
+ * Statistics about all the transactions sent to the decoding output
+ * plugin
+ */
+ int64 totalTxns; /* total number of transactions sent */
+ int64 totalBytes; /* total amount of data decoded */
+};
+
+
+extern ReorderBuffer *ReorderBufferAllocate(void);
+extern void ReorderBufferFree(ReorderBuffer *rb);
+
+extern ReorderBufferTupleBuf *ReorderBufferGetTupleBuf(ReorderBuffer *rb,
+ Size tuple_len);
+extern void ReorderBufferReturnTupleBuf(ReorderBuffer *rb,
+ ReorderBufferTupleBuf *tuple);
+extern ReorderBufferChange *ReorderBufferGetChange(ReorderBuffer *rb);
+extern void ReorderBufferReturnChange(ReorderBuffer *rb,
+ ReorderBufferChange *change, bool upd_mem);
+
+extern Oid *ReorderBufferGetRelids(ReorderBuffer *rb, int nrelids);
+extern void ReorderBufferReturnRelids(ReorderBuffer *rb, Oid *relids);
+
+extern void ReorderBufferQueueChange(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr lsn, ReorderBufferChange *change,
+ bool toast_insert);
+extern void ReorderBufferQueueMessage(ReorderBuffer *rb, TransactionId xid,
+ Snapshot snap, XLogRecPtr lsn,
+ bool transactional, const char *prefix,
+ Size message_size, const char *message);
+extern void ReorderBufferCommit(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
+ TimestampTz commit_time, RepOriginId origin_id, XLogRecPtr origin_lsn);
+extern void ReorderBufferFinishPrepared(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr commit_lsn, XLogRecPtr end_lsn,
+ XLogRecPtr two_phase_at,
+ TimestampTz commit_time,
+ RepOriginId origin_id, XLogRecPtr origin_lsn,
+ char *gid, bool is_commit);
+extern void ReorderBufferAssignChild(ReorderBuffer *rb, TransactionId xid,
+ TransactionId subxid, XLogRecPtr lsn);
+extern void ReorderBufferCommitChild(ReorderBuffer *rb, TransactionId xid,
+ TransactionId subxid, XLogRecPtr commit_lsn,
+ XLogRecPtr end_lsn);
+extern void ReorderBufferAbort(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
+ TimestampTz abort_time);
+extern void ReorderBufferAbortOld(ReorderBuffer *rb, TransactionId oldestRunningXid);
+extern void ReorderBufferForget(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
+extern void ReorderBufferInvalidate(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
+
+extern void ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr lsn, Snapshot snap);
+extern void ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr lsn, Snapshot snap);
+extern void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr lsn, CommandId cid);
+extern void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr lsn, RelFileLocator locator,
+ ItemPointerData tid,
+ CommandId cmin, CommandId cmax, CommandId combocid);
+extern void ReorderBufferAddInvalidations(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn,
+ Size nmsgs, SharedInvalidationMessage *msgs);
+extern void ReorderBufferImmediateInvalidation(ReorderBuffer *rb, uint32 ninvalidations,
+ SharedInvalidationMessage *invalidations);
+extern void ReorderBufferProcessXid(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
+
+extern void ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn);
+extern bool ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid);
+extern bool ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid);
+
+extern bool ReorderBufferRememberPrepareInfo(ReorderBuffer *rb, TransactionId xid,
+ XLogRecPtr prepare_lsn, XLogRecPtr end_lsn,
+ TimestampTz prepare_time,
+ RepOriginId origin_id, XLogRecPtr origin_lsn);
+extern void ReorderBufferSkipPrepare(ReorderBuffer *rb, TransactionId xid);
+extern void ReorderBufferPrepare(ReorderBuffer *rb, TransactionId xid, char *gid);
+extern ReorderBufferTXN *ReorderBufferGetOldestTXN(ReorderBuffer *rb);
+extern TransactionId ReorderBufferGetOldestXmin(ReorderBuffer *rb);
+extern TransactionId *ReorderBufferGetCatalogChangesXacts(ReorderBuffer *rb);
+
+extern void ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr);
+
+extern void StartupReorderBuffer(void);
+
+#endif
diff --git a/pgsql/include/server/replication/slot.h b/pgsql/include/server/replication/slot.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8a89dc7844eeff674e7c84e3687141b59129f45
--- /dev/null
+++ b/pgsql/include/server/replication/slot.h
@@ -0,0 +1,249 @@
+/*-------------------------------------------------------------------------
+ * slot.h
+ * Replication slot management.
+ *
+ * Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SLOT_H
+#define SLOT_H
+
+#include "access/xlog.h"
+#include "access/xlogreader.h"
+#include "storage/condition_variable.h"
+#include "storage/lwlock.h"
+#include "storage/shmem.h"
+#include "storage/spin.h"
+#include "replication/walreceiver.h"
+
+/*
+ * Behaviour of replication slots, upon release or crash.
+ *
+ * Slots marked as PERSISTENT are crash-safe and will not be dropped when
+ * released. Slots marked as EPHEMERAL will be dropped when released or after
+ * restarts. Slots marked TEMPORARY will be dropped at the end of a session
+ * or on error.
+ *
+ * EPHEMERAL is used as a not-quite-ready state when creating persistent
+ * slots. EPHEMERAL slots can be made PERSISTENT by calling
+ * ReplicationSlotPersist(). For a slot that goes away at the end of a
+ * session, TEMPORARY is the appropriate choice.
+ */
+typedef enum ReplicationSlotPersistency
+{
+ RS_PERSISTENT,
+ RS_EPHEMERAL,
+ RS_TEMPORARY
+} ReplicationSlotPersistency;
+
+/*
+ * Slots can be invalidated, e.g. due to max_slot_wal_keep_size. If so, the
+ * 'invalidated' field is set to a value other than _NONE.
+ */
+typedef enum ReplicationSlotInvalidationCause
+{
+ RS_INVAL_NONE,
+ /* required WAL has been removed */
+ RS_INVAL_WAL_REMOVED,
+ /* required rows have been removed */
+ RS_INVAL_HORIZON,
+ /* wal_level insufficient for slot */
+ RS_INVAL_WAL_LEVEL,
+} ReplicationSlotInvalidationCause;
+
+/*
+ * On-Disk data of a replication slot, preserved across restarts.
+ */
+typedef struct ReplicationSlotPersistentData
+{
+ /* The slot's identifier */
+ NameData name;
+
+ /* database the slot is active on */
+ Oid database;
+
+ /*
+ * The slot's behaviour when being dropped (or restored after a crash).
+ */
+ ReplicationSlotPersistency persistency;
+
+ /*
+ * xmin horizon for data
+ *
+ * NB: This may represent a value that hasn't been written to disk yet;
+ * see notes for effective_xmin, below.
+ */
+ TransactionId xmin;
+
+ /*
+ * xmin horizon for catalog tuples
+ *
+ * NB: This may represent a value that hasn't been written to disk yet;
+ * see notes for effective_xmin, below.
+ */
+ TransactionId catalog_xmin;
+
+ /* oldest LSN that might be required by this replication slot */
+ XLogRecPtr restart_lsn;
+
+ /* RS_INVAL_NONE if valid, or the reason for having been invalidated */
+ ReplicationSlotInvalidationCause invalidated;
+
+ /*
+ * Oldest LSN that the client has acked receipt for. This is used as the
+ * start_lsn point in case the client doesn't specify one, and also as a
+ * safety measure to jump forwards in case the client specifies a
+ * start_lsn that's further in the past than this value.
+ */
+ XLogRecPtr confirmed_flush;
+
+ /*
+ * LSN at which we enabled two_phase commit for this slot or LSN at which
+ * we found a consistent point at the time of slot creation.
+ */
+ XLogRecPtr two_phase_at;
+
+ /*
+ * Allow decoding of prepared transactions?
+ */
+ bool two_phase;
+
+ /* plugin name */
+ NameData plugin;
+} ReplicationSlotPersistentData;
+
+/*
+ * Shared memory state of a single replication slot.
+ *
+ * The in-memory data of replication slots follows a locking model based
+ * on two linked concepts:
+ * - A replication slot's in_use flag is switched when added or discarded using
+ * the LWLock ReplicationSlotControlLock, which needs to be hold in exclusive
+ * mode when updating the flag by the backend owning the slot and doing the
+ * operation, while readers (concurrent backends not owning the slot) need
+ * to hold it in shared mode when looking at replication slot data.
+ * - Individual fields are protected by mutex where only the backend owning
+ * the slot is authorized to update the fields from its own slot. The
+ * backend owning the slot does not need to take this lock when reading its
+ * own fields, while concurrent backends not owning this slot should take the
+ * lock when reading this slot's data.
+ */
+typedef struct ReplicationSlot
+{
+ /* lock, on same cacheline as effective_xmin */
+ slock_t mutex;
+
+ /* is this slot defined */
+ bool in_use;
+
+ /* Who is streaming out changes for this slot? 0 in unused slots. */
+ pid_t active_pid;
+
+ /* any outstanding modifications? */
+ bool just_dirtied;
+ bool dirty;
+
+ /*
+ * For logical decoding, it's extremely important that we never remove any
+ * data that's still needed for decoding purposes, even after a crash;
+ * otherwise, decoding will produce wrong answers. Ordinary streaming
+ * replication also needs to prevent old row versions from being removed
+ * too soon, but the worst consequence we might encounter there is
+ * unwanted query cancellations on the standby. Thus, for logical
+ * decoding, this value represents the latest xmin that has actually been
+ * written to disk, whereas for streaming replication, it's just the same
+ * as the persistent value (data.xmin).
+ */
+ TransactionId effective_xmin;
+ TransactionId effective_catalog_xmin;
+
+ /* data surviving shutdowns and crashes */
+ ReplicationSlotPersistentData data;
+
+ /* is somebody performing io on this slot? */
+ LWLock io_in_progress_lock;
+
+ /* Condition variable signaled when active_pid changes */
+ ConditionVariable active_cv;
+
+ /* all the remaining data is only used for logical slots */
+
+ /*
+ * When the client has confirmed flushes >= candidate_xmin_lsn we can
+ * advance the catalog xmin. When restart_valid has been passed,
+ * restart_lsn can be increased.
+ */
+ TransactionId candidate_catalog_xmin;
+ XLogRecPtr candidate_xmin_lsn;
+ XLogRecPtr candidate_restart_valid;
+ XLogRecPtr candidate_restart_lsn;
+} ReplicationSlot;
+
+#define SlotIsPhysical(slot) ((slot)->data.database == InvalidOid)
+#define SlotIsLogical(slot) ((slot)->data.database != InvalidOid)
+
+/*
+ * Shared memory control area for all of replication slots.
+ */
+typedef struct ReplicationSlotCtlData
+{
+ /*
+ * This array should be declared [FLEXIBLE_ARRAY_MEMBER], but for some
+ * reason you can't do that in an otherwise-empty struct.
+ */
+ ReplicationSlot replication_slots[1];
+} ReplicationSlotCtlData;
+
+/*
+ * Pointers to shared memory
+ */
+extern PGDLLIMPORT ReplicationSlotCtlData *ReplicationSlotCtl;
+extern PGDLLIMPORT ReplicationSlot *MyReplicationSlot;
+
+/* GUCs */
+extern PGDLLIMPORT int max_replication_slots;
+
+/* shmem initialization functions */
+extern Size ReplicationSlotsShmemSize(void);
+extern void ReplicationSlotsShmemInit(void);
+
+/* management of individual slots */
+extern void ReplicationSlotCreate(const char *name, bool db_specific,
+ ReplicationSlotPersistency persistency,
+ bool two_phase);
+extern void ReplicationSlotPersist(void);
+extern void ReplicationSlotDrop(const char *name, bool nowait);
+
+extern void ReplicationSlotAcquire(const char *name, bool nowait);
+extern void ReplicationSlotRelease(void);
+extern void ReplicationSlotCleanup(void);
+extern void ReplicationSlotSave(void);
+extern void ReplicationSlotMarkDirty(void);
+
+/* misc stuff */
+extern void ReplicationSlotInitialize(void);
+extern bool ReplicationSlotValidateName(const char *name, int elevel);
+extern void ReplicationSlotReserveWal(void);
+extern void ReplicationSlotsComputeRequiredXmin(bool already_locked);
+extern void ReplicationSlotsComputeRequiredLSN(void);
+extern XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN(void);
+extern bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive);
+extern void ReplicationSlotsDropDBSlots(Oid dboid);
+extern bool InvalidateObsoleteReplicationSlots(ReplicationSlotInvalidationCause cause,
+ XLogSegNo oldestSegno,
+ Oid dboid,
+ TransactionId snapshotConflictHorizon);
+extern ReplicationSlot *SearchNamedReplicationSlot(const char *name, bool need_lock);
+extern int ReplicationSlotIndex(ReplicationSlot *slot);
+extern bool ReplicationSlotName(int index, Name name);
+extern void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot);
+extern void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok);
+
+extern void StartupReplicationSlots(void);
+extern void CheckPointReplicationSlots(void);
+
+extern void CheckSlotRequirements(void);
+extern void CheckSlotPermissions(void);
+
+#endif /* SLOT_H */
diff --git a/pgsql/include/server/replication/snapbuild.h b/pgsql/include/server/replication/snapbuild.h
new file mode 100644
index 0000000000000000000000000000000000000000..f49b941b53ebcd4c5f768624606e59a941db964b
--- /dev/null
+++ b/pgsql/include/server/replication/snapbuild.h
@@ -0,0 +1,94 @@
+/*-------------------------------------------------------------------------
+ *
+ * snapbuild.h
+ * Exports from replication/logical/snapbuild.c.
+ *
+ * Copyright (c) 2012-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/snapbuild.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SNAPBUILD_H
+#define SNAPBUILD_H
+
+#include "access/xlogdefs.h"
+#include "utils/snapmgr.h"
+
+typedef enum
+{
+ /*
+ * Initial state, we can't do much yet.
+ */
+ SNAPBUILD_START = -1,
+
+ /*
+ * Collecting committed transactions, to build the initial catalog
+ * snapshot.
+ */
+ SNAPBUILD_BUILDING_SNAPSHOT = 0,
+
+ /*
+ * We have collected enough information to decode tuples in transactions
+ * that started after this.
+ *
+ * Once we reached this we start to collect changes. We cannot apply them
+ * yet, because they might be based on transactions that were still
+ * running when FULL_SNAPSHOT was reached.
+ */
+ SNAPBUILD_FULL_SNAPSHOT = 1,
+
+ /*
+ * Found a point after SNAPBUILD_FULL_SNAPSHOT where all transactions that
+ * were running at that point finished. Till we reach that we hold off
+ * calling any commit callbacks.
+ */
+ SNAPBUILD_CONSISTENT = 2
+} SnapBuildState;
+
+/* forward declare so we don't have to expose the struct to the public */
+struct SnapBuild;
+typedef struct SnapBuild SnapBuild;
+
+/* forward declare so we don't have to include reorderbuffer.h */
+struct ReorderBuffer;
+
+/* forward declare so we don't have to include heapam_xlog.h */
+struct xl_heap_new_cid;
+struct xl_running_xacts;
+
+extern void CheckPointSnapBuild(void);
+
+extern SnapBuild *AllocateSnapshotBuilder(struct ReorderBuffer *reorder,
+ TransactionId xmin_horizon, XLogRecPtr start_lsn,
+ bool need_full_snapshot,
+ XLogRecPtr two_phase_at);
+extern void FreeSnapshotBuilder(SnapBuild *builder);
+
+extern void SnapBuildSnapDecRefcount(Snapshot snap);
+
+extern Snapshot SnapBuildInitialSnapshot(SnapBuild *builder);
+extern const char *SnapBuildExportSnapshot(SnapBuild *builder);
+extern void SnapBuildClearExportedSnapshot(void);
+extern void SnapBuildResetExportedSnapshotState(void);
+
+extern SnapBuildState SnapBuildCurrentState(SnapBuild *builder);
+extern Snapshot SnapBuildGetOrBuildSnapshot(SnapBuild *builder);
+
+extern bool SnapBuildXactNeedsSkip(SnapBuild *builder, XLogRecPtr ptr);
+extern XLogRecPtr SnapBuildGetTwoPhaseAt(SnapBuild *builder);
+extern void SnapBuildSetTwoPhaseAt(SnapBuild *builder, XLogRecPtr ptr);
+
+extern void SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn,
+ TransactionId xid, int nsubxacts,
+ TransactionId *subxacts, uint32 xinfo);
+extern bool SnapBuildProcessChange(SnapBuild *builder, TransactionId xid,
+ XLogRecPtr lsn);
+extern void SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
+ XLogRecPtr lsn,
+ struct xl_heap_new_cid *xlrec);
+extern void SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn,
+ struct xl_running_xacts *running);
+extern void SnapBuildSerializationPoint(SnapBuild *builder, XLogRecPtr lsn);
+
+#endif /* SNAPBUILD_H */
diff --git a/pgsql/include/server/replication/syncrep.h b/pgsql/include/server/replication/syncrep.h
new file mode 100644
index 0000000000000000000000000000000000000000..0aec4cb1d51b5d8d6d36da9a1fcf04d16c3a677e
--- /dev/null
+++ b/pgsql/include/server/replication/syncrep.h
@@ -0,0 +1,109 @@
+/*-------------------------------------------------------------------------
+ *
+ * syncrep.h
+ * Exports from replication/syncrep.c.
+ *
+ * Portions Copyright (c) 2010-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/replication/syncrep.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _SYNCREP_H
+#define _SYNCREP_H
+
+#include "access/xlogdefs.h"
+
+#define SyncRepRequested() \
+ (max_wal_senders > 0 && synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)
+
+/* SyncRepWaitMode */
+#define SYNC_REP_NO_WAIT (-1)
+#define SYNC_REP_WAIT_WRITE 0
+#define SYNC_REP_WAIT_FLUSH 1
+#define SYNC_REP_WAIT_APPLY 2
+
+#define NUM_SYNC_REP_WAIT_MODE 3
+
+/* syncRepState */
+#define SYNC_REP_NOT_WAITING 0
+#define SYNC_REP_WAITING 1
+#define SYNC_REP_WAIT_COMPLETE 2
+
+/* syncrep_method of SyncRepConfigData */
+#define SYNC_REP_PRIORITY 0
+#define SYNC_REP_QUORUM 1
+
+/*
+ * SyncRepGetCandidateStandbys returns an array of these structs,
+ * one per candidate synchronous walsender.
+ */
+typedef struct SyncRepStandbyData
+{
+ /* Copies of relevant fields from WalSnd shared-memory struct */
+ pid_t pid;
+ XLogRecPtr write;
+ XLogRecPtr flush;
+ XLogRecPtr apply;
+ int sync_standby_priority;
+ /* Index of this walsender in the WalSnd shared-memory array */
+ int walsnd_index;
+ /* This flag indicates whether this struct is about our own process */
+ bool is_me;
+} SyncRepStandbyData;
+
+/*
+ * Struct for the configuration of synchronous replication.
+ *
+ * Note: this must be a flat representation that can be held in a single
+ * chunk of malloc'd memory, so that it can be stored as the "extra" data
+ * for the synchronous_standby_names GUC.
+ */
+typedef struct SyncRepConfigData
+{
+ int config_size; /* total size of this struct, in bytes */
+ int num_sync; /* number of sync standbys that we need to
+ * wait for */
+ uint8 syncrep_method; /* method to choose sync standbys */
+ int nmembers; /* number of members in the following list */
+ /* member_names contains nmembers consecutive nul-terminated C strings */
+ char member_names[FLEXIBLE_ARRAY_MEMBER];
+} SyncRepConfigData;
+
+extern PGDLLIMPORT SyncRepConfigData *SyncRepConfig;
+
+/* communication variables for parsing synchronous_standby_names GUC */
+extern PGDLLIMPORT SyncRepConfigData *syncrep_parse_result;
+extern PGDLLIMPORT char *syncrep_parse_error_msg;
+
+/* user-settable parameters for synchronous replication */
+extern PGDLLIMPORT char *SyncRepStandbyNames;
+
+/* called by user backend */
+extern void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit);
+
+/* called at backend exit */
+extern void SyncRepCleanupAtProcExit(void);
+
+/* called by wal sender */
+extern void SyncRepInitConfig(void);
+extern void SyncRepReleaseWaiters(void);
+
+/* called by wal sender and user backend */
+extern int SyncRepGetCandidateStandbys(SyncRepStandbyData **standbys);
+
+/* called by checkpointer */
+extern void SyncRepUpdateSyncStandbysDefined(void);
+
+/*
+ * Internal functions for parsing synchronous_standby_names grammar,
+ * in syncrep_gram.y and syncrep_scanner.l
+ */
+extern int syncrep_yyparse(void);
+extern int syncrep_yylex(void);
+extern void syncrep_yyerror(const char *str);
+extern void syncrep_scanner_init(const char *str);
+extern void syncrep_scanner_finish(void);
+
+#endif /* _SYNCREP_H */
diff --git a/pgsql/include/server/replication/walreceiver.h b/pgsql/include/server/replication/walreceiver.h
new file mode 100644
index 0000000000000000000000000000000000000000..281626fa6f5d8e49d17044bf41571ce3d28ab0b4
--- /dev/null
+++ b/pgsql/include/server/replication/walreceiver.h
@@ -0,0 +1,478 @@
+/*-------------------------------------------------------------------------
+ *
+ * walreceiver.h
+ * Exports from replication/walreceiverfuncs.c.
+ *
+ * Portions Copyright (c) 2010-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/walreceiver.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _WALRECEIVER_H
+#define _WALRECEIVER_H
+
+#include
+#include
+
+#include "access/xlog.h"
+#include "access/xlogdefs.h"
+#include "pgtime.h"
+#include "port/atomics.h"
+#include "replication/logicalproto.h"
+#include "replication/walsender.h"
+#include "storage/condition_variable.h"
+#include "storage/latch.h"
+#include "storage/spin.h"
+#include "utils/tuplestore.h"
+
+/* user-settable parameters */
+extern PGDLLIMPORT int wal_receiver_status_interval;
+extern PGDLLIMPORT int wal_receiver_timeout;
+extern PGDLLIMPORT bool hot_standby_feedback;
+
+/*
+ * MAXCONNINFO: maximum size of a connection string.
+ *
+ * XXX: Should this move to pg_config_manual.h?
+ */
+#define MAXCONNINFO 1024
+
+/* Can we allow the standby to accept replication connection from another standby? */
+#define AllowCascadeReplication() (EnableHotStandby && max_wal_senders > 0)
+
+/*
+ * Values for WalRcv->walRcvState.
+ */
+typedef enum
+{
+ WALRCV_STOPPED, /* stopped and mustn't start up again */
+ WALRCV_STARTING, /* launched, but the process hasn't
+ * initialized yet */
+ WALRCV_STREAMING, /* walreceiver is streaming */
+ WALRCV_WAITING, /* stopped streaming, waiting for orders */
+ WALRCV_RESTARTING, /* asked to restart streaming */
+ WALRCV_STOPPING /* requested to stop, but still running */
+} WalRcvState;
+
+/* Shared memory area for management of walreceiver process */
+typedef struct
+{
+ /*
+ * PID of currently active walreceiver process, its current state and
+ * start time (actually, the time at which it was requested to be
+ * started).
+ */
+ pid_t pid;
+ WalRcvState walRcvState;
+ ConditionVariable walRcvStoppedCV;
+ pg_time_t startTime;
+
+ /*
+ * receiveStart and receiveStartTLI indicate the first byte position and
+ * timeline that will be received. When startup process starts the
+ * walreceiver, it sets these to the point where it wants the streaming to
+ * begin.
+ */
+ XLogRecPtr receiveStart;
+ TimeLineID receiveStartTLI;
+
+ /*
+ * flushedUpto-1 is the last byte position that has already been received,
+ * and receivedTLI is the timeline it came from. At the first startup of
+ * walreceiver, these are set to receiveStart and receiveStartTLI. After
+ * that, walreceiver updates these whenever it flushes the received WAL to
+ * disk.
+ */
+ XLogRecPtr flushedUpto;
+ TimeLineID receivedTLI;
+
+ /*
+ * latestChunkStart is the starting byte position of the current "batch"
+ * of received WAL. It's actually the same as the previous value of
+ * flushedUpto before the last flush to disk. Startup process can use
+ * this to detect whether it's keeping up or not.
+ */
+ XLogRecPtr latestChunkStart;
+
+ /*
+ * Time of send and receive of any message received.
+ */
+ TimestampTz lastMsgSendTime;
+ TimestampTz lastMsgReceiptTime;
+
+ /*
+ * Latest reported end of WAL on the sender
+ */
+ XLogRecPtr latestWalEnd;
+ TimestampTz latestWalEndTime;
+
+ /*
+ * connection string; initially set to connect to the primary, and later
+ * clobbered to hide security-sensitive fields.
+ */
+ char conninfo[MAXCONNINFO];
+
+ /*
+ * Host name (this can be a host name, an IP address, or a directory path)
+ * and port number of the active replication connection.
+ */
+ char sender_host[NI_MAXHOST];
+ int sender_port;
+
+ /*
+ * replication slot name; is also used for walreceiver to connect with the
+ * primary
+ */
+ char slotname[NAMEDATALEN];
+
+ /*
+ * If it's a temporary replication slot, it needs to be recreated when
+ * connecting.
+ */
+ bool is_temp_slot;
+
+ /* set true once conninfo is ready to display (obfuscated pwds etc) */
+ bool ready_to_display;
+
+ /*
+ * Latch used by startup process to wake up walreceiver after telling it
+ * where to start streaming (after setting receiveStart and
+ * receiveStartTLI), and also to tell it to send apply feedback to the
+ * primary whenever specially marked commit records are applied. This is
+ * normally mapped to procLatch when walreceiver is running.
+ */
+ Latch *latch;
+
+ slock_t mutex; /* locks shared variables shown above */
+
+ /*
+ * Like flushedUpto, but advanced after writing and before flushing,
+ * without the need to acquire the spin lock. Data can be read by another
+ * process up to this point, but shouldn't be used for data integrity
+ * purposes.
+ */
+ pg_atomic_uint64 writtenUpto;
+
+ /*
+ * force walreceiver reply? This doesn't need to be locked; memory
+ * barriers for ordering are sufficient. But we do need atomic fetch and
+ * store semantics, so use sig_atomic_t.
+ */
+ sig_atomic_t force_reply; /* used as a bool */
+} WalRcvData;
+
+extern PGDLLIMPORT WalRcvData *WalRcv;
+
+typedef struct
+{
+ bool logical; /* True if this is logical replication stream,
+ * false if physical stream. */
+ char *slotname; /* Name of the replication slot or NULL. */
+ XLogRecPtr startpoint; /* LSN of starting point. */
+
+ union
+ {
+ struct
+ {
+ TimeLineID startpointTLI; /* Starting timeline */
+ } physical;
+ struct
+ {
+ uint32 proto_version; /* Logical protocol version */
+ List *publication_names; /* String list of publications */
+ bool binary; /* Ask publisher to use binary */
+ char *streaming_str; /* Streaming of large transactions */
+ bool twophase; /* Streaming of two-phase transactions at
+ * prepare time */
+ char *origin; /* Only publish data originating from the
+ * specified origin */
+ } logical;
+ } proto;
+} WalRcvStreamOptions;
+
+struct WalReceiverConn;
+typedef struct WalReceiverConn WalReceiverConn;
+
+/*
+ * Status of walreceiver query execution.
+ *
+ * We only define statuses that are currently used.
+ */
+typedef enum
+{
+ WALRCV_ERROR, /* There was error when executing the query. */
+ WALRCV_OK_COMMAND, /* Query executed utility or replication
+ * command. */
+ WALRCV_OK_TUPLES, /* Query returned tuples. */
+ WALRCV_OK_COPY_IN, /* Query started COPY FROM. */
+ WALRCV_OK_COPY_OUT, /* Query started COPY TO. */
+ WALRCV_OK_COPY_BOTH /* Query started COPY BOTH replication
+ * protocol. */
+} WalRcvExecStatus;
+
+/*
+ * Return value for walrcv_exec, returns the status of the execution and
+ * tuples if any.
+ */
+typedef struct WalRcvExecResult
+{
+ WalRcvExecStatus status;
+ int sqlstate;
+ char *err;
+ Tuplestorestate *tuplestore;
+ TupleDesc tupledesc;
+} WalRcvExecResult;
+
+/* WAL receiver - libpqwalreceiver hooks */
+
+/*
+ * walrcv_connect_fn
+ *
+ * Establish connection to a cluster. 'logical' is true if the
+ * connection is logical, and false if the connection is physical.
+ * 'appname' is a name associated to the connection, to use for example
+ * with fallback_application_name or application_name. Returns the
+ * details about the connection established, as defined by
+ * WalReceiverConn for each WAL receiver module. On error, NULL is
+ * returned with 'err' including the error generated.
+ */
+typedef WalReceiverConn *(*walrcv_connect_fn) (const char *conninfo,
+ bool logical,
+ bool must_use_password,
+ const char *appname,
+ char **err);
+
+/*
+ * walrcv_check_conninfo_fn
+ *
+ * Parse and validate the connection string given as of 'conninfo'.
+ */
+typedef void (*walrcv_check_conninfo_fn) (const char *conninfo,
+ bool must_use_password);
+
+/*
+ * walrcv_get_conninfo_fn
+ *
+ * Returns a user-displayable conninfo string. Note that any
+ * security-sensitive fields should be obfuscated.
+ */
+typedef char *(*walrcv_get_conninfo_fn) (WalReceiverConn *conn);
+
+/*
+ * walrcv_get_senderinfo_fn
+ *
+ * Provide information of the WAL sender this WAL receiver is connected
+ * to, as of 'sender_host' for the host of the sender and 'sender_port'
+ * for its port.
+ */
+typedef void (*walrcv_get_senderinfo_fn) (WalReceiverConn *conn,
+ char **sender_host,
+ int *sender_port);
+
+/*
+ * walrcv_identify_system_fn
+ *
+ * Run IDENTIFY_SYSTEM on the cluster connected to and validate the
+ * identity of the cluster. Returns the system ID of the cluster
+ * connected to. 'primary_tli' is the timeline ID of the sender.
+ */
+typedef char *(*walrcv_identify_system_fn) (WalReceiverConn *conn,
+ TimeLineID *primary_tli);
+
+/*
+ * walrcv_server_version_fn
+ *
+ * Returns the version number of the cluster connected to.
+ */
+typedef int (*walrcv_server_version_fn) (WalReceiverConn *conn);
+
+/*
+ * walrcv_readtimelinehistoryfile_fn
+ *
+ * Fetch from cluster the timeline history file for timeline 'tli'.
+ * Returns the name of the timeline history file as of 'filename', its
+ * contents as of 'content' and its 'size'.
+ */
+typedef void (*walrcv_readtimelinehistoryfile_fn) (WalReceiverConn *conn,
+ TimeLineID tli,
+ char **filename,
+ char **content,
+ int *size);
+
+/*
+ * walrcv_startstreaming_fn
+ *
+ * Start streaming WAL data from given streaming options. Returns true
+ * if the connection has switched successfully to copy-both mode and false
+ * if the server received the command and executed it successfully, but
+ * didn't switch to copy-mode.
+ */
+typedef bool (*walrcv_startstreaming_fn) (WalReceiverConn *conn,
+ const WalRcvStreamOptions *options);
+
+/*
+ * walrcv_endstreaming_fn
+ *
+ * Stop streaming of WAL data. Returns the next timeline ID of the cluster
+ * connected to in 'next_tli', or 0 if there was no report.
+ */
+typedef void (*walrcv_endstreaming_fn) (WalReceiverConn *conn,
+ TimeLineID *next_tli);
+
+/*
+ * walrcv_receive_fn
+ *
+ * Receive a message available from the WAL stream. 'buffer' is a pointer
+ * to a buffer holding the message received. Returns the length of the data,
+ * 0 if no data is available yet ('wait_fd' is a socket descriptor which can
+ * be waited on before a retry), and -1 if the cluster ended the COPY.
+ */
+typedef int (*walrcv_receive_fn) (WalReceiverConn *conn,
+ char **buffer,
+ pgsocket *wait_fd);
+
+/*
+ * walrcv_send_fn
+ *
+ * Send a message of size 'nbytes' to the WAL stream with 'buffer' as
+ * contents.
+ */
+typedef void (*walrcv_send_fn) (WalReceiverConn *conn,
+ const char *buffer,
+ int nbytes);
+
+/*
+ * walrcv_create_slot_fn
+ *
+ * Create a new replication slot named 'slotname'. 'temporary' defines
+ * if the slot is temporary. 'snapshot_action' defines the behavior wanted
+ * for an exported snapshot (see replication protocol for more details).
+ * 'lsn' includes the LSN position at which the created slot became
+ * consistent. Returns the name of the exported snapshot for a logical
+ * slot, or NULL for a physical slot.
+ */
+typedef char *(*walrcv_create_slot_fn) (WalReceiverConn *conn,
+ const char *slotname,
+ bool temporary,
+ bool two_phase,
+ CRSSnapshotAction snapshot_action,
+ XLogRecPtr *lsn);
+
+/*
+ * walrcv_get_backend_pid_fn
+ *
+ * Returns the PID of the remote backend process.
+ */
+typedef pid_t (*walrcv_get_backend_pid_fn) (WalReceiverConn *conn);
+
+/*
+ * walrcv_exec_fn
+ *
+ * Send generic queries (and commands) to the remote cluster. 'nRetTypes'
+ * is the expected number of returned attributes, and 'retTypes' an array
+ * including their type OIDs. Returns the status of the execution and
+ * tuples if any.
+ */
+typedef WalRcvExecResult *(*walrcv_exec_fn) (WalReceiverConn *conn,
+ const char *query,
+ const int nRetTypes,
+ const Oid *retTypes);
+
+/*
+ * walrcv_disconnect_fn
+ *
+ * Disconnect with the cluster.
+ */
+typedef void (*walrcv_disconnect_fn) (WalReceiverConn *conn);
+
+typedef struct WalReceiverFunctionsType
+{
+ walrcv_connect_fn walrcv_connect;
+ walrcv_check_conninfo_fn walrcv_check_conninfo;
+ walrcv_get_conninfo_fn walrcv_get_conninfo;
+ walrcv_get_senderinfo_fn walrcv_get_senderinfo;
+ walrcv_identify_system_fn walrcv_identify_system;
+ walrcv_server_version_fn walrcv_server_version;
+ walrcv_readtimelinehistoryfile_fn walrcv_readtimelinehistoryfile;
+ walrcv_startstreaming_fn walrcv_startstreaming;
+ walrcv_endstreaming_fn walrcv_endstreaming;
+ walrcv_receive_fn walrcv_receive;
+ walrcv_send_fn walrcv_send;
+ walrcv_create_slot_fn walrcv_create_slot;
+ walrcv_get_backend_pid_fn walrcv_get_backend_pid;
+ walrcv_exec_fn walrcv_exec;
+ walrcv_disconnect_fn walrcv_disconnect;
+} WalReceiverFunctionsType;
+
+extern PGDLLIMPORT WalReceiverFunctionsType *WalReceiverFunctions;
+
+#define walrcv_connect(conninfo, logical, must_use_password, appname, err) \
+ WalReceiverFunctions->walrcv_connect(conninfo, logical, must_use_password, appname, err)
+#define walrcv_check_conninfo(conninfo, must_use_password) \
+ WalReceiverFunctions->walrcv_check_conninfo(conninfo, must_use_password)
+#define walrcv_get_conninfo(conn) \
+ WalReceiverFunctions->walrcv_get_conninfo(conn)
+#define walrcv_get_senderinfo(conn, sender_host, sender_port) \
+ WalReceiverFunctions->walrcv_get_senderinfo(conn, sender_host, sender_port)
+#define walrcv_identify_system(conn, primary_tli) \
+ WalReceiverFunctions->walrcv_identify_system(conn, primary_tli)
+#define walrcv_server_version(conn) \
+ WalReceiverFunctions->walrcv_server_version(conn)
+#define walrcv_readtimelinehistoryfile(conn, tli, filename, content, size) \
+ WalReceiverFunctions->walrcv_readtimelinehistoryfile(conn, tli, filename, content, size)
+#define walrcv_startstreaming(conn, options) \
+ WalReceiverFunctions->walrcv_startstreaming(conn, options)
+#define walrcv_endstreaming(conn, next_tli) \
+ WalReceiverFunctions->walrcv_endstreaming(conn, next_tli)
+#define walrcv_receive(conn, buffer, wait_fd) \
+ WalReceiverFunctions->walrcv_receive(conn, buffer, wait_fd)
+#define walrcv_send(conn, buffer, nbytes) \
+ WalReceiverFunctions->walrcv_send(conn, buffer, nbytes)
+#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn) \
+ WalReceiverFunctions->walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
+#define walrcv_get_backend_pid(conn) \
+ WalReceiverFunctions->walrcv_get_backend_pid(conn)
+#define walrcv_exec(conn, exec, nRetTypes, retTypes) \
+ WalReceiverFunctions->walrcv_exec(conn, exec, nRetTypes, retTypes)
+#define walrcv_disconnect(conn) \
+ WalReceiverFunctions->walrcv_disconnect(conn)
+
+static inline void
+walrcv_clear_result(WalRcvExecResult *walres)
+{
+ if (!walres)
+ return;
+
+ if (walres->err)
+ pfree(walres->err);
+
+ if (walres->tuplestore)
+ tuplestore_end(walres->tuplestore);
+
+ if (walres->tupledesc)
+ FreeTupleDesc(walres->tupledesc);
+
+ pfree(walres);
+}
+
+/* prototypes for functions in walreceiver.c */
+extern void WalReceiverMain(void) pg_attribute_noreturn();
+extern void ProcessWalRcvInterrupts(void);
+extern void WalRcvForceReply(void);
+
+/* prototypes for functions in walreceiverfuncs.c */
+extern Size WalRcvShmemSize(void);
+extern void WalRcvShmemInit(void);
+extern void ShutdownWalRcv(void);
+extern bool WalRcvStreaming(void);
+extern bool WalRcvRunning(void);
+extern void RequestXLogStreaming(TimeLineID tli, XLogRecPtr recptr,
+ const char *conninfo, const char *slotname,
+ bool create_temp_slot);
+extern XLogRecPtr GetWalRcvFlushRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI);
+extern XLogRecPtr GetWalRcvWriteRecPtr(void);
+extern int GetReplicationApplyDelay(void);
+extern int GetReplicationTransferLatency(void);
+
+#endif /* _WALRECEIVER_H */
diff --git a/pgsql/include/server/replication/walsender.h b/pgsql/include/server/replication/walsender.h
new file mode 100644
index 0000000000000000000000000000000000000000..9df7e50f9430544539020af58b9acdd0dbcd6859
--- /dev/null
+++ b/pgsql/include/server/replication/walsender.h
@@ -0,0 +1,74 @@
+/*-------------------------------------------------------------------------
+ *
+ * walsender.h
+ * Exports from replication/walsender.c.
+ *
+ * Portions Copyright (c) 2010-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/walsender.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _WALSENDER_H
+#define _WALSENDER_H
+
+#include
+
+/*
+ * What to do with a snapshot in create replication slot command.
+ */
+typedef enum
+{
+ CRS_EXPORT_SNAPSHOT,
+ CRS_NOEXPORT_SNAPSHOT,
+ CRS_USE_SNAPSHOT
+} CRSSnapshotAction;
+
+/* global state */
+extern PGDLLIMPORT bool am_walsender;
+extern PGDLLIMPORT bool am_cascading_walsender;
+extern PGDLLIMPORT bool am_db_walsender;
+extern PGDLLIMPORT bool wake_wal_senders;
+
+/* user-settable parameters */
+extern PGDLLIMPORT int max_wal_senders;
+extern PGDLLIMPORT int wal_sender_timeout;
+extern PGDLLIMPORT bool log_replication_commands;
+
+extern void InitWalSender(void);
+extern bool exec_replication_command(const char *cmd_string);
+extern void WalSndErrorCleanup(void);
+extern void WalSndResourceCleanup(bool isCommit);
+extern void WalSndSignals(void);
+extern Size WalSndShmemSize(void);
+extern void WalSndShmemInit(void);
+extern void WalSndWakeup(bool physical, bool logical);
+extern void WalSndInitStopping(void);
+extern void WalSndWaitStopping(void);
+extern void HandleWalSndInitStopping(void);
+extern void WalSndRqstFileReload(void);
+
+/*
+ * Remember that we want to wakeup walsenders later
+ *
+ * This is separated from doing the actual wakeup because the writeout is done
+ * while holding contended locks.
+ */
+#define WalSndWakeupRequest() \
+ do { wake_wal_senders = true; } while (0)
+
+/*
+ * wakeup walsenders if there is work to be done
+ */
+static inline void
+WalSndWakeupProcessRequests(bool physical, bool logical)
+{
+ if (wake_wal_senders)
+ {
+ wake_wal_senders = false;
+ if (max_wal_senders > 0)
+ WalSndWakeup(physical, logical);
+ }
+}
+
+#endif /* _WALSENDER_H */
diff --git a/pgsql/include/server/replication/walsender_private.h b/pgsql/include/server/replication/walsender_private.h
new file mode 100644
index 0000000000000000000000000000000000000000..7d919583bd36af765244bd36c01ddbc4676d2b18
--- /dev/null
+++ b/pgsql/include/server/replication/walsender_private.h
@@ -0,0 +1,137 @@
+/*-------------------------------------------------------------------------
+ *
+ * walsender_private.h
+ * Private definitions from replication/walsender.c.
+ *
+ * Portions Copyright (c) 2010-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/walsender_private.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _WALSENDER_PRIVATE_H
+#define _WALSENDER_PRIVATE_H
+
+#include "access/xlog.h"
+#include "lib/ilist.h"
+#include "nodes/nodes.h"
+#include "nodes/replnodes.h"
+#include "replication/syncrep.h"
+#include "storage/condition_variable.h"
+#include "storage/latch.h"
+#include "storage/shmem.h"
+#include "storage/spin.h"
+
+typedef enum WalSndState
+{
+ WALSNDSTATE_STARTUP = 0,
+ WALSNDSTATE_BACKUP,
+ WALSNDSTATE_CATCHUP,
+ WALSNDSTATE_STREAMING,
+ WALSNDSTATE_STOPPING
+} WalSndState;
+
+/*
+ * Each walsender has a WalSnd struct in shared memory.
+ *
+ * This struct is protected by its 'mutex' spinlock field, except that some
+ * members are only written by the walsender process itself, and thus that
+ * process is free to read those members without holding spinlock. pid and
+ * needreload always require the spinlock to be held for all accesses.
+ */
+typedef struct WalSnd
+{
+ pid_t pid; /* this walsender's PID, or 0 if not active */
+
+ WalSndState state; /* this walsender's state */
+ XLogRecPtr sentPtr; /* WAL has been sent up to this point */
+ bool needreload; /* does currently-open file need to be
+ * reloaded? */
+
+ /*
+ * The xlog locations that have been written, flushed, and applied by
+ * standby-side. These may be invalid if the standby-side has not offered
+ * values yet.
+ */
+ XLogRecPtr write;
+ XLogRecPtr flush;
+ XLogRecPtr apply;
+
+ /* Measured lag times, or -1 for unknown/none. */
+ TimeOffset writeLag;
+ TimeOffset flushLag;
+ TimeOffset applyLag;
+
+ /*
+ * The priority order of the standby managed by this WALSender, as listed
+ * in synchronous_standby_names, or 0 if not-listed.
+ */
+ int sync_standby_priority;
+
+ /* Protects shared variables in this structure. */
+ slock_t mutex;
+
+ /*
+ * Pointer to the walsender's latch. Used by backends to wake up this
+ * walsender when it has work to do. NULL if the walsender isn't active.
+ */
+ Latch *latch;
+
+ /*
+ * Timestamp of the last message received from standby.
+ */
+ TimestampTz replyTime;
+
+ ReplicationKind kind;
+} WalSnd;
+
+extern PGDLLIMPORT WalSnd *MyWalSnd;
+
+/* There is one WalSndCtl struct for the whole database cluster */
+typedef struct
+{
+ /*
+ * Synchronous replication queue with one queue per request type.
+ * Protected by SyncRepLock.
+ */
+ dlist_head SyncRepQueue[NUM_SYNC_REP_WAIT_MODE];
+
+ /*
+ * Current location of the head of the queue. All waiters should have a
+ * waitLSN that follows this value. Protected by SyncRepLock.
+ */
+ XLogRecPtr lsn[NUM_SYNC_REP_WAIT_MODE];
+
+ /*
+ * Are any sync standbys defined? Waiting backends can't reload the
+ * config file safely, so checkpointer updates this value as needed.
+ * Protected by SyncRepLock.
+ */
+ bool sync_standbys_defined;
+
+ /* used as a registry of physical / logical walsenders to wake */
+ ConditionVariable wal_flush_cv;
+ ConditionVariable wal_replay_cv;
+
+ WalSnd walsnds[FLEXIBLE_ARRAY_MEMBER];
+} WalSndCtlData;
+
+extern PGDLLIMPORT WalSndCtlData *WalSndCtl;
+
+
+extern void WalSndSetState(WalSndState state);
+
+/*
+ * Internal functions for parsing the replication grammar, in repl_gram.y and
+ * repl_scanner.l
+ */
+extern int replication_yyparse(void);
+extern int replication_yylex(void);
+extern void replication_yyerror(const char *message) pg_attribute_noreturn();
+extern void replication_scanner_init(const char *str);
+extern void replication_scanner_finish(void);
+extern bool replication_scanner_is_replication_command(void);
+
+extern PGDLLIMPORT Node *replication_parse_result;
+
+#endif /* _WALSENDER_PRIVATE_H */
diff --git a/pgsql/include/server/replication/worker_internal.h b/pgsql/include/server/replication/worker_internal.h
new file mode 100644
index 0000000000000000000000000000000000000000..343e7818965aa94eedf95eb32ddd6cdb048ced92
--- /dev/null
+++ b/pgsql/include/server/replication/worker_internal.h
@@ -0,0 +1,329 @@
+/*-------------------------------------------------------------------------
+ *
+ * worker_internal.h
+ * Internal headers shared by logical replication workers.
+ *
+ * Portions Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * src/include/replication/worker_internal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef WORKER_INTERNAL_H
+#define WORKER_INTERNAL_H
+
+#include
+
+#include "access/xlogdefs.h"
+#include "catalog/pg_subscription.h"
+#include "datatype/timestamp.h"
+#include "miscadmin.h"
+#include "replication/logicalrelation.h"
+#include "storage/buffile.h"
+#include "storage/fileset.h"
+#include "storage/lock.h"
+#include "storage/shm_mq.h"
+#include "storage/shm_toc.h"
+#include "storage/spin.h"
+
+
+typedef struct LogicalRepWorker
+{
+ /* Time at which this worker was launched. */
+ TimestampTz launch_time;
+
+ /* Indicates if this slot is used or free. */
+ bool in_use;
+
+ /* Increased every time the slot is taken by new worker. */
+ uint16 generation;
+
+ /* Pointer to proc array. NULL if not running. */
+ PGPROC *proc;
+
+ /* Database id to connect to. */
+ Oid dbid;
+
+ /* User to use for connection (will be same as owner of subscription). */
+ Oid userid;
+
+ /* Subscription id for the worker. */
+ Oid subid;
+
+ /* Used for initial table synchronization. */
+ Oid relid;
+ char relstate;
+ XLogRecPtr relstate_lsn;
+ slock_t relmutex;
+
+ /*
+ * Used to create the changes and subxact files for the streaming
+ * transactions. Upon the arrival of the first streaming transaction or
+ * when the first-time leader apply worker times out while sending changes
+ * to the parallel apply worker, the fileset will be initialized, and it
+ * will be deleted when the worker exits. Under this, separate buffiles
+ * would be created for each transaction which will be deleted after the
+ * transaction is finished.
+ */
+ FileSet *stream_fileset;
+
+ /*
+ * PID of leader apply worker if this slot is used for a parallel apply
+ * worker, InvalidPid otherwise.
+ */
+ pid_t leader_pid;
+
+ /* Indicates whether apply can be performed in parallel. */
+ bool parallel_apply;
+
+ /* Stats. */
+ XLogRecPtr last_lsn;
+ TimestampTz last_send_time;
+ TimestampTz last_recv_time;
+ XLogRecPtr reply_lsn;
+ TimestampTz reply_time;
+} LogicalRepWorker;
+
+/*
+ * State of the transaction in parallel apply worker.
+ *
+ * The enum values must have the same order as the transaction state
+ * transitions.
+ */
+typedef enum ParallelTransState
+{
+ PARALLEL_TRANS_UNKNOWN,
+ PARALLEL_TRANS_STARTED,
+ PARALLEL_TRANS_FINISHED
+} ParallelTransState;
+
+/*
+ * State of fileset used to communicate changes from leader to parallel
+ * apply worker.
+ *
+ * FS_EMPTY indicates an initial state where the leader doesn't need to use
+ * the file to communicate with the parallel apply worker.
+ *
+ * FS_SERIALIZE_IN_PROGRESS indicates that the leader is serializing changes
+ * to the file.
+ *
+ * FS_SERIALIZE_DONE indicates that the leader has serialized all changes to
+ * the file.
+ *
+ * FS_READY indicates that it is now ok for a parallel apply worker to
+ * read the file.
+ */
+typedef enum PartialFileSetState
+{
+ FS_EMPTY,
+ FS_SERIALIZE_IN_PROGRESS,
+ FS_SERIALIZE_DONE,
+ FS_READY
+} PartialFileSetState;
+
+/*
+ * Struct for sharing information between leader apply worker and parallel
+ * apply workers.
+ */
+typedef struct ParallelApplyWorkerShared
+{
+ slock_t mutex;
+
+ TransactionId xid;
+
+ /*
+ * State used to ensure commit ordering.
+ *
+ * The parallel apply worker will set it to PARALLEL_TRANS_FINISHED after
+ * handling the transaction finish commands while the apply leader will
+ * wait for it to become PARALLEL_TRANS_FINISHED before proceeding in
+ * transaction finish commands (e.g. STREAM_COMMIT/STREAM_PREPARE/
+ * STREAM_ABORT).
+ */
+ ParallelTransState xact_state;
+
+ /* Information from the corresponding LogicalRepWorker slot. */
+ uint16 logicalrep_worker_generation;
+ int logicalrep_worker_slot_no;
+
+ /*
+ * Indicates whether there are pending streaming blocks in the queue. The
+ * parallel apply worker will check it before starting to wait.
+ */
+ pg_atomic_uint32 pending_stream_count;
+
+ /*
+ * XactLastCommitEnd from the parallel apply worker. This is required by
+ * the leader worker so it can update the lsn_mappings.
+ */
+ XLogRecPtr last_commit_end;
+
+ /*
+ * After entering PARTIAL_SERIALIZE mode, the leader apply worker will
+ * serialize changes to the file, and share the fileset with the parallel
+ * apply worker when processing the transaction finish command. Then the
+ * parallel apply worker will apply all the spooled messages.
+ *
+ * FileSet is used here instead of SharedFileSet because we need it to
+ * survive after releasing the shared memory so that the leader apply
+ * worker can re-use the same fileset for the next streaming transaction.
+ */
+ PartialFileSetState fileset_state;
+ FileSet fileset;
+} ParallelApplyWorkerShared;
+
+/*
+ * Information which is used to manage the parallel apply worker.
+ */
+typedef struct ParallelApplyWorkerInfo
+{
+ /*
+ * This queue is used to send changes from the leader apply worker to the
+ * parallel apply worker.
+ */
+ shm_mq_handle *mq_handle;
+
+ /*
+ * This queue is used to transfer error messages from the parallel apply
+ * worker to the leader apply worker.
+ */
+ shm_mq_handle *error_mq_handle;
+
+ dsm_segment *dsm_seg;
+
+ /*
+ * Indicates whether the leader apply worker needs to serialize the
+ * remaining changes to a file due to timeout when attempting to send data
+ * to the parallel apply worker via shared memory.
+ */
+ bool serialize_changes;
+
+ /*
+ * True if the worker is being used to process a parallel apply
+ * transaction. False indicates this worker is available for re-use.
+ */
+ bool in_use;
+
+ ParallelApplyWorkerShared *shared;
+} ParallelApplyWorkerInfo;
+
+/* Main memory context for apply worker. Permanent during worker lifetime. */
+extern PGDLLIMPORT MemoryContext ApplyContext;
+
+extern PGDLLIMPORT MemoryContext ApplyMessageContext;
+
+extern PGDLLIMPORT ErrorContextCallback *apply_error_context_stack;
+
+extern PGDLLIMPORT ParallelApplyWorkerShared *MyParallelShared;
+
+/* libpqreceiver connection */
+extern PGDLLIMPORT struct WalReceiverConn *LogRepWorkerWalRcvConn;
+
+/* Worker and subscription objects. */
+extern PGDLLIMPORT Subscription *MySubscription;
+extern PGDLLIMPORT LogicalRepWorker *MyLogicalRepWorker;
+
+extern PGDLLIMPORT bool in_remote_transaction;
+
+extern PGDLLIMPORT bool InitializingApplyWorker;
+
+extern void logicalrep_worker_attach(int slot);
+extern LogicalRepWorker *logicalrep_worker_find(Oid subid, Oid relid,
+ bool only_running);
+extern List *logicalrep_workers_find(Oid subid, bool only_running);
+extern bool logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname,
+ Oid userid, Oid relid,
+ dsm_handle subworker_dsm);
+extern void logicalrep_worker_stop(Oid subid, Oid relid);
+extern void logicalrep_pa_worker_stop(ParallelApplyWorkerInfo *winfo);
+extern void logicalrep_worker_wakeup(Oid subid, Oid relid);
+extern void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker);
+
+extern int logicalrep_sync_worker_count(Oid subid);
+
+extern void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid,
+ char *originname, Size szoriginname);
+extern char *LogicalRepSyncTableStart(XLogRecPtr *origin_startpos);
+
+extern bool AllTablesyncsReady(void);
+extern void UpdateTwoPhaseState(Oid suboid, char new_state);
+
+extern void process_syncing_tables(XLogRecPtr current_lsn);
+extern void invalidate_syncing_table_states(Datum arg, int cacheid,
+ uint32 hashvalue);
+
+extern void stream_start_internal(TransactionId xid, bool first_segment);
+extern void stream_stop_internal(TransactionId xid);
+
+/* Common streaming function to apply all the spooled messages */
+extern void apply_spooled_messages(FileSet *stream_fileset, TransactionId xid,
+ XLogRecPtr lsn);
+
+extern void apply_dispatch(StringInfo s);
+
+extern void maybe_reread_subscription(void);
+
+extern void stream_cleanup_files(Oid subid, TransactionId xid);
+
+extern void InitializeApplyWorker(void);
+
+extern void store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn);
+
+/* Function for apply error callback */
+extern void apply_error_callback(void *arg);
+extern void set_apply_error_context_origin(char *originname);
+
+/* Parallel apply worker setup and interactions */
+extern void pa_allocate_worker(TransactionId xid);
+extern ParallelApplyWorkerInfo *pa_find_worker(TransactionId xid);
+extern void pa_detach_all_error_mq(void);
+
+extern bool pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes,
+ const void *data);
+extern void pa_switch_to_partial_serialize(ParallelApplyWorkerInfo *winfo,
+ bool stream_locked);
+
+extern void pa_set_xact_state(ParallelApplyWorkerShared *wshared,
+ ParallelTransState xact_state);
+extern void pa_set_stream_apply_worker(ParallelApplyWorkerInfo *winfo);
+
+extern void pa_start_subtrans(TransactionId current_xid,
+ TransactionId top_xid);
+extern void pa_reset_subtrans(void);
+extern void pa_stream_abort(LogicalRepStreamAbortData *abort_data);
+extern void pa_set_fileset_state(ParallelApplyWorkerShared *wshared,
+ PartialFileSetState fileset_state);
+
+extern void pa_lock_stream(TransactionId xid, LOCKMODE lockmode);
+extern void pa_unlock_stream(TransactionId xid, LOCKMODE lockmode);
+
+extern void pa_lock_transaction(TransactionId xid, LOCKMODE lockmode);
+extern void pa_unlock_transaction(TransactionId xid, LOCKMODE lockmode);
+
+extern void pa_decr_and_wait_stream_block(void);
+
+extern void pa_xact_finish(ParallelApplyWorkerInfo *winfo,
+ XLogRecPtr remote_lsn);
+
+#define isParallelApplyWorker(worker) ((worker)->leader_pid != InvalidPid)
+
+static inline bool
+am_tablesync_worker(void)
+{
+ return OidIsValid(MyLogicalRepWorker->relid);
+}
+
+static inline bool
+am_leader_apply_worker(void)
+{
+ return (!am_tablesync_worker() &&
+ !isParallelApplyWorker(MyLogicalRepWorker));
+}
+
+static inline bool
+am_parallel_apply_worker(void)
+{
+ return isParallelApplyWorker(MyLogicalRepWorker);
+}
+
+#endif /* WORKER_INTERNAL_H */
diff --git a/pgsql/include/server/rewrite/prs2lock.h b/pgsql/include/server/rewrite/prs2lock.h
new file mode 100644
index 0000000000000000000000000000000000000000..f94bdfd245e65ab97e6253a9a38ae5bc023bd3fe
--- /dev/null
+++ b/pgsql/include/server/rewrite/prs2lock.h
@@ -0,0 +1,46 @@
+/*-------------------------------------------------------------------------
+ *
+ * prs2lock.h
+ * data structures for POSTGRES Rule System II (rewrite rules only)
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/prs2lock.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PRS2LOCK_H
+#define PRS2LOCK_H
+
+#include "access/attnum.h"
+#include "nodes/pg_list.h"
+
+/*
+ * RewriteRule -
+ * holds an info for a rewrite rule
+ *
+ */
+typedef struct RewriteRule
+{
+ Oid ruleId;
+ CmdType event;
+ Node *qual;
+ List *actions;
+ char enabled;
+ bool isInstead;
+} RewriteRule;
+
+/*
+ * RuleLock -
+ * all rules that apply to a particular relation. Even though we only
+ * have the rewrite rule system left and these are not really "locks",
+ * the name is kept for historical reasons.
+ */
+typedef struct RuleLock
+{
+ int numLocks;
+ RewriteRule **rules;
+} RuleLock;
+
+#endif /* PRS2LOCK_H */
diff --git a/pgsql/include/server/rewrite/rewriteDefine.h b/pgsql/include/server/rewrite/rewriteDefine.h
new file mode 100644
index 0000000000000000000000000000000000000000..81a7ea034f399c9d1a405912477e78eda3ec7c85
--- /dev/null
+++ b/pgsql/include/server/rewrite/rewriteDefine.h
@@ -0,0 +1,44 @@
+/*-------------------------------------------------------------------------
+ *
+ * rewriteDefine.h
+ *
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/rewriteDefine.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REWRITEDEFINE_H
+#define REWRITEDEFINE_H
+
+#include "catalog/objectaddress.h"
+#include "nodes/parsenodes.h"
+#include "utils/relcache.h"
+
+#define RULE_FIRES_ON_ORIGIN 'O'
+#define RULE_FIRES_ALWAYS 'A'
+#define RULE_FIRES_ON_REPLICA 'R'
+#define RULE_DISABLED 'D'
+
+extern ObjectAddress DefineRule(RuleStmt *stmt, const char *queryString);
+
+extern ObjectAddress DefineQueryRewrite(const char *rulename,
+ Oid event_relid,
+ Node *event_qual,
+ CmdType event_type,
+ bool is_instead,
+ bool replace,
+ List *action);
+
+extern ObjectAddress RenameRewriteRule(RangeVar *relation, const char *oldName,
+ const char *newName);
+
+extern void setRuleCheckAsUser(Node *node, Oid userid);
+
+extern void EnableDisableRule(Relation rel, const char *rulename,
+ char fires_when);
+
+#endif /* REWRITEDEFINE_H */
diff --git a/pgsql/include/server/rewrite/rewriteHandler.h b/pgsql/include/server/rewrite/rewriteHandler.h
new file mode 100644
index 0000000000000000000000000000000000000000..b71e20b087c066ac93d2b08f9e3a3c2dad2d3b49
--- /dev/null
+++ b/pgsql/include/server/rewrite/rewriteHandler.h
@@ -0,0 +1,35 @@
+/*-------------------------------------------------------------------------
+ *
+ * rewriteHandler.h
+ * External interface to query rewriter.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/rewriteHandler.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REWRITEHANDLER_H
+#define REWRITEHANDLER_H
+
+#include "nodes/parsenodes.h"
+#include "utils/relcache.h"
+
+extern List *QueryRewrite(Query *parsetree);
+extern void AcquireRewriteLocks(Query *parsetree,
+ bool forExecute,
+ bool forUpdatePushedDown);
+
+extern Node *build_column_default(Relation rel, int attrno);
+
+extern Query *get_view_query(Relation view);
+extern const char *view_query_is_auto_updatable(Query *viewquery,
+ bool check_cols);
+extern int relation_is_updatable(Oid reloid,
+ List *outer_reloids,
+ bool include_triggers,
+ Bitmapset *include_cols);
+
+#endif /* REWRITEHANDLER_H */
diff --git a/pgsql/include/server/rewrite/rewriteManip.h b/pgsql/include/server/rewrite/rewriteManip.h
new file mode 100644
index 0000000000000000000000000000000000000000..365061fff44c3cc644826dc6f29cae40cc9119b7
--- /dev/null
+++ b/pgsql/include/server/rewrite/rewriteManip.h
@@ -0,0 +1,96 @@
+/*-------------------------------------------------------------------------
+ *
+ * rewriteManip.h
+ * Querytree manipulation subroutines for query rewriter.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/rewriteManip.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REWRITEMANIP_H
+#define REWRITEMANIP_H
+
+#include "nodes/parsenodes.h"
+
+struct AttrMap; /* avoid including attmap.h here */
+
+
+typedef struct replace_rte_variables_context replace_rte_variables_context;
+
+typedef Node *(*replace_rte_variables_callback) (Var *var,
+ replace_rte_variables_context *context);
+
+struct replace_rte_variables_context
+{
+ replace_rte_variables_callback callback; /* callback function */
+ void *callback_arg; /* context data for callback function */
+ int target_varno; /* RTE index to search for */
+ int sublevels_up; /* (current) nesting depth */
+ bool inserted_sublink; /* have we inserted a SubLink? */
+};
+
+typedef enum ReplaceVarsNoMatchOption
+{
+ REPLACEVARS_REPORT_ERROR, /* throw error if no match */
+ REPLACEVARS_CHANGE_VARNO, /* change the Var's varno, nothing else */
+ REPLACEVARS_SUBSTITUTE_NULL /* replace with a NULL Const */
+} ReplaceVarsNoMatchOption;
+
+
+extern void CombineRangeTables(List **dst_rtable, List **dst_perminfos,
+ List *src_rtable, List *src_perminfos);
+extern void OffsetVarNodes(Node *node, int offset, int sublevels_up);
+extern void ChangeVarNodes(Node *node, int rt_index, int new_index,
+ int sublevels_up);
+extern void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up,
+ int min_sublevels_up);
+extern void IncrementVarSublevelsUp_rtable(List *rtable,
+ int delta_sublevels_up, int min_sublevels_up);
+
+extern bool rangeTableEntry_used(Node *node, int rt_index,
+ int sublevels_up);
+
+extern Query *getInsertSelectQuery(Query *parsetree, Query ***subquery_ptr);
+
+extern void AddQual(Query *parsetree, Node *qual);
+extern void AddInvertedQual(Query *parsetree, Node *qual);
+
+extern bool contain_aggs_of_level(Node *node, int levelsup);
+extern int locate_agg_of_level(Node *node, int levelsup);
+extern bool contain_windowfuncs(Node *node);
+extern int locate_windowfunc(Node *node);
+extern bool checkExprHasSubLink(Node *node);
+
+extern Node *add_nulling_relids(Node *node,
+ const Bitmapset *target_relids,
+ const Bitmapset *added_relids);
+extern Node *remove_nulling_relids(Node *node,
+ const Bitmapset *removable_relids,
+ const Bitmapset *except_relids);
+
+extern Node *replace_rte_variables(Node *node,
+ int target_varno, int sublevels_up,
+ replace_rte_variables_callback callback,
+ void *callback_arg,
+ bool *outer_hasSubLinks);
+extern Node *replace_rte_variables_mutator(Node *node,
+ replace_rte_variables_context *context);
+
+extern Node *map_variable_attnos(Node *node,
+ int target_varno, int sublevels_up,
+ const struct AttrMap *attno_map,
+ Oid to_rowtype, bool *found_whole_row);
+
+extern Node *ReplaceVarsFromTargetList(Node *node,
+ int target_varno, int sublevels_up,
+ RangeTblEntry *target_rte,
+ List *targetlist,
+ ReplaceVarsNoMatchOption nomatch_option,
+ int nomatch_varno,
+ bool *outer_hasSubLinks);
+
+#endif /* REWRITEMANIP_H */
diff --git a/pgsql/include/server/rewrite/rewriteRemove.h b/pgsql/include/server/rewrite/rewriteRemove.h
new file mode 100644
index 0000000000000000000000000000000000000000..1413c11b66797d5e6c53f9eb05336289f191d6d1
--- /dev/null
+++ b/pgsql/include/server/rewrite/rewriteRemove.h
@@ -0,0 +1,21 @@
+/*-------------------------------------------------------------------------
+ *
+ * rewriteRemove.h
+ *
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/rewriteRemove.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REWRITEREMOVE_H
+#define REWRITEREMOVE_H
+
+#include "nodes/parsenodes.h"
+
+extern void RemoveRewriteRuleById(Oid ruleOid);
+
+#endif /* REWRITEREMOVE_H */
diff --git a/pgsql/include/server/rewrite/rewriteSearchCycle.h b/pgsql/include/server/rewrite/rewriteSearchCycle.h
new file mode 100644
index 0000000000000000000000000000000000000000..102db81dc4031270c64c0c108714afc38ffe583c
--- /dev/null
+++ b/pgsql/include/server/rewrite/rewriteSearchCycle.h
@@ -0,0 +1,21 @@
+/*-------------------------------------------------------------------------
+ *
+ * rewriteSearchCycle.h
+ * Support for rewriting SEARCH and CYCLE clauses.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/rewriteSearchCycle.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REWRITESEARCHCYCLE_H
+#define REWRITESEARCHCYCLE_H
+
+#include "nodes/parsenodes.h"
+
+extern CommonTableExpr *rewriteSearchAndCycle(CommonTableExpr *cte);
+
+#endif /* REWRITESEARCHCYCLE_H */
diff --git a/pgsql/include/server/rewrite/rewriteSupport.h b/pgsql/include/server/rewrite/rewriteSupport.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5dc367e23af3614c2180d595265fc792ccfd298
--- /dev/null
+++ b/pgsql/include/server/rewrite/rewriteSupport.h
@@ -0,0 +1,26 @@
+/*-------------------------------------------------------------------------
+ *
+ * rewriteSupport.h
+ *
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/rewrite/rewriteSupport.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REWRITESUPPORT_H
+#define REWRITESUPPORT_H
+
+/* The ON SELECT rule of a view is always named this: */
+#define ViewSelectRuleName "_RETURN"
+
+extern bool IsDefinedRewriteRule(Oid owningRel, const char *ruleName);
+
+extern void SetRelationRuleStatus(Oid relationId, bool relHasRules);
+
+extern Oid get_rewrite_oid(Oid relid, const char *rulename, bool missing_ok);
+
+#endif /* REWRITESUPPORT_H */
diff --git a/pgsql/include/server/rewrite/rowsecurity.h b/pgsql/include/server/rewrite/rowsecurity.h
new file mode 100644
index 0000000000000000000000000000000000000000..d20843572347644895584a244c3c406e975c0132
--- /dev/null
+++ b/pgsql/include/server/rewrite/rowsecurity.h
@@ -0,0 +1,49 @@
+/* -------------------------------------------------------------------------
+ *
+ * rowsecurity.h
+ *
+ * prototypes for rewrite/rowsecurity.c and the structures for managing
+ * the row security policies for relations in relcache.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * -------------------------------------------------------------------------
+ */
+#ifndef ROWSECURITY_H
+#define ROWSECURITY_H
+
+#include "nodes/parsenodes.h"
+#include "utils/array.h"
+#include "utils/relcache.h"
+
+typedef struct RowSecurityPolicy
+{
+ char *policy_name; /* Name of the policy */
+ char polcmd; /* Type of command policy is for */
+ ArrayType *roles; /* Array of roles policy is for */
+ bool permissive; /* restrictive or permissive policy */
+ Expr *qual; /* Expression to filter rows */
+ Expr *with_check_qual; /* Expression to limit rows allowed */
+ bool hassublinks; /* If either expression has sublinks */
+} RowSecurityPolicy;
+
+typedef struct RowSecurityDesc
+{
+ MemoryContext rscxt; /* row security memory context */
+ List *policies; /* list of row security policies */
+} RowSecurityDesc;
+
+typedef List *(*row_security_policy_hook_type) (CmdType cmdtype,
+ Relation relation);
+
+extern PGDLLIMPORT row_security_policy_hook_type row_security_policy_hook_permissive;
+
+extern PGDLLIMPORT row_security_policy_hook_type row_security_policy_hook_restrictive;
+
+extern void get_row_security_policies(Query *root,
+ RangeTblEntry *rte, int rt_index,
+ List **securityQuals, List **withCheckOptions,
+ bool *hasRowSecurity, bool *hasSubLinks);
+
+#endif /* ROWSECURITY_H */
diff --git a/pgsql/include/server/snowball/header.h b/pgsql/include/server/snowball/header.h
new file mode 100644
index 0000000000000000000000000000000000000000..dbf04e39657c690e89310faa842e5e72e09199bf
--- /dev/null
+++ b/pgsql/include/server/snowball/header.h
@@ -0,0 +1,67 @@
+/*-------------------------------------------------------------------------
+ *
+ * header.h
+ * Replacement header file for Snowball stemmer modules
+ *
+ * The Snowball stemmer modules do #include "header.h", and think they
+ * are including snowball/libstemmer/header.h. We adjust the CPPFLAGS
+ * so that this file is found instead, and thereby we can modify the
+ * headers they see. The main point here is to ensure that pg_config.h
+ * is included before any system headers such as ; without that,
+ * we have portability issues on some platforms due to variation in
+ * largefile options across different modules in the backend.
+ *
+ * NOTE: this file should not be included into any non-snowball sources!
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/snowball/header.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SNOWBALL_HEADR_H
+#define SNOWBALL_HEADR_H
+
+/*
+ * It's against Postgres coding conventions to include postgres.h in a
+ * header file, but we allow the violation here because the alternative is
+ * to modify the machine-generated .c files provided by the Snowball project.
+ */
+#include "postgres.h"
+
+/* Some platforms define MAXINT and/or MININT, causing conflicts */
+#ifdef MAXINT
+#undef MAXINT
+#endif
+#ifdef MININT
+#undef MININT
+#endif
+
+/* Now we can include the original Snowball header.h */
+#include "snowball/libstemmer/header.h" /* pgrminclude ignore */
+
+/*
+ * Redefine standard memory allocation interface to pgsql's one.
+ * This allows us to control where the Snowball code allocates stuff.
+ */
+#ifdef malloc
+#undef malloc
+#endif
+#define malloc(a) palloc(a)
+
+#ifdef calloc
+#undef calloc
+#endif
+#define calloc(a,b) palloc0((a) * (b))
+
+#ifdef realloc
+#undef realloc
+#endif
+#define realloc(a,b) repalloc(a,b)
+
+#ifdef free
+#undef free
+#endif
+#define free(a) pfree(a)
+
+#endif /* SNOWBALL_HEADR_H */
diff --git a/pgsql/include/server/snowball/libstemmer/api.h b/pgsql/include/server/snowball/libstemmer/api.h
new file mode 100644
index 0000000000000000000000000000000000000000..ba9d1c14bcae1f6e14a6d1154199099858e8a551
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/api.h
@@ -0,0 +1,32 @@
+
+typedef unsigned char symbol;
+
+/* Or replace 'char' above with 'short' for 16 bit characters.
+
+ More precisely, replace 'char' with whatever type guarantees the
+ character width you need. Note however that sizeof(symbol) should divide
+ HEAD, defined in header.h as 2*sizeof(int), without remainder, otherwise
+ there is an alignment problem. In the unlikely event of a problem here,
+ consult Martin Porter.
+
+*/
+
+struct SN_env {
+ symbol * p;
+ int c; int l; int lb; int bra; int ket;
+ symbol * * S;
+ int * I;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * SN_create_env(int S_size, int I_size);
+extern void SN_close_env(struct SN_env * z, int S_size);
+
+extern int SN_set_current(struct SN_env * z, int size, const symbol * s);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/pgsql/include/server/snowball/libstemmer/header.h b/pgsql/include/server/snowball/libstemmer/header.h
new file mode 100644
index 0000000000000000000000000000000000000000..ef5a5464067e927776470670913067b1aae078fd
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/header.h
@@ -0,0 +1,61 @@
+
+#include
+
+#include "api.h"
+
+#define MAXINT INT_MAX
+#define MININT INT_MIN
+
+#define HEAD 2*sizeof(int)
+
+#define SIZE(p) ((int *)(p))[-1]
+#define SET_SIZE(p, n) ((int *)(p))[-1] = n
+#define CAPACITY(p) ((int *)(p))[-2]
+
+struct among
+{ int s_size; /* number of chars in string */
+ const symbol * s; /* search string */
+ int substring_i;/* index to longest matching substring */
+ int result; /* result of the lookup */
+ int (* function)(struct SN_env *);
+};
+
+extern symbol * create_s(void);
+extern void lose_s(symbol * p);
+
+extern int skip_utf8(const symbol * p, int c, int limit, int n);
+
+extern int skip_b_utf8(const symbol * p, int c, int limit, int n);
+
+extern int in_grouping_U(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+extern int in_grouping_b_U(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+extern int out_grouping_U(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+extern int out_grouping_b_U(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+
+extern int in_grouping(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+extern int in_grouping_b(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+extern int out_grouping(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+extern int out_grouping_b(struct SN_env * z, const unsigned char * s, int min, int max, int repeat);
+
+extern int eq_s(struct SN_env * z, int s_size, const symbol * s);
+extern int eq_s_b(struct SN_env * z, int s_size, const symbol * s);
+extern int eq_v(struct SN_env * z, const symbol * p);
+extern int eq_v_b(struct SN_env * z, const symbol * p);
+
+extern int find_among(struct SN_env * z, const struct among * v, int v_size);
+extern int find_among_b(struct SN_env * z, const struct among * v, int v_size);
+
+extern int replace_s(struct SN_env * z, int c_bra, int c_ket, int s_size, const symbol * s, int * adjptr);
+extern int slice_from_s(struct SN_env * z, int s_size, const symbol * s);
+extern int slice_from_v(struct SN_env * z, const symbol * p);
+extern int slice_del(struct SN_env * z);
+
+extern int insert_s(struct SN_env * z, int bra, int ket, int s_size, const symbol * s);
+extern int insert_v(struct SN_env * z, int bra, int ket, const symbol * p);
+
+extern symbol * slice_to(struct SN_env * z, symbol * p);
+extern symbol * assign_to(struct SN_env * z, symbol * p);
+
+extern int len_utf8(const symbol * p);
+
+extern void debug(struct SN_env * z, int number, int line_count);
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_basque.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_basque.h
new file mode 100644
index 0000000000000000000000000000000000000000..bffb6e9043e1920695b59ef1c2c0ab1f47fae923
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_basque.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * basque_ISO_8859_1_create_env(void);
+extern void basque_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int basque_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_catalan.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_catalan.h
new file mode 100644
index 0000000000000000000000000000000000000000..96e97ddfa2a7b4585852802701930d6823622e52
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_catalan.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * catalan_ISO_8859_1_create_env(void);
+extern void catalan_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int catalan_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_danish.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_danish.h
new file mode 100644
index 0000000000000000000000000000000000000000..965436d9a1e259220113a117c63fd31740ae4bbc
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_danish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * danish_ISO_8859_1_create_env(void);
+extern void danish_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int danish_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_dutch.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_dutch.h
new file mode 100644
index 0000000000000000000000000000000000000000..64f1c6d916329e3a8b0198a13be95a72f001a1bb
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_dutch.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * dutch_ISO_8859_1_create_env(void);
+extern void dutch_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int dutch_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_english.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_english.h
new file mode 100644
index 0000000000000000000000000000000000000000..ea90984b0024643d4f5536f9073e90313ea318e3
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_english.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * english_ISO_8859_1_create_env(void);
+extern void english_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int english_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_finnish.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_finnish.h
new file mode 100644
index 0000000000000000000000000000000000000000..2c80e4cdead31e67e2687f2af1e7dda905b5b0b1
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_finnish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * finnish_ISO_8859_1_create_env(void);
+extern void finnish_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int finnish_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_french.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_french.h
new file mode 100644
index 0000000000000000000000000000000000000000..1febb49d20448fb08834e4576ec9ce72f1e1b0a3
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_french.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * french_ISO_8859_1_create_env(void);
+extern void french_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int french_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_german.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_german.h
new file mode 100644
index 0000000000000000000000000000000000000000..98696bb336dc9ab86f24381c57c957f8da49b96a
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_german.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * german_ISO_8859_1_create_env(void);
+extern void german_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int german_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_indonesian.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_indonesian.h
new file mode 100644
index 0000000000000000000000000000000000000000..d998b41b2cfb82ccedff20e786527f45e8bbd2e1
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_indonesian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * indonesian_ISO_8859_1_create_env(void);
+extern void indonesian_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int indonesian_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_irish.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_irish.h
new file mode 100644
index 0000000000000000000000000000000000000000..d91d231790614d89b38d843c45b2c260af7e7622
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_irish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * irish_ISO_8859_1_create_env(void);
+extern void irish_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int irish_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_italian.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_italian.h
new file mode 100644
index 0000000000000000000000000000000000000000..22950bd2347ebe6636196869d2e2178c99b6d734
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_italian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * italian_ISO_8859_1_create_env(void);
+extern void italian_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int italian_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_norwegian.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_norwegian.h
new file mode 100644
index 0000000000000000000000000000000000000000..53930960569253f0f823fc72cf1f0cd2295621cd
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_norwegian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * norwegian_ISO_8859_1_create_env(void);
+extern void norwegian_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int norwegian_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_porter.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_porter.h
new file mode 100644
index 0000000000000000000000000000000000000000..f504be101a60f77408f17273e1dc88cc9c9fd6e6
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_porter.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * porter_ISO_8859_1_create_env(void);
+extern void porter_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int porter_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_portuguese.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_portuguese.h
new file mode 100644
index 0000000000000000000000000000000000000000..c7b517c0912749233c52fa362f5ac604cdc063a9
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_portuguese.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * portuguese_ISO_8859_1_create_env(void);
+extern void portuguese_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int portuguese_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_spanish.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_spanish.h
new file mode 100644
index 0000000000000000000000000000000000000000..b066b4fc26fa2ba0cba5f8ba2f88bba4b5e1d46b
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_spanish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * spanish_ISO_8859_1_create_env(void);
+extern void spanish_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int spanish_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_swedish.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_swedish.h
new file mode 100644
index 0000000000000000000000000000000000000000..7b5ec75523c744831732aa43a104f75dc7a0f158
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_1_swedish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * swedish_ISO_8859_1_create_env(void);
+extern void swedish_ISO_8859_1_close_env(struct SN_env * z);
+
+extern int swedish_ISO_8859_1_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_2_hungarian.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_2_hungarian.h
new file mode 100644
index 0000000000000000000000000000000000000000..be6ebf685ab2ba3a1838b8ad89ece116ecabeac7
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_2_hungarian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * hungarian_ISO_8859_2_create_env(void);
+extern void hungarian_ISO_8859_2_close_env(struct SN_env * z);
+
+extern int hungarian_ISO_8859_2_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_2_romanian.h b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_2_romanian.h
new file mode 100644
index 0000000000000000000000000000000000000000..a7acc38e17d468bc9de8d854069b1604229c0882
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_ISO_8859_2_romanian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * romanian_ISO_8859_2_create_env(void);
+extern void romanian_ISO_8859_2_close_env(struct SN_env * z);
+
+extern int romanian_ISO_8859_2_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_KOI8_R_russian.h b/pgsql/include/server/snowball/libstemmer/stem_KOI8_R_russian.h
new file mode 100644
index 0000000000000000000000000000000000000000..42a8518b953fb8ab87d3697d7bf66bdae6f74cf1
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_KOI8_R_russian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * russian_KOI8_R_create_env(void);
+extern void russian_KOI8_R_close_env(struct SN_env * z);
+
+extern int russian_KOI8_R_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_arabic.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_arabic.h
new file mode 100644
index 0000000000000000000000000000000000000000..cad02f3453a920a3d9226b3aa7abbce88ba88af0
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_arabic.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * arabic_UTF_8_create_env(void);
+extern void arabic_UTF_8_close_env(struct SN_env * z);
+
+extern int arabic_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_armenian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_armenian.h
new file mode 100644
index 0000000000000000000000000000000000000000..793fd09e6c07abe1c3c4890be99584dc6ca75636
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_armenian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * armenian_UTF_8_create_env(void);
+extern void armenian_UTF_8_close_env(struct SN_env * z);
+
+extern int armenian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_basque.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_basque.h
new file mode 100644
index 0000000000000000000000000000000000000000..79ddc983af478d420bee2685c77e74428f09f748
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_basque.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * basque_UTF_8_create_env(void);
+extern void basque_UTF_8_close_env(struct SN_env * z);
+
+extern int basque_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_catalan.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_catalan.h
new file mode 100644
index 0000000000000000000000000000000000000000..58c9995d71c61bd7e6ee43c12dc2e634daa28ebe
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_catalan.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * catalan_UTF_8_create_env(void);
+extern void catalan_UTF_8_close_env(struct SN_env * z);
+
+extern int catalan_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_danish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_danish.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5084dc60f228b1fd35771bde415175178291ca7
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_danish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * danish_UTF_8_create_env(void);
+extern void danish_UTF_8_close_env(struct SN_env * z);
+
+extern int danish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_dutch.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_dutch.h
new file mode 100644
index 0000000000000000000000000000000000000000..16cb995413f1fab6e47bbce909c2ece22b04ff35
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_dutch.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * dutch_UTF_8_create_env(void);
+extern void dutch_UTF_8_close_env(struct SN_env * z);
+
+extern int dutch_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_english.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_english.h
new file mode 100644
index 0000000000000000000000000000000000000000..11fa090e7dbe4936d588bd523f5053dc196ba872
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_english.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * english_UTF_8_create_env(void);
+extern void english_UTF_8_close_env(struct SN_env * z);
+
+extern int english_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_finnish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_finnish.h
new file mode 100644
index 0000000000000000000000000000000000000000..eebaa2de9e939e3c45fbf607bf5b87a5f2b125ea
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_finnish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * finnish_UTF_8_create_env(void);
+extern void finnish_UTF_8_close_env(struct SN_env * z);
+
+extern int finnish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_french.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_french.h
new file mode 100644
index 0000000000000000000000000000000000000000..22158b07c78d395dc2ac28e9787d19bf35ad8208
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_french.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * french_UTF_8_create_env(void);
+extern void french_UTF_8_close_env(struct SN_env * z);
+
+extern int french_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_german.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_german.h
new file mode 100644
index 0000000000000000000000000000000000000000..f276c53b265c64cf1a903d4925af4eb65fdd0c68
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_german.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * german_UTF_8_create_env(void);
+extern void german_UTF_8_close_env(struct SN_env * z);
+
+extern int german_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_greek.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_greek.h
new file mode 100644
index 0000000000000000000000000000000000000000..77667a31f009a42eec095ed268b5a906f2edccbb
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_greek.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * greek_UTF_8_create_env(void);
+extern void greek_UTF_8_close_env(struct SN_env * z);
+
+extern int greek_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_hindi.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_hindi.h
new file mode 100644
index 0000000000000000000000000000000000000000..bbc2e9b72313a45eacbef2ab42d8e5011372c349
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_hindi.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * hindi_UTF_8_create_env(void);
+extern void hindi_UTF_8_close_env(struct SN_env * z);
+
+extern int hindi_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_hungarian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_hungarian.h
new file mode 100644
index 0000000000000000000000000000000000000000..cc29d77b9975f08fc0d14ea6ae635eacdde193eb
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_hungarian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * hungarian_UTF_8_create_env(void);
+extern void hungarian_UTF_8_close_env(struct SN_env * z);
+
+extern int hungarian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_indonesian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_indonesian.h
new file mode 100644
index 0000000000000000000000000000000000000000..9f51324ca92708a22d141d561fb2a30734d95dce
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_indonesian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * indonesian_UTF_8_create_env(void);
+extern void indonesian_UTF_8_close_env(struct SN_env * z);
+
+extern int indonesian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_irish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_irish.h
new file mode 100644
index 0000000000000000000000000000000000000000..f06da96d4c7a01d80e2511f91cc855f3c8ae7fd4
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_irish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * irish_UTF_8_create_env(void);
+extern void irish_UTF_8_close_env(struct SN_env * z);
+
+extern int irish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_italian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_italian.h
new file mode 100644
index 0000000000000000000000000000000000000000..f00dcaa5dc107ff988e65977bb3ef6be78f20254
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_italian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * italian_UTF_8_create_env(void);
+extern void italian_UTF_8_close_env(struct SN_env * z);
+
+extern int italian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_lithuanian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_lithuanian.h
new file mode 100644
index 0000000000000000000000000000000000000000..e62ff1c9d581552bcd13e0dddcb09a91599ecd06
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_lithuanian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * lithuanian_UTF_8_create_env(void);
+extern void lithuanian_UTF_8_close_env(struct SN_env * z);
+
+extern int lithuanian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_nepali.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_nepali.h
new file mode 100644
index 0000000000000000000000000000000000000000..f8f50af8a0c2167e1c83e7b2149ce5d71b0f64f8
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_nepali.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * nepali_UTF_8_create_env(void);
+extern void nepali_UTF_8_close_env(struct SN_env * z);
+
+extern int nepali_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_norwegian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_norwegian.h
new file mode 100644
index 0000000000000000000000000000000000000000..72aab40230d07330668635700833e89ee8d8acfa
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_norwegian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * norwegian_UTF_8_create_env(void);
+extern void norwegian_UTF_8_close_env(struct SN_env * z);
+
+extern int norwegian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_porter.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_porter.h
new file mode 100644
index 0000000000000000000000000000000000000000..00685b2c96ad1608ed03fc47e7ad9b24facab3f2
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_porter.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * porter_UTF_8_create_env(void);
+extern void porter_UTF_8_close_env(struct SN_env * z);
+
+extern int porter_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_portuguese.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_portuguese.h
new file mode 100644
index 0000000000000000000000000000000000000000..7be43352c14e3044ec0200b4998cbb0e2c8a17a4
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_portuguese.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * portuguese_UTF_8_create_env(void);
+extern void portuguese_UTF_8_close_env(struct SN_env * z);
+
+extern int portuguese_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_romanian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_romanian.h
new file mode 100644
index 0000000000000000000000000000000000000000..c93cd335b90bc31e259a82a2ec6a7d2c90a83c8d
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_romanian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * romanian_UTF_8_create_env(void);
+extern void romanian_UTF_8_close_env(struct SN_env * z);
+
+extern int romanian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_russian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_russian.h
new file mode 100644
index 0000000000000000000000000000000000000000..ca1d88216ca4286997484c04e344054b3fb63114
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_russian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * russian_UTF_8_create_env(void);
+extern void russian_UTF_8_close_env(struct SN_env * z);
+
+extern int russian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_serbian.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_serbian.h
new file mode 100644
index 0000000000000000000000000000000000000000..1df04f64674e3432f9a79f2eab207d66bcea2189
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_serbian.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * serbian_UTF_8_create_env(void);
+extern void serbian_UTF_8_close_env(struct SN_env * z);
+
+extern int serbian_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_spanish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_spanish.h
new file mode 100644
index 0000000000000000000000000000000000000000..dfd8dc3649d7fa005673ff7c2e52483d551b321d
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_spanish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * spanish_UTF_8_create_env(void);
+extern void spanish_UTF_8_close_env(struct SN_env * z);
+
+extern int spanish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_swedish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_swedish.h
new file mode 100644
index 0000000000000000000000000000000000000000..ca08a64750ecff98c38925f781892d8c39ec7ea6
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_swedish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * swedish_UTF_8_create_env(void);
+extern void swedish_UTF_8_close_env(struct SN_env * z);
+
+extern int swedish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_tamil.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_tamil.h
new file mode 100644
index 0000000000000000000000000000000000000000..5f5ae352baa1c23203579c226ac63d1124b4180b
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_tamil.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * tamil_UTF_8_create_env(void);
+extern void tamil_UTF_8_close_env(struct SN_env * z);
+
+extern int tamil_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_turkish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_turkish.h
new file mode 100644
index 0000000000000000000000000000000000000000..68405929c3bae7abb9ecf85287d32fff87649992
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_turkish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * turkish_UTF_8_create_env(void);
+extern void turkish_UTF_8_close_env(struct SN_env * z);
+
+extern int turkish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/snowball/libstemmer/stem_UTF_8_yiddish.h b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_yiddish.h
new file mode 100644
index 0000000000000000000000000000000000000000..55b66256a27aca8a544a20e617b019404c36ddb4
--- /dev/null
+++ b/pgsql/include/server/snowball/libstemmer/stem_UTF_8_yiddish.h
@@ -0,0 +1,15 @@
+/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern struct SN_env * yiddish_UTF_8_create_env(void);
+extern void yiddish_UTF_8_close_env(struct SN_env * z);
+
+extern int yiddish_UTF_8_stem(struct SN_env * z);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/pgsql/include/server/statistics/extended_stats_internal.h b/pgsql/include/server/statistics/extended_stats_internal.h
new file mode 100644
index 0000000000000000000000000000000000000000..7b55eb8ffac33413b2b1ccb65381315634143244
--- /dev/null
+++ b/pgsql/include/server/statistics/extended_stats_internal.h
@@ -0,0 +1,130 @@
+/*-------------------------------------------------------------------------
+ *
+ * extended_stats_internal.h
+ * POSTGRES extended statistics internal declarations
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/statistics/extended_stats_internal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef EXTENDED_STATS_INTERNAL_H
+#define EXTENDED_STATS_INTERNAL_H
+
+#include "statistics/statistics.h"
+#include "utils/sortsupport.h"
+
+typedef struct
+{
+ Oid eqopr; /* '=' operator for datatype, if any */
+ Oid eqfunc; /* and associated function */
+ Oid ltopr; /* '<' operator for datatype, if any */
+} StdAnalyzeData;
+
+typedef struct
+{
+ Datum value; /* a data value */
+ int tupno; /* position index for tuple it came from */
+} ScalarItem;
+
+/* (de)serialization info */
+typedef struct DimensionInfo
+{
+ int nvalues; /* number of deduplicated values */
+ int nbytes; /* number of bytes (serialized) */
+ int nbytes_aligned; /* size of deserialized data with alignment */
+ int typlen; /* pg_type.typlen */
+ bool typbyval; /* pg_type.typbyval */
+} DimensionInfo;
+
+/* multi-sort */
+typedef struct MultiSortSupportData
+{
+ int ndims; /* number of dimensions */
+ /* sort support data for each dimension: */
+ SortSupportData ssup[FLEXIBLE_ARRAY_MEMBER];
+} MultiSortSupportData;
+
+typedef MultiSortSupportData *MultiSortSupport;
+
+typedef struct SortItem
+{
+ Datum *values;
+ bool *isnull;
+ int count;
+} SortItem;
+
+/* a unified representation of the data the statistics is built on */
+typedef struct StatsBuildData
+{
+ int numrows;
+ int nattnums;
+ AttrNumber *attnums;
+ VacAttrStats **stats;
+ Datum **values;
+ bool **nulls;
+} StatsBuildData;
+
+
+extern MVNDistinct *statext_ndistinct_build(double totalrows, StatsBuildData *data);
+extern bytea *statext_ndistinct_serialize(MVNDistinct *ndistinct);
+extern MVNDistinct *statext_ndistinct_deserialize(bytea *data);
+
+extern MVDependencies *statext_dependencies_build(StatsBuildData *data);
+extern bytea *statext_dependencies_serialize(MVDependencies *dependencies);
+extern MVDependencies *statext_dependencies_deserialize(bytea *data);
+
+extern MCVList *statext_mcv_build(StatsBuildData *data,
+ double totalrows, int stattarget);
+extern bytea *statext_mcv_serialize(MCVList *mcvlist, VacAttrStats **stats);
+extern MCVList *statext_mcv_deserialize(bytea *data);
+
+extern MultiSortSupport multi_sort_init(int ndims);
+extern void multi_sort_add_dimension(MultiSortSupport mss, int sortdim,
+ Oid oper, Oid collation);
+extern int multi_sort_compare(const void *a, const void *b, void *arg);
+extern int multi_sort_compare_dim(int dim, const SortItem *a,
+ const SortItem *b, MultiSortSupport mss);
+extern int multi_sort_compare_dims(int start, int end, const SortItem *a,
+ const SortItem *b, MultiSortSupport mss);
+extern int compare_scalars_simple(const void *a, const void *b, void *arg);
+extern int compare_datums_simple(Datum a, Datum b, SortSupport ssup);
+
+extern AttrNumber *build_attnums_array(Bitmapset *attrs, int nexprs, int *numattrs);
+
+extern SortItem *build_sorted_items(StatsBuildData *data, int *nitems,
+ MultiSortSupport mss,
+ int numattrs, AttrNumber *attnums);
+
+extern bool examine_opclause_args(List *args, Node **exprp,
+ Const **cstp, bool *expronleftp);
+
+extern Selectivity mcv_combine_selectivities(Selectivity simple_sel,
+ Selectivity mcv_sel,
+ Selectivity mcv_basesel,
+ Selectivity mcv_totalsel);
+
+extern Selectivity mcv_clauselist_selectivity(PlannerInfo *root,
+ StatisticExtInfo *stat,
+ List *clauses,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo,
+ RelOptInfo *rel,
+ Selectivity *basesel,
+ Selectivity *totalsel);
+
+extern Selectivity mcv_clause_selectivity_or(PlannerInfo *root,
+ StatisticExtInfo *stat,
+ MCVList *mcv,
+ Node *clause,
+ bool **or_matches,
+ Selectivity *basesel,
+ Selectivity *overlap_mcvsel,
+ Selectivity *overlap_basesel,
+ Selectivity *totalsel);
+
+#endif /* EXTENDED_STATS_INTERNAL_H */
diff --git a/pgsql/include/server/statistics/statistics.h b/pgsql/include/server/statistics/statistics.h
new file mode 100644
index 0000000000000000000000000000000000000000..17e3e7f881dfaee607fe126c7df3d7da44847871
--- /dev/null
+++ b/pgsql/include/server/statistics/statistics.h
@@ -0,0 +1,130 @@
+/*-------------------------------------------------------------------------
+ *
+ * statistics.h
+ * Extended statistics and selectivity estimation functions.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/statistics/statistics.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef STATISTICS_H
+#define STATISTICS_H
+
+#include "commands/vacuum.h"
+#include "nodes/pathnodes.h"
+
+#define STATS_MAX_DIMENSIONS 8 /* max number of attributes */
+
+/* Multivariate distinct coefficients */
+#define STATS_NDISTINCT_MAGIC 0xA352BFA4 /* struct identifier */
+#define STATS_NDISTINCT_TYPE_BASIC 1 /* struct version */
+
+/* MVNDistinctItem represents a single combination of columns */
+typedef struct MVNDistinctItem
+{
+ double ndistinct; /* ndistinct value for this combination */
+ int nattributes; /* number of attributes */
+ AttrNumber *attributes; /* attribute numbers */
+} MVNDistinctItem;
+
+/* A MVNDistinct object, comprising all possible combinations of columns */
+typedef struct MVNDistinct
+{
+ uint32 magic; /* magic constant marker */
+ uint32 type; /* type of ndistinct (BASIC) */
+ uint32 nitems; /* number of items in the statistic */
+ MVNDistinctItem items[FLEXIBLE_ARRAY_MEMBER];
+} MVNDistinct;
+
+/* Multivariate functional dependencies */
+#define STATS_DEPS_MAGIC 0xB4549A2C /* marks serialized bytea */
+#define STATS_DEPS_TYPE_BASIC 1 /* basic dependencies type */
+
+/*
+ * Functional dependencies, tracking column-level relationships (values
+ * in one column determine values in another one).
+ */
+typedef struct MVDependency
+{
+ double degree; /* degree of validity (0-1) */
+ AttrNumber nattributes; /* number of attributes */
+ AttrNumber attributes[FLEXIBLE_ARRAY_MEMBER]; /* attribute numbers */
+} MVDependency;
+
+typedef struct MVDependencies
+{
+ uint32 magic; /* magic constant marker */
+ uint32 type; /* type of MV Dependencies (BASIC) */
+ uint32 ndeps; /* number of dependencies */
+ MVDependency *deps[FLEXIBLE_ARRAY_MEMBER]; /* dependencies */
+} MVDependencies;
+
+/* used to flag stats serialized to bytea */
+#define STATS_MCV_MAGIC 0xE1A651C2 /* marks serialized bytea */
+#define STATS_MCV_TYPE_BASIC 1 /* basic MCV list type */
+
+/* max items in MCV list (should be equal to max default_statistics_target) */
+#define STATS_MCVLIST_MAX_ITEMS 10000
+
+/*
+ * Multivariate MCV (most-common value) lists
+ *
+ * A straightforward extension of MCV items - i.e. a list (array) of
+ * combinations of attribute values, together with a frequency and null flags.
+ */
+typedef struct MCVItem
+{
+ double frequency; /* frequency of this combination */
+ double base_frequency; /* frequency if independent */
+ bool *isnull; /* NULL flags */
+ Datum *values; /* item values */
+} MCVItem;
+
+/* multivariate MCV list - essentially an array of MCV items */
+typedef struct MCVList
+{
+ uint32 magic; /* magic constant marker */
+ uint32 type; /* type of MCV list (BASIC) */
+ uint32 nitems; /* number of MCV items in the array */
+ AttrNumber ndimensions; /* number of dimensions */
+ Oid types[STATS_MAX_DIMENSIONS]; /* OIDs of data types */
+ MCVItem items[FLEXIBLE_ARRAY_MEMBER]; /* array of MCV items */
+} MCVList;
+
+extern MVNDistinct *statext_ndistinct_load(Oid mvoid, bool inh);
+extern MVDependencies *statext_dependencies_load(Oid mvoid, bool inh);
+extern MCVList *statext_mcv_load(Oid mvoid, bool inh);
+
+extern void BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
+ int numrows, HeapTuple *rows,
+ int natts, VacAttrStats **vacattrstats);
+extern int ComputeExtStatisticsRows(Relation onerel,
+ int natts, VacAttrStats **vacattrstats);
+extern bool statext_is_kind_built(HeapTuple htup, char type);
+extern Selectivity dependencies_clauselist_selectivity(PlannerInfo *root,
+ List *clauses,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo,
+ RelOptInfo *rel,
+ Bitmapset **estimatedclauses);
+extern Selectivity statext_clauselist_selectivity(PlannerInfo *root,
+ List *clauses,
+ int varRelid,
+ JoinType jointype,
+ SpecialJoinInfo *sjinfo,
+ RelOptInfo *rel,
+ Bitmapset **estimatedclauses,
+ bool is_or);
+extern bool has_stats_of_kind(List *stats, char requiredkind);
+extern StatisticExtInfo *choose_best_statistics(List *stats, char requiredkind,
+ bool inh,
+ Bitmapset **clause_attnums,
+ List **clause_exprs,
+ int nclauses);
+extern HeapTuple statext_expressions_load(Oid stxoid, bool inh, int idx);
+
+#endif /* STATISTICS_H */
diff --git a/pgsql/include/server/storage/backendid.h b/pgsql/include/server/storage/backendid.h
new file mode 100644
index 0000000000000000000000000000000000000000..1e90b602f0cb5be264d28fd41a4f871691c1c7d0
--- /dev/null
+++ b/pgsql/include/server/storage/backendid.h
@@ -0,0 +1,37 @@
+/*-------------------------------------------------------------------------
+ *
+ * backendid.h
+ * POSTGRES backend id communication definitions
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/backendid.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BACKENDID_H
+#define BACKENDID_H
+
+/* ----------------
+ * -cim 8/17/90
+ * ----------------
+ */
+typedef int BackendId; /* unique currently active backend identifier */
+
+#define InvalidBackendId (-1)
+
+extern PGDLLIMPORT BackendId MyBackendId; /* backend id of this backend */
+
+/* backend id of our parallel session leader, or InvalidBackendId if none */
+extern PGDLLIMPORT BackendId ParallelLeaderBackendId;
+
+/*
+ * The BackendId to use for our session's temp relations is normally our own,
+ * but parallel workers should use their leader's ID.
+ */
+#define BackendIdForTempRelations() \
+ (ParallelLeaderBackendId == InvalidBackendId ? MyBackendId : ParallelLeaderBackendId)
+
+#endif /* BACKENDID_H */
diff --git a/pgsql/include/server/storage/barrier.h b/pgsql/include/server/storage/barrier.h
new file mode 100644
index 0000000000000000000000000000000000000000..e965c7ba75fba7c62eaa5c7b447d949a82b4d27a
--- /dev/null
+++ b/pgsql/include/server/storage/barrier.h
@@ -0,0 +1,46 @@
+/*-------------------------------------------------------------------------
+ *
+ * barrier.h
+ * Barriers for synchronizing cooperating processes.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/barrier.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BARRIER_H
+#define BARRIER_H
+
+/*
+ * For the header previously known as "barrier.h", please include
+ * "port/atomics.h", which deals with atomics, compiler barriers and memory
+ * barriers.
+ */
+
+#include "storage/condition_variable.h"
+#include "storage/spin.h"
+
+typedef struct Barrier
+{
+ slock_t mutex;
+ int phase; /* phase counter */
+ int participants; /* the number of participants attached */
+ int arrived; /* the number of participants that have
+ * arrived */
+ int elected; /* highest phase elected */
+ bool static_party; /* used only for assertions */
+ ConditionVariable condition_variable;
+} Barrier;
+
+extern void BarrierInit(Barrier *barrier, int participants);
+extern bool BarrierArriveAndWait(Barrier *barrier, uint32 wait_event_info);
+extern bool BarrierArriveAndDetach(Barrier *barrier);
+extern bool BarrierArriveAndDetachExceptLast(Barrier *barrier);
+extern int BarrierAttach(Barrier *barrier);
+extern bool BarrierDetach(Barrier *barrier);
+extern int BarrierPhase(Barrier *barrier);
+extern int BarrierParticipants(Barrier *barrier);
+
+#endif /* BARRIER_H */
diff --git a/pgsql/include/server/storage/block.h b/pgsql/include/server/storage/block.h
new file mode 100644
index 0000000000000000000000000000000000000000..31a036df0dbed6e2a9e6519cf9b7a116c25d8594
--- /dev/null
+++ b/pgsql/include/server/storage/block.h
@@ -0,0 +1,108 @@
+/*-------------------------------------------------------------------------
+ *
+ * block.h
+ * POSTGRES disk block definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/block.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BLOCK_H
+#define BLOCK_H
+
+/*
+ * BlockNumber:
+ *
+ * each data file (heap or index) is divided into postgres disk blocks
+ * (which may be thought of as the unit of i/o -- a postgres buffer
+ * contains exactly one disk block). the blocks are numbered
+ * sequentially, 0 to 0xFFFFFFFE.
+ *
+ * InvalidBlockNumber is the same thing as P_NEW in bufmgr.h.
+ *
+ * the access methods, the buffer manager and the storage manager are
+ * more or less the only pieces of code that should be accessing disk
+ * blocks directly.
+ */
+typedef uint32 BlockNumber;
+
+#define InvalidBlockNumber ((BlockNumber) 0xFFFFFFFF)
+
+#define MaxBlockNumber ((BlockNumber) 0xFFFFFFFE)
+
+/*
+ * BlockId:
+ *
+ * this is a storage type for BlockNumber. in other words, this type
+ * is used for on-disk structures (e.g., in HeapTupleData) whereas
+ * BlockNumber is the type on which calculations are performed (e.g.,
+ * in access method code).
+ *
+ * there doesn't appear to be any reason to have separate types except
+ * for the fact that BlockIds can be SHORTALIGN'd (and therefore any
+ * structures that contains them, such as ItemPointerData, can also be
+ * SHORTALIGN'd). this is an important consideration for reducing the
+ * space requirements of the line pointer (ItemIdData) array on each
+ * page and the header of each heap or index tuple, so it doesn't seem
+ * wise to change this without good reason.
+ */
+typedef struct BlockIdData
+{
+ uint16 bi_hi;
+ uint16 bi_lo;
+} BlockIdData;
+
+typedef BlockIdData *BlockId; /* block identifier */
+
+/* ----------------
+ * support functions
+ * ----------------
+ */
+
+/*
+ * BlockNumberIsValid
+ * True iff blockNumber is valid.
+ */
+static inline bool
+BlockNumberIsValid(BlockNumber blockNumber)
+{
+ return blockNumber != InvalidBlockNumber;
+}
+
+/*
+ * BlockIdSet
+ * Sets a block identifier to the specified value.
+ */
+static inline void
+BlockIdSet(BlockIdData *blockId, BlockNumber blockNumber)
+{
+ blockId->bi_hi = blockNumber >> 16;
+ blockId->bi_lo = blockNumber & 0xffff;
+}
+
+/*
+ * BlockIdEquals
+ * Check for block number equality.
+ */
+static inline bool
+BlockIdEquals(const BlockIdData *blockId1, const BlockIdData *blockId2)
+{
+ return (blockId1->bi_hi == blockId2->bi_hi &&
+ blockId1->bi_lo == blockId2->bi_lo);
+}
+
+/*
+ * BlockIdGetBlockNumber
+ * Retrieve the block number from a block identifier.
+ */
+static inline BlockNumber
+BlockIdGetBlockNumber(const BlockIdData *blockId)
+{
+ return (((BlockNumber) blockId->bi_hi) << 16) | ((BlockNumber) blockId->bi_lo);
+}
+
+#endif /* BLOCK_H */
diff --git a/pgsql/include/server/storage/buf.h b/pgsql/include/server/storage/buf.h
new file mode 100644
index 0000000000000000000000000000000000000000..6520d9ae1e85032cbe769393d8d83e64a2a048ea
--- /dev/null
+++ b/pgsql/include/server/storage/buf.h
@@ -0,0 +1,46 @@
+/*-------------------------------------------------------------------------
+ *
+ * buf.h
+ * Basic buffer manager data types.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/buf.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BUF_H
+#define BUF_H
+
+/*
+ * Buffer identifiers.
+ *
+ * Zero is invalid, positive is the index of a shared buffer (1..NBuffers),
+ * negative is the index of a local buffer (-1 .. -NLocBuffer).
+ */
+typedef int Buffer;
+
+#define InvalidBuffer 0
+
+/*
+ * BufferIsInvalid
+ * True iff the buffer is invalid.
+ */
+#define BufferIsInvalid(buffer) ((buffer) == InvalidBuffer)
+
+/*
+ * BufferIsLocal
+ * True iff the buffer is local (not visible to other backends).
+ */
+#define BufferIsLocal(buffer) ((buffer) < 0)
+
+/*
+ * Buffer access strategy objects.
+ *
+ * BufferAccessStrategyData is private to freelist.c
+ */
+typedef struct BufferAccessStrategyData *BufferAccessStrategy;
+
+#endif /* BUF_H */
diff --git a/pgsql/include/server/storage/buf_internals.h b/pgsql/include/server/storage/buf_internals.h
new file mode 100644
index 0000000000000000000000000000000000000000..98cd2499098c69ecd649ae8b2c340048d191cb8e
--- /dev/null
+++ b/pgsql/include/server/storage/buf_internals.h
@@ -0,0 +1,440 @@
+/*-------------------------------------------------------------------------
+ *
+ * buf_internals.h
+ * Internal definitions for buffer manager and the buffer replacement
+ * strategy.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/buf_internals.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BUFMGR_INTERNALS_H
+#define BUFMGR_INTERNALS_H
+
+#include "pgstat.h"
+#include "port/atomics.h"
+#include "storage/buf.h"
+#include "storage/bufmgr.h"
+#include "storage/condition_variable.h"
+#include "storage/latch.h"
+#include "storage/lwlock.h"
+#include "storage/shmem.h"
+#include "storage/smgr.h"
+#include "storage/spin.h"
+#include "utils/relcache.h"
+
+/*
+ * Buffer state is a single 32-bit variable where following data is combined.
+ *
+ * - 18 bits refcount
+ * - 4 bits usage count
+ * - 10 bits of flags
+ *
+ * Combining these values allows to perform some operations without locking
+ * the buffer header, by modifying them together with a CAS loop.
+ *
+ * The definition of buffer state components is below.
+ */
+#define BUF_REFCOUNT_ONE 1
+#define BUF_REFCOUNT_MASK ((1U << 18) - 1)
+#define BUF_USAGECOUNT_MASK 0x003C0000U
+#define BUF_USAGECOUNT_ONE (1U << 18)
+#define BUF_USAGECOUNT_SHIFT 18
+#define BUF_FLAG_MASK 0xFFC00000U
+
+/* Get refcount and usagecount from buffer state */
+#define BUF_STATE_GET_REFCOUNT(state) ((state) & BUF_REFCOUNT_MASK)
+#define BUF_STATE_GET_USAGECOUNT(state) (((state) & BUF_USAGECOUNT_MASK) >> BUF_USAGECOUNT_SHIFT)
+
+/*
+ * Flags for buffer descriptors
+ *
+ * Note: BM_TAG_VALID essentially means that there is a buffer hashtable
+ * entry associated with the buffer's tag.
+ */
+#define BM_LOCKED (1U << 22) /* buffer header is locked */
+#define BM_DIRTY (1U << 23) /* data needs writing */
+#define BM_VALID (1U << 24) /* data is valid */
+#define BM_TAG_VALID (1U << 25) /* tag is assigned */
+#define BM_IO_IN_PROGRESS (1U << 26) /* read or write in progress */
+#define BM_IO_ERROR (1U << 27) /* previous I/O failed */
+#define BM_JUST_DIRTIED (1U << 28) /* dirtied since write started */
+#define BM_PIN_COUNT_WAITER (1U << 29) /* have waiter for sole pin */
+#define BM_CHECKPOINT_NEEDED (1U << 30) /* must write for checkpoint */
+#define BM_PERMANENT (1U << 31) /* permanent buffer (not unlogged,
+ * or init fork) */
+/*
+ * The maximum allowed value of usage_count represents a tradeoff between
+ * accuracy and speed of the clock-sweep buffer management algorithm. A
+ * large value (comparable to NBuffers) would approximate LRU semantics.
+ * But it can take as many as BM_MAX_USAGE_COUNT+1 complete cycles of
+ * clock sweeps to find a free buffer, so in practice we don't want the
+ * value to be very large.
+ */
+#define BM_MAX_USAGE_COUNT 5
+
+/*
+ * Buffer tag identifies which disk block the buffer contains.
+ *
+ * Note: the BufferTag data must be sufficient to determine where to write the
+ * block, without reference to pg_class or pg_tablespace entries. It's
+ * possible that the backend flushing the buffer doesn't even believe the
+ * relation is visible yet (its xact may have started before the xact that
+ * created the rel). The storage manager must be able to cope anyway.
+ *
+ * Note: if there's any pad bytes in the struct, InitBufferTag will have
+ * to be fixed to zero them, since this struct is used as a hash key.
+ */
+typedef struct buftag
+{
+ Oid spcOid; /* tablespace oid */
+ Oid dbOid; /* database oid */
+ RelFileNumber relNumber; /* relation file number */
+ ForkNumber forkNum; /* fork number */
+ BlockNumber blockNum; /* blknum relative to begin of reln */
+} BufferTag;
+
+static inline RelFileNumber
+BufTagGetRelNumber(const BufferTag *tag)
+{
+ return tag->relNumber;
+}
+
+static inline ForkNumber
+BufTagGetForkNum(const BufferTag *tag)
+{
+ return tag->forkNum;
+}
+
+static inline void
+BufTagSetRelForkDetails(BufferTag *tag, RelFileNumber relnumber,
+ ForkNumber forknum)
+{
+ tag->relNumber = relnumber;
+ tag->forkNum = forknum;
+}
+
+static inline RelFileLocator
+BufTagGetRelFileLocator(const BufferTag *tag)
+{
+ RelFileLocator rlocator;
+
+ rlocator.spcOid = tag->spcOid;
+ rlocator.dbOid = tag->dbOid;
+ rlocator.relNumber = BufTagGetRelNumber(tag);
+
+ return rlocator;
+}
+
+static inline void
+ClearBufferTag(BufferTag *tag)
+{
+ tag->spcOid = InvalidOid;
+ tag->dbOid = InvalidOid;
+ BufTagSetRelForkDetails(tag, InvalidRelFileNumber, InvalidForkNumber);
+ tag->blockNum = InvalidBlockNumber;
+}
+
+static inline void
+InitBufferTag(BufferTag *tag, const RelFileLocator *rlocator,
+ ForkNumber forkNum, BlockNumber blockNum)
+{
+ tag->spcOid = rlocator->spcOid;
+ tag->dbOid = rlocator->dbOid;
+ BufTagSetRelForkDetails(tag, rlocator->relNumber, forkNum);
+ tag->blockNum = blockNum;
+}
+
+static inline bool
+BufferTagsEqual(const BufferTag *tag1, const BufferTag *tag2)
+{
+ return (tag1->spcOid == tag2->spcOid) &&
+ (tag1->dbOid == tag2->dbOid) &&
+ (tag1->relNumber == tag2->relNumber) &&
+ (tag1->blockNum == tag2->blockNum) &&
+ (tag1->forkNum == tag2->forkNum);
+}
+
+static inline bool
+BufTagMatchesRelFileLocator(const BufferTag *tag,
+ const RelFileLocator *rlocator)
+{
+ return (tag->spcOid == rlocator->spcOid) &&
+ (tag->dbOid == rlocator->dbOid) &&
+ (BufTagGetRelNumber(tag) == rlocator->relNumber);
+}
+
+
+/*
+ * The shared buffer mapping table is partitioned to reduce contention.
+ * To determine which partition lock a given tag requires, compute the tag's
+ * hash code with BufTableHashCode(), then apply BufMappingPartitionLock().
+ * NB: NUM_BUFFER_PARTITIONS must be a power of 2!
+ */
+static inline uint32
+BufTableHashPartition(uint32 hashcode)
+{
+ return hashcode % NUM_BUFFER_PARTITIONS;
+}
+
+static inline LWLock *
+BufMappingPartitionLock(uint32 hashcode)
+{
+ return &MainLWLockArray[BUFFER_MAPPING_LWLOCK_OFFSET +
+ BufTableHashPartition(hashcode)].lock;
+}
+
+static inline LWLock *
+BufMappingPartitionLockByIndex(uint32 index)
+{
+ return &MainLWLockArray[BUFFER_MAPPING_LWLOCK_OFFSET + index].lock;
+}
+
+/*
+ * BufferDesc -- shared descriptor/state data for a single shared buffer.
+ *
+ * Note: Buffer header lock (BM_LOCKED flag) must be held to examine or change
+ * tag, state or wait_backend_pgprocno fields. In general, buffer header lock
+ * is a spinlock which is combined with flags, refcount and usagecount into
+ * single atomic variable. This layout allow us to do some operations in a
+ * single atomic operation, without actually acquiring and releasing spinlock;
+ * for instance, increase or decrease refcount. buf_id field never changes
+ * after initialization, so does not need locking. freeNext is protected by
+ * the buffer_strategy_lock not buffer header lock. The LWLock can take care
+ * of itself. The buffer header lock is *not* used to control access to the
+ * data in the buffer!
+ *
+ * It's assumed that nobody changes the state field while buffer header lock
+ * is held. Thus buffer header lock holder can do complex updates of the
+ * state variable in single write, simultaneously with lock release (cleaning
+ * BM_LOCKED flag). On the other hand, updating of state without holding
+ * buffer header lock is restricted to CAS, which ensures that BM_LOCKED flag
+ * is not set. Atomic increment/decrement, OR/AND etc. are not allowed.
+ *
+ * An exception is that if we have the buffer pinned, its tag can't change
+ * underneath us, so we can examine the tag without locking the buffer header.
+ * Also, in places we do one-time reads of the flags without bothering to
+ * lock the buffer header; this is generally for situations where we don't
+ * expect the flag bit being tested to be changing.
+ *
+ * We can't physically remove items from a disk page if another backend has
+ * the buffer pinned. Hence, a backend may need to wait for all other pins
+ * to go away. This is signaled by storing its own pgprocno into
+ * wait_backend_pgprocno and setting flag bit BM_PIN_COUNT_WAITER. At present,
+ * there can be only one such waiter per buffer.
+ *
+ * We use this same struct for local buffer headers, but the locks are not
+ * used and not all of the flag bits are useful either. To avoid unnecessary
+ * overhead, manipulations of the state field should be done without actual
+ * atomic operations (i.e. only pg_atomic_read_u32() and
+ * pg_atomic_unlocked_write_u32()).
+ *
+ * Be careful to avoid increasing the size of the struct when adding or
+ * reordering members. Keeping it below 64 bytes (the most common CPU
+ * cache line size) is fairly important for performance.
+ *
+ * Per-buffer I/O condition variables are currently kept outside this struct in
+ * a separate array. They could be moved in here and still fit within that
+ * limit on common systems, but for now that is not done.
+ */
+typedef struct BufferDesc
+{
+ BufferTag tag; /* ID of page contained in buffer */
+ int buf_id; /* buffer's index number (from 0) */
+
+ /* state of the tag, containing flags, refcount and usagecount */
+ pg_atomic_uint32 state;
+
+ int wait_backend_pgprocno; /* backend of pin-count waiter */
+ int freeNext; /* link in freelist chain */
+ LWLock content_lock; /* to lock access to buffer contents */
+} BufferDesc;
+
+/*
+ * Concurrent access to buffer headers has proven to be more efficient if
+ * they're cache line aligned. So we force the start of the BufferDescriptors
+ * array to be on a cache line boundary and force the elements to be cache
+ * line sized.
+ *
+ * XXX: As this is primarily matters in highly concurrent workloads which
+ * probably all are 64bit these days, and the space wastage would be a bit
+ * more noticeable on 32bit systems, we don't force the stride to be cache
+ * line sized on those. If somebody does actual performance testing, we can
+ * reevaluate.
+ *
+ * Note that local buffer descriptors aren't forced to be aligned - as there's
+ * no concurrent access to those it's unlikely to be beneficial.
+ *
+ * We use a 64-byte cache line size here, because that's the most common
+ * size. Making it bigger would be a waste of memory. Even if running on a
+ * platform with either 32 or 128 byte line sizes, it's good to align to
+ * boundaries and avoid false sharing.
+ */
+#define BUFFERDESC_PAD_TO_SIZE (SIZEOF_VOID_P == 8 ? 64 : 1)
+
+typedef union BufferDescPadded
+{
+ BufferDesc bufferdesc;
+ char pad[BUFFERDESC_PAD_TO_SIZE];
+} BufferDescPadded;
+
+/*
+ * The PendingWriteback & WritebackContext structure are used to keep
+ * information about pending flush requests to be issued to the OS.
+ */
+typedef struct PendingWriteback
+{
+ /* could store different types of pending flushes here */
+ BufferTag tag;
+} PendingWriteback;
+
+/* struct forward declared in bufmgr.h */
+typedef struct WritebackContext
+{
+ /* pointer to the max number of writeback requests to coalesce */
+ int *max_pending;
+
+ /* current number of pending writeback requests */
+ int nr_pending;
+
+ /* pending requests */
+ PendingWriteback pending_writebacks[WRITEBACK_MAX_PENDING_FLUSHES];
+} WritebackContext;
+
+/* in buf_init.c */
+extern PGDLLIMPORT BufferDescPadded *BufferDescriptors;
+extern PGDLLIMPORT ConditionVariableMinimallyPadded *BufferIOCVArray;
+extern PGDLLIMPORT WritebackContext BackendWritebackContext;
+
+/* in localbuf.c */
+extern PGDLLIMPORT BufferDesc *LocalBufferDescriptors;
+
+
+static inline BufferDesc *
+GetBufferDescriptor(uint32 id)
+{
+ return &(BufferDescriptors[id]).bufferdesc;
+}
+
+static inline BufferDesc *
+GetLocalBufferDescriptor(uint32 id)
+{
+ return &LocalBufferDescriptors[id];
+}
+
+static inline Buffer
+BufferDescriptorGetBuffer(const BufferDesc *bdesc)
+{
+ return (Buffer) (bdesc->buf_id + 1);
+}
+
+static inline ConditionVariable *
+BufferDescriptorGetIOCV(const BufferDesc *bdesc)
+{
+ return &(BufferIOCVArray[bdesc->buf_id]).cv;
+}
+
+static inline LWLock *
+BufferDescriptorGetContentLock(const BufferDesc *bdesc)
+{
+ return (LWLock *) (&bdesc->content_lock);
+}
+
+/*
+ * The freeNext field is either the index of the next freelist entry,
+ * or one of these special values:
+ */
+#define FREENEXT_END_OF_LIST (-1)
+#define FREENEXT_NOT_IN_LIST (-2)
+
+/*
+ * Functions for acquiring/releasing a shared buffer header's spinlock. Do
+ * not apply these to local buffers!
+ */
+extern uint32 LockBufHdr(BufferDesc *desc);
+
+static inline void
+UnlockBufHdr(BufferDesc *desc, uint32 buf_state)
+{
+ pg_write_barrier();
+ pg_atomic_write_u32(&desc->state, buf_state & (~BM_LOCKED));
+}
+
+/* in bufmgr.c */
+
+/*
+ * Structure to sort buffers per file on checkpoints.
+ *
+ * This structure is allocated per buffer in shared memory, so it should be
+ * kept as small as possible.
+ */
+typedef struct CkptSortItem
+{
+ Oid tsId;
+ RelFileNumber relNumber;
+ ForkNumber forkNum;
+ BlockNumber blockNum;
+ int buf_id;
+} CkptSortItem;
+
+extern PGDLLIMPORT CkptSortItem *CkptBufferIds;
+
+/*
+ * Internal buffer management routines
+ */
+/* bufmgr.c */
+extern void WritebackContextInit(WritebackContext *context, int *max_pending);
+extern void IssuePendingWritebacks(WritebackContext *wb_context, IOContext io_context);
+extern void ScheduleBufferTagForWriteback(WritebackContext *wb_context,
+ IOContext io_context, BufferTag *tag);
+
+/* freelist.c */
+extern IOContext IOContextForStrategy(BufferAccessStrategy strategy);
+extern BufferDesc *StrategyGetBuffer(BufferAccessStrategy strategy,
+ uint32 *buf_state, bool *from_ring);
+extern void StrategyFreeBuffer(BufferDesc *buf);
+extern bool StrategyRejectBuffer(BufferAccessStrategy strategy,
+ BufferDesc *buf, bool from_ring);
+
+extern int StrategySyncStart(uint32 *complete_passes, uint32 *num_buf_alloc);
+extern void StrategyNotifyBgWriter(int bgwprocno);
+
+extern Size StrategyShmemSize(void);
+extern void StrategyInitialize(bool init);
+extern bool have_free_buffer(void);
+
+/* buf_table.c */
+extern Size BufTableShmemSize(int size);
+extern void InitBufTable(int size);
+extern uint32 BufTableHashCode(BufferTag *tagPtr);
+extern int BufTableLookup(BufferTag *tagPtr, uint32 hashcode);
+extern int BufTableInsert(BufferTag *tagPtr, uint32 hashcode, int buf_id);
+extern void BufTableDelete(BufferTag *tagPtr, uint32 hashcode);
+
+/* localbuf.c */
+extern bool PinLocalBuffer(BufferDesc *buf_hdr, bool adjust_usagecount);
+extern void UnpinLocalBuffer(Buffer buffer);
+extern PrefetchBufferResult PrefetchLocalBuffer(SMgrRelation smgr,
+ ForkNumber forkNum,
+ BlockNumber blockNum);
+extern BufferDesc *LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum,
+ BlockNumber blockNum, bool *foundPtr);
+extern BlockNumber ExtendBufferedRelLocal(BufferManagerRelation bmr,
+ ForkNumber fork,
+ uint32 flags,
+ uint32 extend_by,
+ BlockNumber extend_upto,
+ Buffer *buffers,
+ uint32 *extended_by);
+extern void MarkLocalBufferDirty(Buffer buffer);
+extern void DropRelationLocalBuffers(RelFileLocator rlocator,
+ ForkNumber forkNum,
+ BlockNumber firstDelBlock);
+extern void DropRelationAllLocalBuffers(RelFileLocator rlocator);
+extern void AtEOXact_LocalBuffers(bool isCommit);
+
+#endif /* BUFMGR_INTERNALS_H */
diff --git a/pgsql/include/server/storage/buffile.h b/pgsql/include/server/storage/buffile.h
new file mode 100644
index 0000000000000000000000000000000000000000..658376671933c7295d0814a717d5b6a0440d85ba
--- /dev/null
+++ b/pgsql/include/server/storage/buffile.h
@@ -0,0 +1,59 @@
+/*-------------------------------------------------------------------------
+ *
+ * buffile.h
+ * Management of large buffered temporary files.
+ *
+ * The BufFile routines provide a partial replacement for stdio atop
+ * virtual file descriptors managed by fd.c. Currently they only support
+ * buffered access to a virtual file, without any of stdio's formatting
+ * features. That's enough for immediate needs, but the set of facilities
+ * could be expanded if necessary.
+ *
+ * BufFile also supports working with temporary files that exceed the OS
+ * file size limit and/or the largest offset representable in an int.
+ * It might be better to split that out as a separately accessible module,
+ * but currently we have no need for oversize temp files without buffered
+ * access.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/buffile.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef BUFFILE_H
+#define BUFFILE_H
+
+#include "storage/fileset.h"
+
+/* BufFile is an opaque type whose details are not known outside buffile.c. */
+
+typedef struct BufFile BufFile;
+
+/*
+ * prototypes for functions in buffile.c
+ */
+
+extern BufFile *BufFileCreateTemp(bool interXact);
+extern void BufFileClose(BufFile *file);
+extern pg_nodiscard size_t BufFileRead(BufFile *file, void *ptr, size_t size);
+extern void BufFileReadExact(BufFile *file, void *ptr, size_t size);
+extern size_t BufFileReadMaybeEOF(BufFile *file, void *ptr, size_t size, bool eofOK);
+extern void BufFileWrite(BufFile *file, const void *ptr, size_t size);
+extern int BufFileSeek(BufFile *file, int fileno, off_t offset, int whence);
+extern void BufFileTell(BufFile *file, int *fileno, off_t *offset);
+extern int BufFileSeekBlock(BufFile *file, long blknum);
+extern int64 BufFileSize(BufFile *file);
+extern long BufFileAppend(BufFile *target, BufFile *source);
+
+extern BufFile *BufFileCreateFileSet(FileSet *fileset, const char *name);
+extern void BufFileExportFileSet(BufFile *file);
+extern BufFile *BufFileOpenFileSet(FileSet *fileset, const char *name,
+ int mode, bool missing_ok);
+extern void BufFileDeleteFileSet(FileSet *fileset, const char *name,
+ bool missing_ok);
+extern void BufFileTruncateFileSet(BufFile *file, int fileno, off_t offset);
+
+#endif /* BUFFILE_H */
diff --git a/pgsql/include/server/storage/bufmgr.h b/pgsql/include/server/storage/bufmgr.h
new file mode 100644
index 0000000000000000000000000000000000000000..b379c76e2732e669e9d321b70bd480c68850e8ec
--- /dev/null
+++ b/pgsql/include/server/storage/bufmgr.h
@@ -0,0 +1,393 @@
+/*-------------------------------------------------------------------------
+ *
+ * bufmgr.h
+ * POSTGRES buffer manager definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/bufmgr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BUFMGR_H
+#define BUFMGR_H
+
+#include "storage/block.h"
+#include "storage/buf.h"
+#include "storage/bufpage.h"
+#include "storage/relfilelocator.h"
+#include "utils/relcache.h"
+#include "utils/snapmgr.h"
+
+typedef void *Block;
+
+/*
+ * Possible arguments for GetAccessStrategy().
+ *
+ * If adding a new BufferAccessStrategyType, also add a new IOContext so
+ * IO statistics using this strategy are tracked.
+ */
+typedef enum BufferAccessStrategyType
+{
+ BAS_NORMAL, /* Normal random access */
+ BAS_BULKREAD, /* Large read-only scan (hint bit updates are
+ * ok) */
+ BAS_BULKWRITE, /* Large multi-block write (e.g. COPY IN) */
+ BAS_VACUUM /* VACUUM */
+} BufferAccessStrategyType;
+
+/* Possible modes for ReadBufferExtended() */
+typedef enum
+{
+ RBM_NORMAL, /* Normal read */
+ RBM_ZERO_AND_LOCK, /* Don't read from disk, caller will
+ * initialize. Also locks the page. */
+ RBM_ZERO_AND_CLEANUP_LOCK, /* Like RBM_ZERO_AND_LOCK, but locks the page
+ * in "cleanup" mode */
+ RBM_ZERO_ON_ERROR, /* Read, but return an all-zeros page on error */
+ RBM_NORMAL_NO_LOG /* Don't log page as invalid during WAL
+ * replay; otherwise same as RBM_NORMAL */
+} ReadBufferMode;
+
+/*
+ * Type returned by PrefetchBuffer().
+ */
+typedef struct PrefetchBufferResult
+{
+ Buffer recent_buffer; /* If valid, a hit (recheck needed!) */
+ bool initiated_io; /* If true, a miss resulting in async I/O */
+} PrefetchBufferResult;
+
+/*
+ * Flags influencing the behaviour of ExtendBufferedRel*
+ */
+typedef enum ExtendBufferedFlags
+{
+ /*
+ * Don't acquire extension lock. This is safe only if the relation isn't
+ * shared, an access exclusive lock is held or if this is the startup
+ * process.
+ */
+ EB_SKIP_EXTENSION_LOCK = (1 << 0),
+
+ /* Is this extension part of recovery? */
+ EB_PERFORMING_RECOVERY = (1 << 1),
+
+ /*
+ * Should the fork be created if it does not currently exist? This likely
+ * only ever makes sense for relation forks.
+ */
+ EB_CREATE_FORK_IF_NEEDED = (1 << 2),
+
+ /* Should the first (possibly only) return buffer be returned locked? */
+ EB_LOCK_FIRST = (1 << 3),
+
+ /* Should the smgr size cache be cleared? */
+ EB_CLEAR_SIZE_CACHE = (1 << 4),
+
+ /* internal flags follow */
+ EB_LOCK_TARGET = (1 << 5),
+} ExtendBufferedFlags;
+
+/*
+ * Some functions identify relations either by relation or smgr +
+ * relpersistence. Used via the BMR_REL()/BMR_SMGR() macros below. This
+ * allows us to use the same function for both recovery and normal operation.
+ */
+typedef struct BufferManagerRelation
+{
+ Relation rel;
+ struct SMgrRelationData *smgr;
+ char relpersistence;
+} BufferManagerRelation;
+
+#define BMR_REL(p_rel) ((BufferManagerRelation){.rel = p_rel})
+#define BMR_SMGR(p_smgr, p_relpersistence) ((BufferManagerRelation){.smgr = p_smgr, .relpersistence = p_relpersistence})
+
+
+/* forward declared, to avoid having to expose buf_internals.h here */
+struct WritebackContext;
+
+/* forward declared, to avoid including smgr.h here */
+struct SMgrRelationData;
+
+/* in globals.c ... this duplicates miscadmin.h */
+extern PGDLLIMPORT int NBuffers;
+
+/* in bufmgr.c */
+extern PGDLLIMPORT bool zero_damaged_pages;
+extern PGDLLIMPORT int bgwriter_lru_maxpages;
+extern PGDLLIMPORT double bgwriter_lru_multiplier;
+extern PGDLLIMPORT bool track_io_timing;
+
+/* only applicable when prefetching is available */
+#ifdef USE_PREFETCH
+#define DEFAULT_EFFECTIVE_IO_CONCURRENCY 1
+#define DEFAULT_MAINTENANCE_IO_CONCURRENCY 10
+#else
+#define DEFAULT_EFFECTIVE_IO_CONCURRENCY 0
+#define DEFAULT_MAINTENANCE_IO_CONCURRENCY 0
+#endif
+extern PGDLLIMPORT int effective_io_concurrency;
+extern PGDLLIMPORT int maintenance_io_concurrency;
+
+extern PGDLLIMPORT int checkpoint_flush_after;
+extern PGDLLIMPORT int backend_flush_after;
+extern PGDLLIMPORT int bgwriter_flush_after;
+
+/* in buf_init.c */
+extern PGDLLIMPORT char *BufferBlocks;
+
+/* in localbuf.c */
+extern PGDLLIMPORT int NLocBuffer;
+extern PGDLLIMPORT Block *LocalBufferBlockPointers;
+extern PGDLLIMPORT int32 *LocalRefCount;
+
+/* upper limit for effective_io_concurrency */
+#define MAX_IO_CONCURRENCY 1000
+
+/* special block number for ReadBuffer() */
+#define P_NEW InvalidBlockNumber /* grow the file to get a new page */
+
+/*
+ * Buffer content lock modes (mode argument for LockBuffer())
+ */
+#define BUFFER_LOCK_UNLOCK 0
+#define BUFFER_LOCK_SHARE 1
+#define BUFFER_LOCK_EXCLUSIVE 2
+
+
+/*
+ * prototypes for functions in bufmgr.c
+ */
+extern PrefetchBufferResult PrefetchSharedBuffer(struct SMgrRelationData *smgr_reln,
+ ForkNumber forkNum,
+ BlockNumber blockNum);
+extern PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum,
+ BlockNumber blockNum);
+extern bool ReadRecentBuffer(RelFileLocator rlocator, ForkNumber forkNum,
+ BlockNumber blockNum, Buffer recent_buffer);
+extern Buffer ReadBuffer(Relation reln, BlockNumber blockNum);
+extern Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum,
+ BlockNumber blockNum, ReadBufferMode mode,
+ BufferAccessStrategy strategy);
+extern Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator,
+ ForkNumber forkNum, BlockNumber blockNum,
+ ReadBufferMode mode, BufferAccessStrategy strategy,
+ bool permanent);
+extern void ReleaseBuffer(Buffer buffer);
+extern void UnlockReleaseBuffer(Buffer buffer);
+extern void MarkBufferDirty(Buffer buffer);
+extern void IncrBufferRefCount(Buffer buffer);
+extern void CheckBufferIsPinnedOnce(Buffer buffer);
+extern Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation,
+ BlockNumber blockNum);
+
+extern Buffer ExtendBufferedRel(BufferManagerRelation bmr,
+ ForkNumber forkNum,
+ BufferAccessStrategy strategy,
+ uint32 flags);
+extern BlockNumber ExtendBufferedRelBy(BufferManagerRelation bmr,
+ ForkNumber fork,
+ BufferAccessStrategy strategy,
+ uint32 flags,
+ uint32 extend_by,
+ Buffer *buffers,
+ uint32 *extended_by);
+extern Buffer ExtendBufferedRelTo(BufferManagerRelation bmr,
+ ForkNumber fork,
+ BufferAccessStrategy strategy,
+ uint32 flags,
+ BlockNumber extend_to,
+ ReadBufferMode mode);
+
+extern void InitBufferPoolAccess(void);
+extern void AtEOXact_Buffers(bool isCommit);
+extern void PrintBufferLeakWarning(Buffer buffer);
+extern void CheckPointBuffers(int flags);
+extern BlockNumber BufferGetBlockNumber(Buffer buffer);
+extern BlockNumber RelationGetNumberOfBlocksInFork(Relation relation,
+ ForkNumber forkNum);
+extern void FlushOneBuffer(Buffer buffer);
+extern void FlushRelationBuffers(Relation rel);
+extern void FlushRelationsAllBuffers(struct SMgrRelationData **smgrs, int nrels);
+extern void CreateAndCopyRelationData(RelFileLocator src_rlocator,
+ RelFileLocator dst_rlocator,
+ bool permanent);
+extern void FlushDatabaseBuffers(Oid dbid);
+extern void DropRelationBuffers(struct SMgrRelationData *smgr_reln,
+ ForkNumber *forkNum,
+ int nforks, BlockNumber *firstDelBlock);
+extern void DropRelationsAllBuffers(struct SMgrRelationData **smgr_reln,
+ int nlocators);
+extern void DropDatabaseBuffers(Oid dbid);
+
+#define RelationGetNumberOfBlocks(reln) \
+ RelationGetNumberOfBlocksInFork(reln, MAIN_FORKNUM)
+
+extern bool BufferIsPermanent(Buffer buffer);
+extern XLogRecPtr BufferGetLSNAtomic(Buffer buffer);
+
+#ifdef NOT_USED
+extern void PrintPinnedBufs(void);
+#endif
+extern void BufferGetTag(Buffer buffer, RelFileLocator *rlocator,
+ ForkNumber *forknum, BlockNumber *blknum);
+
+extern void MarkBufferDirtyHint(Buffer buffer, bool buffer_std);
+
+extern void UnlockBuffers(void);
+extern void LockBuffer(Buffer buffer, int mode);
+extern bool ConditionalLockBuffer(Buffer buffer);
+extern void LockBufferForCleanup(Buffer buffer);
+extern bool ConditionalLockBufferForCleanup(Buffer buffer);
+extern bool IsBufferCleanupOK(Buffer buffer);
+extern bool HoldingBufferPinThatDelaysRecovery(void);
+
+extern void AbortBufferIO(Buffer buffer);
+
+extern bool BgBufferSync(struct WritebackContext *wb_context);
+
+extern void TestForOldSnapshot_impl(Snapshot snapshot, Relation relation);
+
+/* in buf_init.c */
+extern void InitBufferPool(void);
+extern Size BufferShmemSize(void);
+
+/* in localbuf.c */
+extern void AtProcExit_LocalBuffers(void);
+
+/* in freelist.c */
+
+extern BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype);
+extern BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype,
+ int ring_size_kb);
+extern int GetAccessStrategyBufferCount(BufferAccessStrategy strategy);
+
+extern void FreeAccessStrategy(BufferAccessStrategy strategy);
+
+
+/* inline functions */
+
+/*
+ * Although this header file is nominally backend-only, certain frontend
+ * programs like pg_waldump include it. For compilers that emit static
+ * inline functions even when they're unused, that leads to unsatisfied
+ * external references; hence hide these with #ifndef FRONTEND.
+ */
+
+#ifndef FRONTEND
+
+/*
+ * BufferIsValid
+ * True iff the given buffer number is valid (either as a shared
+ * or local buffer).
+ *
+ * Note: For a long time this was defined the same as BufferIsPinned,
+ * that is it would say False if you didn't hold a pin on the buffer.
+ * I believe this was bogus and served only to mask logic errors.
+ * Code should always know whether it has a buffer reference,
+ * independently of the pin state.
+ *
+ * Note: For a further long time this was not quite the inverse of the
+ * BufferIsInvalid() macro, in that it also did sanity checks to verify
+ * that the buffer number was in range. Most likely, this macro was
+ * originally intended only to be used in assertions, but its use has
+ * since expanded quite a bit, and the overhead of making those checks
+ * even in non-assert-enabled builds can be significant. Thus, we've
+ * now demoted the range checks to assertions within the macro itself.
+ */
+static inline bool
+BufferIsValid(Buffer bufnum)
+{
+ Assert(bufnum <= NBuffers);
+ Assert(bufnum >= -NLocBuffer);
+
+ return bufnum != InvalidBuffer;
+}
+
+/*
+ * BufferGetBlock
+ * Returns a reference to a disk page image associated with a buffer.
+ *
+ * Note:
+ * Assumes buffer is valid.
+ */
+static inline Block
+BufferGetBlock(Buffer buffer)
+{
+ Assert(BufferIsValid(buffer));
+
+ if (BufferIsLocal(buffer))
+ return LocalBufferBlockPointers[-buffer - 1];
+ else
+ return (Block) (BufferBlocks + ((Size) (buffer - 1)) * BLCKSZ);
+}
+
+/*
+ * BufferGetPageSize
+ * Returns the page size within a buffer.
+ *
+ * Notes:
+ * Assumes buffer is valid.
+ *
+ * The buffer can be a raw disk block and need not contain a valid
+ * (formatted) disk page.
+ */
+/* XXX should dig out of buffer descriptor */
+static inline Size
+BufferGetPageSize(Buffer buffer)
+{
+ AssertMacro(BufferIsValid(buffer));
+ return (Size) BLCKSZ;
+}
+
+/*
+ * BufferGetPage
+ * Returns the page associated with a buffer.
+ *
+ * When this is called as part of a scan, there may be a need for a nearby
+ * call to TestForOldSnapshot(). See the definition of that for details.
+ */
+static inline Page
+BufferGetPage(Buffer buffer)
+{
+ return (Page) BufferGetBlock(buffer);
+}
+
+/*
+ * Check whether the given snapshot is too old to have safely read the given
+ * page from the given table. If so, throw a "snapshot too old" error.
+ *
+ * This test generally needs to be performed after every BufferGetPage() call
+ * that is executed as part of a scan. It is not needed for calls made for
+ * modifying the page (for example, to position to the right place to insert a
+ * new index tuple or for vacuuming). It may also be omitted where calls to
+ * lower-level functions will have already performed the test.
+ *
+ * Note that a NULL snapshot argument is allowed and causes a fast return
+ * without error; this is to support call sites which can be called from
+ * either scans or index modification areas.
+ *
+ * For best performance, keep the tests that are fastest and/or most likely to
+ * exclude a page from old snapshot testing near the front.
+ */
+static inline void
+TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
+{
+ Assert(relation != NULL);
+
+ if (old_snapshot_threshold >= 0
+ && (snapshot) != NULL
+ && ((snapshot)->snapshot_type == SNAPSHOT_MVCC
+ || (snapshot)->snapshot_type == SNAPSHOT_TOAST)
+ && !XLogRecPtrIsInvalid((snapshot)->lsn)
+ && PageGetLSN(page) > (snapshot)->lsn)
+ TestForOldSnapshot_impl(snapshot, relation);
+}
+
+#endif /* FRONTEND */
+
+#endif /* BUFMGR_H */
diff --git a/pgsql/include/server/storage/bufpage.h b/pgsql/include/server/storage/bufpage.h
new file mode 100644
index 0000000000000000000000000000000000000000..424ecba028fc7f8fd958fc09dff374f53de887d1
--- /dev/null
+++ b/pgsql/include/server/storage/bufpage.h
@@ -0,0 +1,510 @@
+/*-------------------------------------------------------------------------
+ *
+ * bufpage.h
+ * Standard POSTGRES buffer page definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/bufpage.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BUFPAGE_H
+#define BUFPAGE_H
+
+#include "access/xlogdefs.h"
+#include "storage/block.h"
+#include "storage/item.h"
+#include "storage/off.h"
+
+/*
+ * A postgres disk page is an abstraction layered on top of a postgres
+ * disk block (which is simply a unit of i/o, see block.h).
+ *
+ * specifically, while a disk block can be unformatted, a postgres
+ * disk page is always a slotted page of the form:
+ *
+ * +----------------+---------------------------------+
+ * | PageHeaderData | linp1 linp2 linp3 ... |
+ * +-----------+----+---------------------------------+
+ * | ... linpN | |
+ * +-----------+--------------------------------------+
+ * | ^ pd_lower |
+ * | |
+ * | v pd_upper |
+ * +-------------+------------------------------------+
+ * | | tupleN ... |
+ * +-------------+------------------+-----------------+
+ * | ... tuple3 tuple2 tuple1 | "special space" |
+ * +--------------------------------+-----------------+
+ * ^ pd_special
+ *
+ * a page is full when nothing can be added between pd_lower and
+ * pd_upper.
+ *
+ * all blocks written out by an access method must be disk pages.
+ *
+ * EXCEPTIONS:
+ *
+ * obviously, a page is not formatted before it is initialized by
+ * a call to PageInit.
+ *
+ * NOTES:
+ *
+ * linp1..N form an ItemId (line pointer) array. ItemPointers point
+ * to a physical block number and a logical offset (line pointer
+ * number) within that block/page. Note that OffsetNumbers
+ * conventionally start at 1, not 0.
+ *
+ * tuple1..N are added "backwards" on the page. Since an ItemPointer
+ * offset is used to access an ItemId entry rather than an actual
+ * byte-offset position, tuples can be physically shuffled on a page
+ * whenever the need arises. This indirection also keeps crash recovery
+ * relatively simple, because the low-level details of page space
+ * management can be controlled by standard buffer page code during
+ * logging, and during recovery.
+ *
+ * AM-generic per-page information is kept in PageHeaderData.
+ *
+ * AM-specific per-page data (if any) is kept in the area marked "special
+ * space"; each AM has an "opaque" structure defined somewhere that is
+ * stored as the page trailer. an access method should always
+ * initialize its pages with PageInit and then set its own opaque
+ * fields.
+ */
+
+typedef Pointer Page;
+
+
+/*
+ * location (byte offset) within a page.
+ *
+ * note that this is actually limited to 2^15 because we have limited
+ * ItemIdData.lp_off and ItemIdData.lp_len to 15 bits (see itemid.h).
+ */
+typedef uint16 LocationIndex;
+
+
+/*
+ * For historical reasons, the 64-bit LSN value is stored as two 32-bit
+ * values.
+ */
+typedef struct
+{
+ uint32 xlogid; /* high bits */
+ uint32 xrecoff; /* low bits */
+} PageXLogRecPtr;
+
+static inline XLogRecPtr
+PageXLogRecPtrGet(PageXLogRecPtr val)
+{
+ return (uint64) val.xlogid << 32 | val.xrecoff;
+}
+
+#define PageXLogRecPtrSet(ptr, lsn) \
+ ((ptr).xlogid = (uint32) ((lsn) >> 32), (ptr).xrecoff = (uint32) (lsn))
+
+/*
+ * disk page organization
+ *
+ * space management information generic to any page
+ *
+ * pd_lsn - identifies xlog record for last change to this page.
+ * pd_checksum - page checksum, if set.
+ * pd_flags - flag bits.
+ * pd_lower - offset to start of free space.
+ * pd_upper - offset to end of free space.
+ * pd_special - offset to start of special space.
+ * pd_pagesize_version - size in bytes and page layout version number.
+ * pd_prune_xid - oldest XID among potentially prunable tuples on page.
+ *
+ * The LSN is used by the buffer manager to enforce the basic rule of WAL:
+ * "thou shalt write xlog before data". A dirty buffer cannot be dumped
+ * to disk until xlog has been flushed at least as far as the page's LSN.
+ *
+ * pd_checksum stores the page checksum, if it has been set for this page;
+ * zero is a valid value for a checksum. If a checksum is not in use then
+ * we leave the field unset. This will typically mean the field is zero
+ * though non-zero values may also be present if databases have been
+ * pg_upgraded from releases prior to 9.3, when the same byte offset was
+ * used to store the current timelineid when the page was last updated.
+ * Note that there is no indication on a page as to whether the checksum
+ * is valid or not, a deliberate design choice which avoids the problem
+ * of relying on the page contents to decide whether to verify it. Hence
+ * there are no flag bits relating to checksums.
+ *
+ * pd_prune_xid is a hint field that helps determine whether pruning will be
+ * useful. It is currently unused in index pages.
+ *
+ * The page version number and page size are packed together into a single
+ * uint16 field. This is for historical reasons: before PostgreSQL 7.3,
+ * there was no concept of a page version number, and doing it this way
+ * lets us pretend that pre-7.3 databases have page version number zero.
+ * We constrain page sizes to be multiples of 256, leaving the low eight
+ * bits available for a version number.
+ *
+ * Minimum possible page size is perhaps 64B to fit page header, opaque space
+ * and a minimal tuple; of course, in reality you want it much bigger, so
+ * the constraint on pagesize mod 256 is not an important restriction.
+ * On the high end, we can only support pages up to 32KB because lp_off/lp_len
+ * are 15 bits.
+ */
+
+typedef struct PageHeaderData
+{
+ /* XXX LSN is member of *any* block, not only page-organized ones */
+ PageXLogRecPtr pd_lsn; /* LSN: next byte after last byte of xlog
+ * record for last change to this page */
+ uint16 pd_checksum; /* checksum */
+ uint16 pd_flags; /* flag bits, see below */
+ LocationIndex pd_lower; /* offset to start of free space */
+ LocationIndex pd_upper; /* offset to end of free space */
+ LocationIndex pd_special; /* offset to start of special space */
+ uint16 pd_pagesize_version;
+ TransactionId pd_prune_xid; /* oldest prunable XID, or zero if none */
+ ItemIdData pd_linp[FLEXIBLE_ARRAY_MEMBER]; /* line pointer array */
+} PageHeaderData;
+
+typedef PageHeaderData *PageHeader;
+
+/*
+ * pd_flags contains the following flag bits. Undefined bits are initialized
+ * to zero and may be used in the future.
+ *
+ * PD_HAS_FREE_LINES is set if there are any LP_UNUSED line pointers before
+ * pd_lower. This should be considered a hint rather than the truth, since
+ * changes to it are not WAL-logged.
+ *
+ * PD_PAGE_FULL is set if an UPDATE doesn't find enough free space in the
+ * page for its new tuple version; this suggests that a prune is needed.
+ * Again, this is just a hint.
+ */
+#define PD_HAS_FREE_LINES 0x0001 /* are there any unused line pointers? */
+#define PD_PAGE_FULL 0x0002 /* not enough free space for new tuple? */
+#define PD_ALL_VISIBLE 0x0004 /* all tuples on page are visible to
+ * everyone */
+
+#define PD_VALID_FLAG_BITS 0x0007 /* OR of all valid pd_flags bits */
+
+/*
+ * Page layout version number 0 is for pre-7.3 Postgres releases.
+ * Releases 7.3 and 7.4 use 1, denoting a new HeapTupleHeader layout.
+ * Release 8.0 uses 2; it changed the HeapTupleHeader layout again.
+ * Release 8.1 uses 3; it redefined HeapTupleHeader infomask bits.
+ * Release 8.3 uses 4; it changed the HeapTupleHeader layout again, and
+ * added the pd_flags field (by stealing some bits from pd_tli),
+ * as well as adding the pd_prune_xid field (which enlarges the header).
+ *
+ * As of Release 9.3, the checksum version must also be considered when
+ * handling pages.
+ */
+#define PG_PAGE_LAYOUT_VERSION 4
+#define PG_DATA_CHECKSUM_VERSION 1
+
+/* ----------------------------------------------------------------
+ * page support functions
+ * ----------------------------------------------------------------
+ */
+
+/*
+ * line pointer(s) do not count as part of header
+ */
+#define SizeOfPageHeaderData (offsetof(PageHeaderData, pd_linp))
+
+/*
+ * PageIsEmpty
+ * returns true iff no itemid has been allocated on the page
+ */
+static inline bool
+PageIsEmpty(Page page)
+{
+ return ((PageHeader) page)->pd_lower <= SizeOfPageHeaderData;
+}
+
+/*
+ * PageIsNew
+ * returns true iff page has not been initialized (by PageInit)
+ */
+static inline bool
+PageIsNew(Page page)
+{
+ return ((PageHeader) page)->pd_upper == 0;
+}
+
+/*
+ * PageGetItemId
+ * Returns an item identifier of a page.
+ */
+static inline ItemId
+PageGetItemId(Page page, OffsetNumber offsetNumber)
+{
+ return &((PageHeader) page)->pd_linp[offsetNumber - 1];
+}
+
+/*
+ * PageGetContents
+ * To be used in cases where the page does not contain line pointers.
+ *
+ * Note: prior to 8.3 this was not guaranteed to yield a MAXALIGN'd result.
+ * Now it is. Beware of old code that might think the offset to the contents
+ * is just SizeOfPageHeaderData rather than MAXALIGN(SizeOfPageHeaderData).
+ */
+static inline char *
+PageGetContents(Page page)
+{
+ return (char *) page + MAXALIGN(SizeOfPageHeaderData);
+}
+
+/* ----------------
+ * functions to access page size info
+ * ----------------
+ */
+
+/*
+ * PageGetPageSize
+ * Returns the page size of a page.
+ *
+ * this can only be called on a formatted page (unlike
+ * BufferGetPageSize, which can be called on an unformatted page).
+ * however, it can be called on a page that is not stored in a buffer.
+ */
+static inline Size
+PageGetPageSize(Page page)
+{
+ return (Size) (((PageHeader) page)->pd_pagesize_version & (uint16) 0xFF00);
+}
+
+/*
+ * PageGetPageLayoutVersion
+ * Returns the page layout version of a page.
+ */
+static inline uint8
+PageGetPageLayoutVersion(Page page)
+{
+ return (((PageHeader) page)->pd_pagesize_version & 0x00FF);
+}
+
+/*
+ * PageSetPageSizeAndVersion
+ * Sets the page size and page layout version number of a page.
+ *
+ * We could support setting these two values separately, but there's
+ * no real need for it at the moment.
+ */
+static inline void
+PageSetPageSizeAndVersion(Page page, Size size, uint8 version)
+{
+ Assert((size & 0xFF00) == size);
+ Assert((version & 0x00FF) == version);
+
+ ((PageHeader) page)->pd_pagesize_version = size | version;
+}
+
+/* ----------------
+ * page special data functions
+ * ----------------
+ */
+/*
+ * PageGetSpecialSize
+ * Returns size of special space on a page.
+ */
+static inline uint16
+PageGetSpecialSize(Page page)
+{
+ return (PageGetPageSize(page) - ((PageHeader) page)->pd_special);
+}
+
+/*
+ * Using assertions, validate that the page special pointer is OK.
+ *
+ * This is intended to catch use of the pointer before page initialization.
+ */
+static inline void
+PageValidateSpecialPointer(Page page)
+{
+ Assert(page);
+ Assert(((PageHeader) page)->pd_special <= BLCKSZ);
+ Assert(((PageHeader) page)->pd_special >= SizeOfPageHeaderData);
+}
+
+/*
+ * PageGetSpecialPointer
+ * Returns pointer to special space on a page.
+ */
+static inline char *
+PageGetSpecialPointer(Page page)
+{
+ PageValidateSpecialPointer(page);
+ return (char *) page + ((PageHeader) page)->pd_special;
+}
+
+/*
+ * PageGetItem
+ * Retrieves an item on the given page.
+ *
+ * Note:
+ * This does not change the status of any of the resources passed.
+ * The semantics may change in the future.
+ */
+static inline Item
+PageGetItem(Page page, ItemId itemId)
+{
+ Assert(page);
+ Assert(ItemIdHasStorage(itemId));
+
+ return (Item) (((char *) page) + ItemIdGetOffset(itemId));
+}
+
+/*
+ * PageGetMaxOffsetNumber
+ * Returns the maximum offset number used by the given page.
+ * Since offset numbers are 1-based, this is also the number
+ * of items on the page.
+ *
+ * NOTE: if the page is not initialized (pd_lower == 0), we must
+ * return zero to ensure sane behavior.
+ */
+static inline OffsetNumber
+PageGetMaxOffsetNumber(Page page)
+{
+ PageHeader pageheader = (PageHeader) page;
+
+ if (pageheader->pd_lower <= SizeOfPageHeaderData)
+ return 0;
+ else
+ return (pageheader->pd_lower - SizeOfPageHeaderData) / sizeof(ItemIdData);
+}
+
+/*
+ * Additional functions for access to page headers.
+ */
+static inline XLogRecPtr
+PageGetLSN(Page page)
+{
+ return PageXLogRecPtrGet(((PageHeader) page)->pd_lsn);
+}
+static inline void
+PageSetLSN(Page page, XLogRecPtr lsn)
+{
+ PageXLogRecPtrSet(((PageHeader) page)->pd_lsn, lsn);
+}
+
+static inline bool
+PageHasFreeLinePointers(Page page)
+{
+ return ((PageHeader) page)->pd_flags & PD_HAS_FREE_LINES;
+}
+static inline void
+PageSetHasFreeLinePointers(Page page)
+{
+ ((PageHeader) page)->pd_flags |= PD_HAS_FREE_LINES;
+}
+static inline void
+PageClearHasFreeLinePointers(Page page)
+{
+ ((PageHeader) page)->pd_flags &= ~PD_HAS_FREE_LINES;
+}
+
+static inline bool
+PageIsFull(Page page)
+{
+ return ((PageHeader) page)->pd_flags & PD_PAGE_FULL;
+}
+static inline void
+PageSetFull(Page page)
+{
+ ((PageHeader) page)->pd_flags |= PD_PAGE_FULL;
+}
+static inline void
+PageClearFull(Page page)
+{
+ ((PageHeader) page)->pd_flags &= ~PD_PAGE_FULL;
+}
+
+static inline bool
+PageIsAllVisible(Page page)
+{
+ return ((PageHeader) page)->pd_flags & PD_ALL_VISIBLE;
+}
+static inline void
+PageSetAllVisible(Page page)
+{
+ ((PageHeader) page)->pd_flags |= PD_ALL_VISIBLE;
+}
+static inline void
+PageClearAllVisible(Page page)
+{
+ ((PageHeader) page)->pd_flags &= ~PD_ALL_VISIBLE;
+}
+
+/*
+ * These two require "access/transam.h", so left as macros.
+ */
+#define PageSetPrunable(page, xid) \
+do { \
+ Assert(TransactionIdIsNormal(xid)); \
+ if (!TransactionIdIsValid(((PageHeader) (page))->pd_prune_xid) || \
+ TransactionIdPrecedes(xid, ((PageHeader) (page))->pd_prune_xid)) \
+ ((PageHeader) (page))->pd_prune_xid = (xid); \
+} while (0)
+#define PageClearPrunable(page) \
+ (((PageHeader) (page))->pd_prune_xid = InvalidTransactionId)
+
+
+/* ----------------------------------------------------------------
+ * extern declarations
+ * ----------------------------------------------------------------
+ */
+
+/* flags for PageAddItemExtended() */
+#define PAI_OVERWRITE (1 << 0)
+#define PAI_IS_HEAP (1 << 1)
+
+/* flags for PageIsVerifiedExtended() */
+#define PIV_LOG_WARNING (1 << 0)
+#define PIV_REPORT_STAT (1 << 1)
+
+#define PageAddItem(page, item, size, offsetNumber, overwrite, is_heap) \
+ PageAddItemExtended(page, item, size, offsetNumber, \
+ ((overwrite) ? PAI_OVERWRITE : 0) | \
+ ((is_heap) ? PAI_IS_HEAP : 0))
+
+#define PageIsVerified(page, blkno) \
+ PageIsVerifiedExtended(page, blkno, \
+ PIV_LOG_WARNING | PIV_REPORT_STAT)
+
+/*
+ * Check that BLCKSZ is a multiple of sizeof(size_t). In
+ * PageIsVerifiedExtended(), it is much faster to check if a page is
+ * full of zeroes using the native word size. Note that this assertion
+ * is kept within a header to make sure that StaticAssertDecl() works
+ * across various combinations of platforms and compilers.
+ */
+StaticAssertDecl(BLCKSZ == ((BLCKSZ / sizeof(size_t)) * sizeof(size_t)),
+ "BLCKSZ has to be a multiple of sizeof(size_t)");
+
+extern void PageInit(Page page, Size pageSize, Size specialSize);
+extern bool PageIsVerifiedExtended(Page page, BlockNumber blkno, int flags);
+extern OffsetNumber PageAddItemExtended(Page page, Item item, Size size,
+ OffsetNumber offsetNumber, int flags);
+extern Page PageGetTempPage(Page page);
+extern Page PageGetTempPageCopy(Page page);
+extern Page PageGetTempPageCopySpecial(Page page);
+extern void PageRestoreTempPage(Page tempPage, Page oldPage);
+extern void PageRepairFragmentation(Page page);
+extern void PageTruncateLinePointerArray(Page page);
+extern Size PageGetFreeSpace(Page page);
+extern Size PageGetFreeSpaceForMultipleTuples(Page page, int ntups);
+extern Size PageGetExactFreeSpace(Page page);
+extern Size PageGetHeapFreeSpace(Page page);
+extern void PageIndexTupleDelete(Page page, OffsetNumber offnum);
+extern void PageIndexMultiDelete(Page page, OffsetNumber *itemnos, int nitems);
+extern void PageIndexTupleDeleteNoCompact(Page page, OffsetNumber offnum);
+extern bool PageIndexTupleOverwrite(Page page, OffsetNumber offnum,
+ Item newtup, Size newsize);
+extern char *PageSetChecksumCopy(Page page, BlockNumber blkno);
+extern void PageSetChecksumInplace(Page page, BlockNumber blkno);
+
+#endif /* BUFPAGE_H */
diff --git a/pgsql/include/server/storage/checksum.h b/pgsql/include/server/storage/checksum.h
new file mode 100644
index 0000000000000000000000000000000000000000..4afd25a0af12978d281fd631dca7f733f9903778
--- /dev/null
+++ b/pgsql/include/server/storage/checksum.h
@@ -0,0 +1,24 @@
+/*-------------------------------------------------------------------------
+ *
+ * checksum.h
+ * Checksum implementation for data pages.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/checksum.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef CHECKSUM_H
+#define CHECKSUM_H
+
+#include "storage/block.h"
+
+/*
+ * Compute the checksum for a Postgres page. The page must be aligned on a
+ * 4-byte boundary.
+ */
+extern uint16 pg_checksum_page(char *page, BlockNumber blkno);
+
+#endif /* CHECKSUM_H */
diff --git a/pgsql/include/server/storage/checksum_impl.h b/pgsql/include/server/storage/checksum_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..7b157161a2db878915277cd2d78ee898a0c63736
--- /dev/null
+++ b/pgsql/include/server/storage/checksum_impl.h
@@ -0,0 +1,215 @@
+/*-------------------------------------------------------------------------
+ *
+ * checksum_impl.h
+ * Checksum implementation for data pages.
+ *
+ * This file exists for the benefit of external programs that may wish to
+ * check Postgres page checksums. They can #include this to get the code
+ * referenced by storage/checksum.h. (Note: you may need to redefine
+ * Assert() as empty to compile this successfully externally.)
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/checksum_impl.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/*
+ * The algorithm used to checksum pages is chosen for very fast calculation.
+ * Workloads where the database working set fits into OS file cache but not
+ * into shared buffers can read in pages at a very fast pace and the checksum
+ * algorithm itself can become the largest bottleneck.
+ *
+ * The checksum algorithm itself is based on the FNV-1a hash (FNV is shorthand
+ * for Fowler/Noll/Vo). The primitive of a plain FNV-1a hash folds in data 1
+ * byte at a time according to the formula:
+ *
+ * hash = (hash ^ value) * FNV_PRIME
+ *
+ * FNV-1a algorithm is described at http://www.isthe.com/chongo/tech/comp/fnv/
+ *
+ * PostgreSQL doesn't use FNV-1a hash directly because it has bad mixing of
+ * high bits - high order bits in input data only affect high order bits in
+ * output data. To resolve this we xor in the value prior to multiplication
+ * shifted right by 17 bits. The number 17 was chosen because it doesn't
+ * have common denominator with set bit positions in FNV_PRIME and empirically
+ * provides the fastest mixing for high order bits of final iterations quickly
+ * avalanche into lower positions. For performance reasons we choose to combine
+ * 4 bytes at a time. The actual hash formula used as the basis is:
+ *
+ * hash = (hash ^ value) * FNV_PRIME ^ ((hash ^ value) >> 17)
+ *
+ * The main bottleneck in this calculation is the multiplication latency. To
+ * hide the latency and to make use of SIMD parallelism multiple hash values
+ * are calculated in parallel. The page is treated as a 32 column two
+ * dimensional array of 32 bit values. Each column is aggregated separately
+ * into a partial checksum. Each partial checksum uses a different initial
+ * value (offset basis in FNV terminology). The initial values actually used
+ * were chosen randomly, as the values themselves don't matter as much as that
+ * they are different and don't match anything in real data. After initializing
+ * partial checksums each value in the column is aggregated according to the
+ * above formula. Finally two more iterations of the formula are performed with
+ * value 0 to mix the bits of the last value added.
+ *
+ * The partial checksums are then folded together using xor to form a single
+ * 32-bit checksum. The caller can safely reduce the value to 16 bits
+ * using modulo 2^16-1. That will cause a very slight bias towards lower
+ * values but this is not significant for the performance of the
+ * checksum.
+ *
+ * The algorithm choice was based on what instructions are available in SIMD
+ * instruction sets. This meant that a fast and good algorithm needed to use
+ * multiplication as the main mixing operator. The simplest multiplication
+ * based checksum primitive is the one used by FNV. The prime used is chosen
+ * for good dispersion of values. It has no known simple patterns that result
+ * in collisions. Test of 5-bit differentials of the primitive over 64bit keys
+ * reveals no differentials with 3 or more values out of 100000 random keys
+ * colliding. Avalanche test shows that only high order bits of the last word
+ * have a bias. Tests of 1-4 uncorrelated bit errors, stray 0 and 0xFF bytes,
+ * overwriting page from random position to end with 0 bytes, and overwriting
+ * random segments of page with 0x00, 0xFF and random data all show optimal
+ * 2e-16 false positive rate within margin of error.
+ *
+ * Vectorization of the algorithm requires 32bit x 32bit -> 32bit integer
+ * multiplication instruction. As of 2013 the corresponding instruction is
+ * available on x86 SSE4.1 extensions (pmulld) and ARM NEON (vmul.i32).
+ * Vectorization requires a compiler to do the vectorization for us. For recent
+ * GCC versions the flags -msse4.1 -funroll-loops -ftree-vectorize are enough
+ * to achieve vectorization.
+ *
+ * The optimal amount of parallelism to use depends on CPU specific instruction
+ * latency, SIMD instruction width, throughput and the amount of registers
+ * available to hold intermediate state. Generally, more parallelism is better
+ * up to the point that state doesn't fit in registers and extra load-store
+ * instructions are needed to swap values in/out. The number chosen is a fixed
+ * part of the algorithm because changing the parallelism changes the checksum
+ * result.
+ *
+ * The parallelism number 32 was chosen based on the fact that it is the
+ * largest state that fits into architecturally visible x86 SSE registers while
+ * leaving some free registers for intermediate values. For future processors
+ * with 256bit vector registers this will leave some performance on the table.
+ * When vectorization is not available it might be beneficial to restructure
+ * the computation to calculate a subset of the columns at a time and perform
+ * multiple passes to avoid register spilling. This optimization opportunity
+ * is not used. Current coding also assumes that the compiler has the ability
+ * to unroll the inner loop to avoid loop overhead and minimize register
+ * spilling. For less sophisticated compilers it might be beneficial to
+ * manually unroll the inner loop.
+ */
+
+#include "storage/bufpage.h"
+
+/* number of checksums to calculate in parallel */
+#define N_SUMS 32
+/* prime multiplier of FNV-1a hash */
+#define FNV_PRIME 16777619
+
+/* Use a union so that this code is valid under strict aliasing */
+typedef union
+{
+ PageHeaderData phdr;
+ uint32 data[BLCKSZ / (sizeof(uint32) * N_SUMS)][N_SUMS];
+} PGChecksummablePage;
+
+/*
+ * Base offsets to initialize each of the parallel FNV hashes into a
+ * different initial state.
+ */
+static const uint32 checksumBaseOffsets[N_SUMS] = {
+ 0x5B1F36E9, 0xB8525960, 0x02AB50AA, 0x1DE66D2A,
+ 0x79FF467A, 0x9BB9F8A3, 0x217E7CD2, 0x83E13D2C,
+ 0xF8D4474F, 0xE39EB970, 0x42C6AE16, 0x993216FA,
+ 0x7B093B5D, 0x98DAFF3C, 0xF718902A, 0x0B1C9CDB,
+ 0xE58F764B, 0x187636BC, 0x5D7B3BB1, 0xE73DE7DE,
+ 0x92BEC979, 0xCCA6C0B2, 0x304A0979, 0x85AA43D4,
+ 0x783125BB, 0x6CA8EAA2, 0xE407EAC6, 0x4B5CFC3E,
+ 0x9FBF8C76, 0x15CA20BE, 0xF2CA9FD3, 0x959BD756
+};
+
+/*
+ * Calculate one round of the checksum.
+ */
+#define CHECKSUM_COMP(checksum, value) \
+do { \
+ uint32 __tmp = (checksum) ^ (value); \
+ (checksum) = __tmp * FNV_PRIME ^ (__tmp >> 17); \
+} while (0)
+
+/*
+ * Block checksum algorithm. The page must be adequately aligned
+ * (at least on 4-byte boundary).
+ */
+static uint32
+pg_checksum_block(const PGChecksummablePage *page)
+{
+ uint32 sums[N_SUMS];
+ uint32 result = 0;
+ uint32 i,
+ j;
+
+ /* ensure that the size is compatible with the algorithm */
+ Assert(sizeof(PGChecksummablePage) == BLCKSZ);
+
+ /* initialize partial checksums to their corresponding offsets */
+ memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets));
+
+ /* main checksum calculation */
+ for (i = 0; i < (uint32) (BLCKSZ / (sizeof(uint32) * N_SUMS)); i++)
+ for (j = 0; j < N_SUMS; j++)
+ CHECKSUM_COMP(sums[j], page->data[i][j]);
+
+ /* finally add in two rounds of zeroes for additional mixing */
+ for (i = 0; i < 2; i++)
+ for (j = 0; j < N_SUMS; j++)
+ CHECKSUM_COMP(sums[j], 0);
+
+ /* xor fold partial checksums together */
+ for (i = 0; i < N_SUMS; i++)
+ result ^= sums[i];
+
+ return result;
+}
+
+/*
+ * Compute the checksum for a Postgres page.
+ *
+ * The page must be adequately aligned (at least on a 4-byte boundary).
+ * Beware also that the checksum field of the page is transiently zeroed.
+ *
+ * The checksum includes the block number (to detect the case where a page is
+ * somehow moved to a different location), the page header (excluding the
+ * checksum itself), and the page data.
+ */
+uint16
+pg_checksum_page(char *page, BlockNumber blkno)
+{
+ PGChecksummablePage *cpage = (PGChecksummablePage *) page;
+ uint16 save_checksum;
+ uint32 checksum;
+
+ /* We only calculate the checksum for properly-initialized pages */
+ Assert(!PageIsNew((Page) page));
+
+ /*
+ * Save pd_checksum and temporarily set it to zero, so that the checksum
+ * calculation isn't affected by the old checksum stored on the page.
+ * Restore it after, because actually updating the checksum is NOT part of
+ * the API of this function.
+ */
+ save_checksum = cpage->phdr.pd_checksum;
+ cpage->phdr.pd_checksum = 0;
+ checksum = pg_checksum_block(cpage);
+ cpage->phdr.pd_checksum = save_checksum;
+
+ /* Mix in the block number to detect transposed pages */
+ checksum ^= blkno;
+
+ /*
+ * Reduce to a uint16 (to fit in the pd_checksum field) with an offset of
+ * one. That avoids checksums of zero, which seems like a good idea.
+ */
+ return (uint16) ((checksum % 65535) + 1);
+}
diff --git a/pgsql/include/server/storage/condition_variable.h b/pgsql/include/server/storage/condition_variable.h
new file mode 100644
index 0000000000000000000000000000000000000000..e218cb2c499fef6230439fb193c0da5fc307c594
--- /dev/null
+++ b/pgsql/include/server/storage/condition_variable.h
@@ -0,0 +1,73 @@
+/*-------------------------------------------------------------------------
+ *
+ * condition_variable.h
+ * Condition variables
+ *
+ * A condition variable is a method of waiting until a certain condition
+ * becomes true. Conventionally, a condition variable supports three
+ * operations: (1) sleep; (2) signal, which wakes up one process sleeping
+ * on the condition variable; and (3) broadcast, which wakes up every
+ * process sleeping on the condition variable. In our implementation,
+ * condition variables put a process into an interruptible sleep (so it
+ * can be canceled prior to the fulfillment of the condition) and do not
+ * use pointers internally (so that they are safe to use within DSMs).
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/condition_variable.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef CONDITION_VARIABLE_H
+#define CONDITION_VARIABLE_H
+
+#include "storage/proclist_types.h"
+#include "storage/spin.h"
+
+typedef struct
+{
+ slock_t mutex; /* spinlock protecting the wakeup list */
+ proclist_head wakeup; /* list of wake-able processes */
+} ConditionVariable;
+
+/*
+ * Pad a condition variable to a power-of-two size so that an array of
+ * condition variables does not cross a cache line boundary.
+ */
+#define CV_MINIMAL_SIZE (sizeof(ConditionVariable) <= 16 ? 16 : 32)
+typedef union ConditionVariableMinimallyPadded
+{
+ ConditionVariable cv;
+ char pad[CV_MINIMAL_SIZE];
+} ConditionVariableMinimallyPadded;
+
+/* Initialize a condition variable. */
+extern void ConditionVariableInit(ConditionVariable *cv);
+
+/*
+ * To sleep on a condition variable, a process should use a loop which first
+ * checks the condition, exiting the loop if it is met, and then calls
+ * ConditionVariableSleep. Spurious wakeups are possible, but should be
+ * infrequent. After exiting the loop, ConditionVariableCancelSleep must
+ * be called to ensure that the process is no longer in the wait list for
+ * the condition variable.
+ */
+extern void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info);
+extern bool ConditionVariableTimedSleep(ConditionVariable *cv, long timeout,
+ uint32 wait_event_info);
+extern bool ConditionVariableCancelSleep(void);
+
+/*
+ * Optionally, ConditionVariablePrepareToSleep can be called before entering
+ * the test-and-sleep loop described above. Doing so is more efficient if
+ * at least one sleep is needed, whereas not doing so is more efficient when
+ * no sleep is needed because the test condition is true the first time.
+ */
+extern void ConditionVariablePrepareToSleep(ConditionVariable *cv);
+
+/* Wake up a single waiter (via signal) or all waiters (via broadcast). */
+extern void ConditionVariableSignal(ConditionVariable *cv);
+extern void ConditionVariableBroadcast(ConditionVariable *cv);
+
+#endif /* CONDITION_VARIABLE_H */
diff --git a/pgsql/include/server/storage/copydir.h b/pgsql/include/server/storage/copydir.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8be5b21e0b2eaf6f33211a985ccd40a68ce3707
--- /dev/null
+++ b/pgsql/include/server/storage/copydir.h
@@ -0,0 +1,19 @@
+/*-------------------------------------------------------------------------
+ *
+ * copydir.h
+ * Copy a directory.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/copydir.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef COPYDIR_H
+#define COPYDIR_H
+
+extern void copydir(const char *fromdir, const char *todir, bool recurse);
+extern void copy_file(const char *fromfile, const char *tofile);
+
+#endif /* COPYDIR_H */
diff --git a/pgsql/include/server/storage/dsm.h b/pgsql/include/server/storage/dsm.h
new file mode 100644
index 0000000000000000000000000000000000000000..858bbf61c28d3f8298c35cd9cf49b9be9d5c2df2
--- /dev/null
+++ b/pgsql/include/server/storage/dsm.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * dsm.h
+ * manage dynamic shared memory segments
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/dsm.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DSM_H
+#define DSM_H
+
+#include "storage/dsm_impl.h"
+
+typedef struct dsm_segment dsm_segment;
+
+#define DSM_CREATE_NULL_IF_MAXSEGMENTS 0x0001
+
+/* Startup and shutdown functions. */
+struct PGShmemHeader; /* avoid including pg_shmem.h */
+extern void dsm_cleanup_using_control_segment(dsm_handle old_control_handle);
+extern void dsm_postmaster_startup(struct PGShmemHeader *);
+extern void dsm_backend_shutdown(void);
+extern void dsm_detach_all(void);
+
+extern size_t dsm_estimate_size(void);
+extern void dsm_shmem_init(void);
+
+#ifdef EXEC_BACKEND
+extern void dsm_set_control_handle(dsm_handle h);
+#endif
+
+/* Functions that create or remove mappings. */
+extern dsm_segment *dsm_create(Size size, int flags);
+extern dsm_segment *dsm_attach(dsm_handle h);
+extern void dsm_detach(dsm_segment *seg);
+
+/* Resource management functions. */
+extern void dsm_pin_mapping(dsm_segment *seg);
+extern void dsm_unpin_mapping(dsm_segment *seg);
+extern void dsm_pin_segment(dsm_segment *seg);
+extern void dsm_unpin_segment(dsm_handle handle);
+extern dsm_segment *dsm_find_mapping(dsm_handle handle);
+
+/* Informational functions. */
+extern void *dsm_segment_address(dsm_segment *seg);
+extern Size dsm_segment_map_length(dsm_segment *seg);
+extern dsm_handle dsm_segment_handle(dsm_segment *seg);
+
+/* Cleanup hooks. */
+typedef void (*on_dsm_detach_callback) (dsm_segment *, Datum arg);
+extern void on_dsm_detach(dsm_segment *seg,
+ on_dsm_detach_callback function, Datum arg);
+extern void cancel_on_dsm_detach(dsm_segment *seg,
+ on_dsm_detach_callback function, Datum arg);
+extern void reset_on_dsm_detach(void);
+
+#endif /* DSM_H */
diff --git a/pgsql/include/server/storage/dsm_impl.h b/pgsql/include/server/storage/dsm_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..daf07bd19cd6831430065fb7d2fdd6947547d470
--- /dev/null
+++ b/pgsql/include/server/storage/dsm_impl.h
@@ -0,0 +1,79 @@
+/*-------------------------------------------------------------------------
+ *
+ * dsm_impl.h
+ * low-level dynamic shared memory primitives
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/dsm_impl.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DSM_IMPL_H
+#define DSM_IMPL_H
+
+/* Dynamic shared memory implementations. */
+#define DSM_IMPL_POSIX 1
+#define DSM_IMPL_SYSV 2
+#define DSM_IMPL_WINDOWS 3
+#define DSM_IMPL_MMAP 4
+
+/*
+ * Determine which dynamic shared memory implementations will be supported
+ * on this platform, and which one will be the default.
+ */
+#ifdef WIN32
+#define USE_DSM_WINDOWS
+#define DEFAULT_DYNAMIC_SHARED_MEMORY_TYPE DSM_IMPL_WINDOWS
+#else
+#ifdef HAVE_SHM_OPEN
+#define USE_DSM_POSIX
+#define DEFAULT_DYNAMIC_SHARED_MEMORY_TYPE DSM_IMPL_POSIX
+#endif
+#define USE_DSM_SYSV
+#ifndef DEFAULT_DYNAMIC_SHARED_MEMORY_TYPE
+#define DEFAULT_DYNAMIC_SHARED_MEMORY_TYPE DSM_IMPL_SYSV
+#endif
+#define USE_DSM_MMAP
+#endif
+
+/* GUC. */
+extern PGDLLIMPORT int dynamic_shared_memory_type;
+extern PGDLLIMPORT int min_dynamic_shared_memory;
+
+/*
+ * Directory for on-disk state.
+ *
+ * This is used by all implementations for crash recovery and by the mmap
+ * implementation for storage.
+ */
+#define PG_DYNSHMEM_DIR "pg_dynshmem"
+#define PG_DYNSHMEM_MMAP_FILE_PREFIX "mmap."
+
+/* A "name" for a dynamic shared memory segment. */
+typedef uint32 dsm_handle;
+
+/* Sentinel value to use for invalid DSM handles. */
+#define DSM_HANDLE_INVALID ((dsm_handle) 0)
+
+/* All the shared-memory operations we know about. */
+typedef enum
+{
+ DSM_OP_CREATE,
+ DSM_OP_ATTACH,
+ DSM_OP_DETACH,
+ DSM_OP_DESTROY
+} dsm_op;
+
+/* Create, attach to, detach from, resize, or destroy a segment. */
+extern bool dsm_impl_op(dsm_op op, dsm_handle handle, Size request_size,
+ void **impl_private, void **mapped_address, Size *mapped_size,
+ int elevel);
+
+/* Implementation-dependent actions required to keep segment until shutdown. */
+extern void dsm_impl_pin_segment(dsm_handle handle, void *impl_private,
+ void **impl_private_pm_handle);
+extern void dsm_impl_unpin_segment(dsm_handle handle, void **impl_private);
+
+#endif /* DSM_IMPL_H */
diff --git a/pgsql/include/server/storage/fd.h b/pgsql/include/server/storage/fd.h
new file mode 100644
index 0000000000000000000000000000000000000000..6791a406fc11441857ba8168d2f3e52b9292f35a
--- /dev/null
+++ b/pgsql/include/server/storage/fd.h
@@ -0,0 +1,202 @@
+/*-------------------------------------------------------------------------
+ *
+ * fd.h
+ * Virtual file descriptor definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/fd.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+/*
+ * calls:
+ *
+ * File {Close, Read, Write, Size, Sync}
+ * {Path Name Open, Allocate, Free} File
+ *
+ * These are NOT JUST RENAMINGS OF THE UNIX ROUTINES.
+ * Use them for all file activity...
+ *
+ * File fd;
+ * fd = PathNameOpenFile("foo", O_RDONLY);
+ *
+ * AllocateFile();
+ * FreeFile();
+ *
+ * Use AllocateFile, not fopen, if you need a stdio file (FILE*); then
+ * use FreeFile, not fclose, to close it. AVOID using stdio for files
+ * that you intend to hold open for any length of time, since there is
+ * no way for them to share kernel file descriptors with other files.
+ *
+ * Likewise, use AllocateDir/FreeDir, not opendir/closedir, to allocate
+ * open directories (DIR*), and OpenTransientFile/CloseTransientFile for an
+ * unbuffered file descriptor.
+ *
+ * If you really can't use any of the above, at least call AcquireExternalFD
+ * or ReserveExternalFD to report any file descriptors that are held for any
+ * length of time. Failure to do so risks unnecessary EMFILE errors.
+ */
+#ifndef FD_H
+#define FD_H
+
+#include
+#include
+
+typedef enum RecoveryInitSyncMethod
+{
+ RECOVERY_INIT_SYNC_METHOD_FSYNC,
+ RECOVERY_INIT_SYNC_METHOD_SYNCFS
+} RecoveryInitSyncMethod;
+
+typedef int File;
+
+
+#define IO_DIRECT_DATA 0x01
+#define IO_DIRECT_WAL 0x02
+#define IO_DIRECT_WAL_INIT 0x04
+
+
+/* GUC parameter */
+extern PGDLLIMPORT int max_files_per_process;
+extern PGDLLIMPORT bool data_sync_retry;
+extern PGDLLIMPORT int recovery_init_sync_method;
+extern PGDLLIMPORT int io_direct_flags;
+
+/*
+ * This is private to fd.c, but exported for save/restore_backend_variables()
+ */
+extern PGDLLIMPORT int max_safe_fds;
+
+/*
+ * On Windows, we have to interpret EACCES as possibly meaning the same as
+ * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
+ * that's what you get. Ugh. This code is designed so that we don't
+ * actually believe these cases are okay without further evidence (namely,
+ * a pending fsync request getting canceled ... see ProcessSyncRequests).
+ */
+#ifndef WIN32
+#define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT)
+#else
+#define FILE_POSSIBLY_DELETED(err) ((err) == ENOENT || (err) == EACCES)
+#endif
+
+/*
+ * O_DIRECT is not standard, but almost every Unix has it. We translate it
+ * to the appropriate Windows flag in src/port/open.c. We simulate it with
+ * fcntl(F_NOCACHE) on macOS inside fd.c's open() wrapper. We use the name
+ * PG_O_DIRECT rather than defining O_DIRECT in that case (probably not a good
+ * idea on a Unix). We can only use it if the compiler will correctly align
+ * PGIOAlignedBlock for us, though.
+ */
+#if defined(O_DIRECT) && defined(pg_attribute_aligned)
+#define PG_O_DIRECT O_DIRECT
+#elif defined(F_NOCACHE)
+#define PG_O_DIRECT 0x80000000
+#define PG_O_DIRECT_USE_F_NOCACHE
+#else
+#define PG_O_DIRECT 0
+#endif
+
+/*
+ * prototypes for functions in fd.c
+ */
+
+/* Operations on virtual Files --- equivalent to Unix kernel file ops */
+extern File PathNameOpenFile(const char *fileName, int fileFlags);
+extern File PathNameOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode);
+extern File OpenTemporaryFile(bool interXact);
+extern void FileClose(File file);
+extern int FilePrefetch(File file, off_t offset, off_t amount, uint32 wait_event_info);
+extern int FileRead(File file, void *buffer, size_t amount, off_t offset, uint32 wait_event_info);
+extern int FileWrite(File file, const void *buffer, size_t amount, off_t offset, uint32 wait_event_info);
+extern int FileSync(File file, uint32 wait_event_info);
+extern int FileZero(File file, off_t offset, off_t amount, uint32 wait_event_info);
+extern int FileFallocate(File file, off_t offset, off_t amount, uint32 wait_event_info);
+
+extern off_t FileSize(File file);
+extern int FileTruncate(File file, off_t offset, uint32 wait_event_info);
+extern void FileWriteback(File file, off_t offset, off_t nbytes, uint32 wait_event_info);
+extern char *FilePathName(File file);
+extern int FileGetRawDesc(File file);
+extern int FileGetRawFlags(File file);
+extern mode_t FileGetRawMode(File file);
+
+/* Operations used for sharing named temporary files */
+extern File PathNameCreateTemporaryFile(const char *path, bool error_on_failure);
+extern File PathNameOpenTemporaryFile(const char *path, int mode);
+extern bool PathNameDeleteTemporaryFile(const char *path, bool error_on_failure);
+extern void PathNameCreateTemporaryDir(const char *basedir, const char *directory);
+extern void PathNameDeleteTemporaryDir(const char *dirname);
+extern void TempTablespacePath(char *path, Oid tablespace);
+
+/* Operations that allow use of regular stdio --- USE WITH CAUTION */
+extern FILE *AllocateFile(const char *name, const char *mode);
+extern int FreeFile(FILE *file);
+
+/* Operations that allow use of pipe streams (popen/pclose) */
+extern FILE *OpenPipeStream(const char *command, const char *mode);
+extern int ClosePipeStream(FILE *file);
+
+/* Operations to allow use of the library routines */
+extern DIR *AllocateDir(const char *dirname);
+extern struct dirent *ReadDir(DIR *dir, const char *dirname);
+extern struct dirent *ReadDirExtended(DIR *dir, const char *dirname,
+ int elevel);
+extern int FreeDir(DIR *dir);
+
+/* Operations to allow use of a plain kernel FD, with automatic cleanup */
+extern int OpenTransientFile(const char *fileName, int fileFlags);
+extern int OpenTransientFilePerm(const char *fileName, int fileFlags, mode_t fileMode);
+extern int CloseTransientFile(int fd);
+
+/* If you've really really gotta have a plain kernel FD, use this */
+extern int BasicOpenFile(const char *fileName, int fileFlags);
+extern int BasicOpenFilePerm(const char *fileName, int fileFlags, mode_t fileMode);
+
+/* Use these for other cases, and also for long-lived BasicOpenFile FDs */
+extern bool AcquireExternalFD(void);
+extern void ReserveExternalFD(void);
+extern void ReleaseExternalFD(void);
+
+/* Make a directory with default permissions */
+extern int MakePGDirectory(const char *directoryName);
+
+/* Miscellaneous support routines */
+extern void InitFileAccess(void);
+extern void InitTemporaryFileAccess(void);
+extern void set_max_safe_fds(void);
+extern void closeAllVfds(void);
+extern void SetTempTablespaces(Oid *tableSpaces, int numSpaces);
+extern bool TempTablespacesAreSet(void);
+extern int GetTempTablespaces(Oid *tableSpaces, int numSpaces);
+extern Oid GetNextTempTableSpace(void);
+extern void AtEOXact_Files(bool isCommit);
+extern void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid,
+ SubTransactionId parentSubid);
+extern void RemovePgTempFiles(void);
+extern void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok,
+ bool unlink_all);
+extern bool looks_like_temp_rel_name(const char *name);
+
+extern int pg_fsync(int fd);
+extern int pg_fsync_no_writethrough(int fd);
+extern int pg_fsync_writethrough(int fd);
+extern int pg_fdatasync(int fd);
+extern void pg_flush_data(int fd, off_t offset, off_t nbytes);
+extern int pg_truncate(const char *path, off_t length);
+extern void fsync_fname(const char *fname, bool isdir);
+extern int fsync_fname_ext(const char *fname, bool isdir, bool ignore_perm, int elevel);
+extern int durable_rename(const char *oldfile, const char *newfile, int elevel);
+extern int durable_unlink(const char *fname, int elevel);
+extern void SyncDataDirectory(void);
+extern int data_sync_elevel(int elevel);
+
+/* Filename components */
+#define PG_TEMP_FILES_DIR "pgsql_tmp"
+#define PG_TEMP_FILE_PREFIX "pgsql_tmp"
+
+#endif /* FD_H */
diff --git a/pgsql/include/server/storage/fileset.h b/pgsql/include/server/storage/fileset.h
new file mode 100644
index 0000000000000000000000000000000000000000..9aa6581d29693c9ebf979edaf4e7eb517bfee0e0
--- /dev/null
+++ b/pgsql/include/server/storage/fileset.h
@@ -0,0 +1,40 @@
+/*-------------------------------------------------------------------------
+ *
+ * fileset.h
+ * Management of named temporary files.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/fileset.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef FILESET_H
+#define FILESET_H
+
+#include "storage/fd.h"
+
+/*
+ * A set of temporary files.
+ */
+typedef struct FileSet
+{
+ pid_t creator_pid; /* PID of the creating process */
+ uint32 number; /* per-PID identifier */
+ int ntablespaces; /* number of tablespaces to use */
+ Oid tablespaces[8]; /* OIDs of tablespaces to use. Assumes that
+ * it's rare that there more than temp
+ * tablespaces. */
+} FileSet;
+
+extern void FileSetInit(FileSet *fileset);
+extern File FileSetCreate(FileSet *fileset, const char *name);
+extern File FileSetOpen(FileSet *fileset, const char *name,
+ int mode);
+extern bool FileSetDelete(FileSet *fileset, const char *name,
+ bool error_on_failure);
+extern void FileSetDeleteAll(FileSet *fileset);
+
+#endif
diff --git a/pgsql/include/server/storage/freespace.h b/pgsql/include/server/storage/freespace.h
new file mode 100644
index 0000000000000000000000000000000000000000..9e1a85a141c56938d9b35a3e548201322085d350
--- /dev/null
+++ b/pgsql/include/server/storage/freespace.h
@@ -0,0 +1,39 @@
+/*-------------------------------------------------------------------------
+ *
+ * freespace.h
+ * POSTGRES free space map for quickly finding free space in relations
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/freespace.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FREESPACE_H_
+#define FREESPACE_H_
+
+#include "storage/block.h"
+#include "storage/relfilelocator.h"
+#include "utils/relcache.h"
+
+/* prototypes for public functions in freespace.c */
+extern Size GetRecordedFreeSpace(Relation rel, BlockNumber heapBlk);
+extern BlockNumber GetPageWithFreeSpace(Relation rel, Size spaceNeeded);
+extern BlockNumber RecordAndGetPageWithFreeSpace(Relation rel,
+ BlockNumber oldPage,
+ Size oldSpaceAvail,
+ Size spaceNeeded);
+extern void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk,
+ Size spaceAvail);
+extern void XLogRecordPageWithFreeSpace(RelFileLocator rlocator, BlockNumber heapBlk,
+ Size spaceAvail);
+
+extern BlockNumber FreeSpaceMapPrepareTruncateRel(Relation rel,
+ BlockNumber nblocks);
+extern void FreeSpaceMapVacuum(Relation rel);
+extern void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start,
+ BlockNumber end);
+
+#endif /* FREESPACE_H_ */
diff --git a/pgsql/include/server/storage/fsm_internals.h b/pgsql/include/server/storage/fsm_internals.h
new file mode 100644
index 0000000000000000000000000000000000000000..9e314c83fa4f06e59975f550edab881be1b8d06b
--- /dev/null
+++ b/pgsql/include/server/storage/fsm_internals.h
@@ -0,0 +1,72 @@
+/*-------------------------------------------------------------------------
+ *
+ * fsm_internals.h
+ * internal functions for free space map
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/fsm_internals.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FSM_INTERNALS_H
+#define FSM_INTERNALS_H
+
+#include "storage/buf.h"
+#include "storage/bufpage.h"
+
+/*
+ * Structure of a FSM page. See src/backend/storage/freespace/README for
+ * details.
+ */
+typedef struct
+{
+ /*
+ * fsm_search_avail() tries to spread the load of multiple backends by
+ * returning different pages to different backends in a round-robin
+ * fashion. fp_next_slot points to the next slot to be returned (assuming
+ * there's enough space on it for the request). It's defined as an int,
+ * because it's updated without an exclusive lock. uint16 would be more
+ * appropriate, but int is more likely to be atomically
+ * fetchable/storable.
+ */
+ int fp_next_slot;
+
+ /*
+ * fp_nodes contains the binary tree, stored in array. The first
+ * NonLeafNodesPerPage elements are upper nodes, and the following
+ * LeafNodesPerPage elements are leaf nodes. Unused nodes are zero.
+ */
+ uint8 fp_nodes[FLEXIBLE_ARRAY_MEMBER];
+} FSMPageData;
+
+typedef FSMPageData *FSMPage;
+
+/*
+ * Number of non-leaf and leaf nodes, and nodes in total, on an FSM page.
+ * These definitions are internal to fsmpage.c.
+ */
+#define NodesPerPage (BLCKSZ - MAXALIGN(SizeOfPageHeaderData) - \
+ offsetof(FSMPageData, fp_nodes))
+
+#define NonLeafNodesPerPage (BLCKSZ / 2 - 1)
+#define LeafNodesPerPage (NodesPerPage - NonLeafNodesPerPage)
+
+/*
+ * Number of FSM "slots" on a FSM page. This is what should be used
+ * outside fsmpage.c.
+ */
+#define SlotsPerFSMPage LeafNodesPerPage
+
+/* Prototypes for functions in fsmpage.c */
+extern int fsm_search_avail(Buffer buf, uint8 minvalue, bool advancenext,
+ bool exclusive_lock_held);
+extern uint8 fsm_get_avail(Page page, int slot);
+extern uint8 fsm_get_max_avail(Page page);
+extern bool fsm_set_avail(Page page, int slot, uint8 value);
+extern bool fsm_truncate_avail(Page page, int nslots);
+extern bool fsm_rebuild_page(Page page);
+
+#endif /* FSM_INTERNALS_H */
diff --git a/pgsql/include/server/storage/indexfsm.h b/pgsql/include/server/storage/indexfsm.h
new file mode 100644
index 0000000000000000000000000000000000000000..aed77a7a9f071657f605d76af5e60883b24dc018
--- /dev/null
+++ b/pgsql/include/server/storage/indexfsm.h
@@ -0,0 +1,26 @@
+/*-------------------------------------------------------------------------
+ *
+ * indexfsm.h
+ * POSTGRES free space map for quickly finding an unused page in index
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/indexfsm.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef INDEXFSM_H_
+#define INDEXFSM_H_
+
+#include "storage/block.h"
+#include "utils/relcache.h"
+
+extern BlockNumber GetFreeIndexPage(Relation rel);
+extern void RecordFreeIndexPage(Relation rel, BlockNumber freeBlock);
+extern void RecordUsedIndexPage(Relation rel, BlockNumber usedBlock);
+
+extern void IndexFreeSpaceMapVacuum(Relation rel);
+
+#endif /* INDEXFSM_H_ */
diff --git a/pgsql/include/server/storage/ipc.h b/pgsql/include/server/storage/ipc.h
new file mode 100644
index 0000000000000000000000000000000000000000..888c08b30675e59d86516774cae44fe4884788ec
--- /dev/null
+++ b/pgsql/include/server/storage/ipc.h
@@ -0,0 +1,84 @@
+/*-------------------------------------------------------------------------
+ *
+ * ipc.h
+ * POSTGRES inter-process communication definitions.
+ *
+ * This file is misnamed, as it no longer has much of anything directly
+ * to do with IPC. The functionality here is concerned with managing
+ * exit-time cleanup for either a postmaster or a backend.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/ipc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef IPC_H
+#define IPC_H
+
+typedef void (*pg_on_exit_callback) (int code, Datum arg);
+typedef void (*shmem_startup_hook_type) (void);
+
+/*----------
+ * API for handling cleanup that must occur during either ereport(ERROR)
+ * or ereport(FATAL) exits from a block of code. (Typical examples are
+ * undoing transient changes to shared-memory state.)
+ *
+ * PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg);
+ * {
+ * ... code that might throw ereport(ERROR) or ereport(FATAL) ...
+ * }
+ * PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg);
+ *
+ * where the cleanup code is in a function declared per pg_on_exit_callback.
+ * The Datum value "arg" can carry any information the cleanup function
+ * needs.
+ *
+ * This construct ensures that cleanup_function() will be called during
+ * either ERROR or FATAL exits. It will not be called on successful
+ * exit from the controlled code. (If you want it to happen then too,
+ * call the function yourself from just after the construct.)
+ *
+ * Note: the macro arguments are multiply evaluated, so avoid side-effects.
+ *----------
+ */
+#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg) \
+ do { \
+ before_shmem_exit(cleanup_function, arg); \
+ PG_TRY()
+
+#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg) \
+ cancel_before_shmem_exit(cleanup_function, arg); \
+ PG_CATCH(); \
+ { \
+ cancel_before_shmem_exit(cleanup_function, arg); \
+ cleanup_function (0, arg); \
+ PG_RE_THROW(); \
+ } \
+ PG_END_TRY(); \
+ } while (0)
+
+
+/* ipc.c */
+extern PGDLLIMPORT bool proc_exit_inprogress;
+extern PGDLLIMPORT bool shmem_exit_inprogress;
+
+extern void proc_exit(int code) pg_attribute_noreturn();
+extern void shmem_exit(int code);
+extern void on_proc_exit(pg_on_exit_callback function, Datum arg);
+extern void on_shmem_exit(pg_on_exit_callback function, Datum arg);
+extern void before_shmem_exit(pg_on_exit_callback function, Datum arg);
+extern void cancel_before_shmem_exit(pg_on_exit_callback function, Datum arg);
+extern void on_exit_reset(void);
+extern void check_on_shmem_exit_lists_are_empty(void);
+
+/* ipci.c */
+extern PGDLLIMPORT shmem_startup_hook_type shmem_startup_hook;
+
+extern Size CalculateShmemSize(int *num_semaphores);
+extern void CreateSharedMemoryAndSemaphores(void);
+extern void InitializeShmemGUCs(void);
+
+#endif /* IPC_H */
diff --git a/pgsql/include/server/storage/item.h b/pgsql/include/server/storage/item.h
new file mode 100644
index 0000000000000000000000000000000000000000..56d59a70cdf322862de2dba3a1cec50cb7b90a38
--- /dev/null
+++ b/pgsql/include/server/storage/item.h
@@ -0,0 +1,19 @@
+/*-------------------------------------------------------------------------
+ *
+ * item.h
+ * POSTGRES disk item definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/item.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ITEM_H
+#define ITEM_H
+
+typedef Pointer Item;
+
+#endif /* ITEM_H */
diff --git a/pgsql/include/server/storage/itemid.h b/pgsql/include/server/storage/itemid.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5cfb8c3ccb895f2fc1f600c816246f566406620
--- /dev/null
+++ b/pgsql/include/server/storage/itemid.h
@@ -0,0 +1,184 @@
+/*-------------------------------------------------------------------------
+ *
+ * itemid.h
+ * Standard POSTGRES buffer page item identifier/line pointer definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/itemid.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ITEMID_H
+#define ITEMID_H
+
+/*
+ * A line pointer on a buffer page. See buffer page definitions and comments
+ * for an explanation of how line pointers are used.
+ *
+ * In some cases a line pointer is "in use" but does not have any associated
+ * storage on the page. By convention, lp_len == 0 in every line pointer
+ * that does not have storage, independently of its lp_flags state.
+ */
+typedef struct ItemIdData
+{
+ unsigned lp_off:15, /* offset to tuple (from start of page) */
+ lp_flags:2, /* state of line pointer, see below */
+ lp_len:15; /* byte length of tuple */
+} ItemIdData;
+
+typedef ItemIdData *ItemId;
+
+/*
+ * lp_flags has these possible states. An UNUSED line pointer is available
+ * for immediate re-use, the other states are not.
+ */
+#define LP_UNUSED 0 /* unused (should always have lp_len=0) */
+#define LP_NORMAL 1 /* used (should always have lp_len>0) */
+#define LP_REDIRECT 2 /* HOT redirect (should have lp_len=0) */
+#define LP_DEAD 3 /* dead, may or may not have storage */
+
+/*
+ * Item offsets and lengths are represented by these types when
+ * they're not actually stored in an ItemIdData.
+ */
+typedef uint16 ItemOffset;
+typedef uint16 ItemLength;
+
+
+/* ----------------
+ * support macros
+ * ----------------
+ */
+
+/*
+ * ItemIdGetLength
+ */
+#define ItemIdGetLength(itemId) \
+ ((itemId)->lp_len)
+
+/*
+ * ItemIdGetOffset
+ */
+#define ItemIdGetOffset(itemId) \
+ ((itemId)->lp_off)
+
+/*
+ * ItemIdGetFlags
+ */
+#define ItemIdGetFlags(itemId) \
+ ((itemId)->lp_flags)
+
+/*
+ * ItemIdGetRedirect
+ * In a REDIRECT pointer, lp_off holds offset number for next line pointer
+ */
+#define ItemIdGetRedirect(itemId) \
+ ((itemId)->lp_off)
+
+/*
+ * ItemIdIsValid
+ * True iff item identifier is valid.
+ * This is a pretty weak test, probably useful only in Asserts.
+ */
+#define ItemIdIsValid(itemId) PointerIsValid(itemId)
+
+/*
+ * ItemIdIsUsed
+ * True iff item identifier is in use.
+ */
+#define ItemIdIsUsed(itemId) \
+ ((itemId)->lp_flags != LP_UNUSED)
+
+/*
+ * ItemIdIsNormal
+ * True iff item identifier is in state NORMAL.
+ */
+#define ItemIdIsNormal(itemId) \
+ ((itemId)->lp_flags == LP_NORMAL)
+
+/*
+ * ItemIdIsRedirected
+ * True iff item identifier is in state REDIRECT.
+ */
+#define ItemIdIsRedirected(itemId) \
+ ((itemId)->lp_flags == LP_REDIRECT)
+
+/*
+ * ItemIdIsDead
+ * True iff item identifier is in state DEAD.
+ */
+#define ItemIdIsDead(itemId) \
+ ((itemId)->lp_flags == LP_DEAD)
+
+/*
+ * ItemIdHasStorage
+ * True iff item identifier has associated storage.
+ */
+#define ItemIdHasStorage(itemId) \
+ ((itemId)->lp_len != 0)
+
+/*
+ * ItemIdSetUnused
+ * Set the item identifier to be UNUSED, with no storage.
+ * Beware of multiple evaluations of itemId!
+ */
+#define ItemIdSetUnused(itemId) \
+( \
+ (itemId)->lp_flags = LP_UNUSED, \
+ (itemId)->lp_off = 0, \
+ (itemId)->lp_len = 0 \
+)
+
+/*
+ * ItemIdSetNormal
+ * Set the item identifier to be NORMAL, with the specified storage.
+ * Beware of multiple evaluations of itemId!
+ */
+#define ItemIdSetNormal(itemId, off, len) \
+( \
+ (itemId)->lp_flags = LP_NORMAL, \
+ (itemId)->lp_off = (off), \
+ (itemId)->lp_len = (len) \
+)
+
+/*
+ * ItemIdSetRedirect
+ * Set the item identifier to be REDIRECT, with the specified link.
+ * Beware of multiple evaluations of itemId!
+ */
+#define ItemIdSetRedirect(itemId, link) \
+( \
+ (itemId)->lp_flags = LP_REDIRECT, \
+ (itemId)->lp_off = (link), \
+ (itemId)->lp_len = 0 \
+)
+
+/*
+ * ItemIdSetDead
+ * Set the item identifier to be DEAD, with no storage.
+ * Beware of multiple evaluations of itemId!
+ */
+#define ItemIdSetDead(itemId) \
+( \
+ (itemId)->lp_flags = LP_DEAD, \
+ (itemId)->lp_off = 0, \
+ (itemId)->lp_len = 0 \
+)
+
+/*
+ * ItemIdMarkDead
+ * Set the item identifier to be DEAD, keeping its existing storage.
+ *
+ * Note: in indexes, this is used as if it were a hint-bit mechanism;
+ * we trust that multiple processors can do this in parallel and get
+ * the same result.
+ */
+#define ItemIdMarkDead(itemId) \
+( \
+ (itemId)->lp_flags = LP_DEAD \
+)
+
+#endif /* ITEMID_H */
diff --git a/pgsql/include/server/storage/itemptr.h b/pgsql/include/server/storage/itemptr.h
new file mode 100644
index 0000000000000000000000000000000000000000..fafefa14cd8cb60dcbfb887c61e75e3420ef2abe
--- /dev/null
+++ b/pgsql/include/server/storage/itemptr.h
@@ -0,0 +1,245 @@
+/*-------------------------------------------------------------------------
+ *
+ * itemptr.h
+ * POSTGRES disk item pointer definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/itemptr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ITEMPTR_H
+#define ITEMPTR_H
+
+#include "storage/block.h"
+#include "storage/off.h"
+
+/*
+ * ItemPointer:
+ *
+ * This is a pointer to an item within a disk page of a known file
+ * (for example, a cross-link from an index to its parent table).
+ * ip_blkid tells us which block, ip_posid tells us which entry in
+ * the linp (ItemIdData) array we want.
+ *
+ * Note: because there is an item pointer in each tuple header and index
+ * tuple header on disk, it's very important not to waste space with
+ * structure padding bytes. The struct is designed to be six bytes long
+ * (it contains three int16 fields) but a few compilers will pad it to
+ * eight bytes unless coerced. We apply appropriate persuasion where
+ * possible. If your compiler can't be made to play along, you'll waste
+ * lots of space.
+ */
+typedef struct ItemPointerData
+{
+ BlockIdData ip_blkid;
+ OffsetNumber ip_posid;
+}
+
+/* If compiler understands packed and aligned pragmas, use those */
+#if defined(pg_attribute_packed) && defined(pg_attribute_aligned)
+ pg_attribute_packed()
+ pg_attribute_aligned(2)
+#endif
+ItemPointerData;
+
+typedef ItemPointerData *ItemPointer;
+
+/* ----------------
+ * special values used in heap tuples (t_ctid)
+ * ----------------
+ */
+
+/*
+ * If a heap tuple holds a speculative insertion token rather than a real
+ * TID, ip_posid is set to SpecTokenOffsetNumber, and the token is stored in
+ * ip_blkid. SpecTokenOffsetNumber must be higher than MaxOffsetNumber, so
+ * that it can be distinguished from a valid offset number in a regular item
+ * pointer.
+ */
+#define SpecTokenOffsetNumber 0xfffe
+
+/*
+ * When a tuple is moved to a different partition by UPDATE, the t_ctid of
+ * the old tuple version is set to this magic value.
+ */
+#define MovedPartitionsOffsetNumber 0xfffd
+#define MovedPartitionsBlockNumber InvalidBlockNumber
+
+
+/* ----------------
+ * support functions
+ * ----------------
+ */
+
+/*
+ * ItemPointerIsValid
+ * True iff the disk item pointer is not NULL.
+ */
+static inline bool
+ItemPointerIsValid(const ItemPointerData *pointer)
+{
+ return PointerIsValid(pointer) && pointer->ip_posid != 0;
+}
+
+/*
+ * ItemPointerGetBlockNumberNoCheck
+ * Returns the block number of a disk item pointer.
+ */
+static inline BlockNumber
+ItemPointerGetBlockNumberNoCheck(const ItemPointerData *pointer)
+{
+ return BlockIdGetBlockNumber(&pointer->ip_blkid);
+}
+
+/*
+ * ItemPointerGetBlockNumber
+ * As above, but verifies that the item pointer looks valid.
+ */
+static inline BlockNumber
+ItemPointerGetBlockNumber(const ItemPointerData *pointer)
+{
+ Assert(ItemPointerIsValid(pointer));
+ return ItemPointerGetBlockNumberNoCheck(pointer);
+}
+
+/*
+ * ItemPointerGetOffsetNumberNoCheck
+ * Returns the offset number of a disk item pointer.
+ */
+static inline OffsetNumber
+ItemPointerGetOffsetNumberNoCheck(const ItemPointerData *pointer)
+{
+ return pointer->ip_posid;
+}
+
+/*
+ * ItemPointerGetOffsetNumber
+ * As above, but verifies that the item pointer looks valid.
+ */
+static inline OffsetNumber
+ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
+{
+ Assert(ItemPointerIsValid(pointer));
+ return ItemPointerGetOffsetNumberNoCheck(pointer);
+}
+
+/*
+ * ItemPointerSet
+ * Sets a disk item pointer to the specified block and offset.
+ */
+static inline void
+ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
+{
+ Assert(PointerIsValid(pointer));
+ BlockIdSet(&pointer->ip_blkid, blockNumber);
+ pointer->ip_posid = offNum;
+}
+
+/*
+ * ItemPointerSetBlockNumber
+ * Sets a disk item pointer to the specified block.
+ */
+static inline void
+ItemPointerSetBlockNumber(ItemPointerData *pointer, BlockNumber blockNumber)
+{
+ Assert(PointerIsValid(pointer));
+ BlockIdSet(&pointer->ip_blkid, blockNumber);
+}
+
+/*
+ * ItemPointerSetOffsetNumber
+ * Sets a disk item pointer to the specified offset.
+ */
+static inline void
+ItemPointerSetOffsetNumber(ItemPointerData *pointer, OffsetNumber offsetNumber)
+{
+ Assert(PointerIsValid(pointer));
+ pointer->ip_posid = offsetNumber;
+}
+
+/*
+ * ItemPointerCopy
+ * Copies the contents of one disk item pointer to another.
+ *
+ * Should there ever be padding in an ItemPointer this would need to be handled
+ * differently as it's used as hash key.
+ */
+static inline void
+ItemPointerCopy(const ItemPointerData *fromPointer, ItemPointerData *toPointer)
+{
+ Assert(PointerIsValid(toPointer));
+ Assert(PointerIsValid(fromPointer));
+ *toPointer = *fromPointer;
+}
+
+/*
+ * ItemPointerSetInvalid
+ * Sets a disk item pointer to be invalid.
+ */
+static inline void
+ItemPointerSetInvalid(ItemPointerData *pointer)
+{
+ Assert(PointerIsValid(pointer));
+ BlockIdSet(&pointer->ip_blkid, InvalidBlockNumber);
+ pointer->ip_posid = InvalidOffsetNumber;
+}
+
+/*
+ * ItemPointerIndicatesMovedPartitions
+ * True iff the block number indicates the tuple has moved to another
+ * partition.
+ */
+static inline bool
+ItemPointerIndicatesMovedPartitions(const ItemPointerData *pointer)
+{
+ return
+ ItemPointerGetOffsetNumber(pointer) == MovedPartitionsOffsetNumber &&
+ ItemPointerGetBlockNumberNoCheck(pointer) == MovedPartitionsBlockNumber;
+}
+
+/*
+ * ItemPointerSetMovedPartitions
+ * Indicate that the item referenced by the itempointer has moved into a
+ * different partition.
+ */
+static inline void
+ItemPointerSetMovedPartitions(ItemPointerData *pointer)
+{
+ ItemPointerSet(pointer, MovedPartitionsBlockNumber, MovedPartitionsOffsetNumber);
+}
+
+/* ----------------
+ * externs
+ * ----------------
+ */
+
+extern bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2);
+extern int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2);
+extern void ItemPointerInc(ItemPointer pointer);
+extern void ItemPointerDec(ItemPointer pointer);
+
+/* ----------------
+ * Datum conversion functions
+ * ----------------
+ */
+
+static inline ItemPointer
+DatumGetItemPointer(Datum X)
+{
+ return (ItemPointer) DatumGetPointer(X);
+}
+
+static inline Datum
+ItemPointerGetDatum(const ItemPointerData *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_ITEMPOINTER(n) DatumGetItemPointer(PG_GETARG_DATUM(n))
+#define PG_RETURN_ITEMPOINTER(x) return ItemPointerGetDatum(x)
+
+#endif /* ITEMPTR_H */
diff --git a/pgsql/include/server/storage/large_object.h b/pgsql/include/server/storage/large_object.h
new file mode 100644
index 0000000000000000000000000000000000000000..db521f23eb80ccd6627af1c1368935048ddda4ac
--- /dev/null
+++ b/pgsql/include/server/storage/large_object.h
@@ -0,0 +1,100 @@
+/*-------------------------------------------------------------------------
+ *
+ * large_object.h
+ * Declarations for PostgreSQL large objects. POSTGRES 4.2 supported
+ * zillions of large objects (internal, external, jaquith, inversion).
+ * Now we only support inversion.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/large_object.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LARGE_OBJECT_H
+#define LARGE_OBJECT_H
+
+#include "utils/snapshot.h"
+
+
+/*----------
+ * Data about a currently-open large object.
+ *
+ * id is the logical OID of the large object
+ * snapshot is the snapshot to use for read/write operations
+ * subid is the subtransaction that opened the desc (or currently owns it)
+ * offset is the current seek offset within the LO
+ * flags contains some flag bits
+ *
+ * NOTE: as of v11, permission checks are made when the large object is
+ * opened; therefore IFS_RDLOCK/IFS_WRLOCK indicate that read or write mode
+ * has been requested *and* the corresponding permission has been checked.
+ *
+ * NOTE: before 7.1, we also had to store references to the separate table
+ * and index of a specific large object. Now they all live in pg_largeobject
+ * and are accessed via a common relation descriptor.
+ *----------
+ */
+typedef struct LargeObjectDesc
+{
+ Oid id; /* LO's identifier */
+ Snapshot snapshot; /* snapshot to use */
+ SubTransactionId subid; /* owning subtransaction ID */
+ uint64 offset; /* current seek pointer */
+ int flags; /* see flag bits below */
+
+/* bits in flags: */
+#define IFS_RDLOCK (1 << 0) /* LO was opened for reading */
+#define IFS_WRLOCK (1 << 1) /* LO was opened for writing */
+
+} LargeObjectDesc;
+
+
+/*
+ * Each "page" (tuple) of a large object can hold this much data
+ *
+ * We could set this as high as BLCKSZ less some overhead, but it seems
+ * better to make it a smaller value, so that not as much space is used
+ * up when a page-tuple is updated. Note that the value is deliberately
+ * chosen large enough to trigger the tuple toaster, so that we will
+ * attempt to compress page tuples in-line. (But they won't be moved off
+ * unless the user creates a toast-table for pg_largeobject...)
+ *
+ * Also, it seems to be a smart move to make the page size be a power of 2,
+ * since clients will often be written to send data in power-of-2 blocks.
+ * This avoids unnecessary tuple updates caused by partial-page writes.
+ *
+ * NB: Changing LOBLKSIZE requires an initdb.
+ */
+#define LOBLKSIZE (BLCKSZ / 4)
+
+/*
+ * Maximum length in bytes for a large object. To make this larger, we'd
+ * have to widen pg_largeobject.pageno as well as various internal variables.
+ */
+#define MAX_LARGE_OBJECT_SIZE ((int64) INT_MAX * LOBLKSIZE)
+
+
+/*
+ * GUC: backwards-compatibility flag to suppress LO permission checks
+ */
+extern PGDLLIMPORT bool lo_compat_privileges;
+
+/*
+ * Function definitions...
+ */
+
+/* inversion stuff in inv_api.c */
+extern void close_lo_relation(bool isCommit);
+extern Oid inv_create(Oid lobjId);
+extern LargeObjectDesc *inv_open(Oid lobjId, int flags, MemoryContext mcxt);
+extern void inv_close(LargeObjectDesc *obj_desc);
+extern int inv_drop(Oid lobjId);
+extern int64 inv_seek(LargeObjectDesc *obj_desc, int64 offset, int whence);
+extern int64 inv_tell(LargeObjectDesc *obj_desc);
+extern int inv_read(LargeObjectDesc *obj_desc, char *buf, int nbytes);
+extern int inv_write(LargeObjectDesc *obj_desc, const char *buf, int nbytes);
+extern void inv_truncate(LargeObjectDesc *obj_desc, int64 len);
+
+#endif /* LARGE_OBJECT_H */
diff --git a/pgsql/include/server/storage/latch.h b/pgsql/include/server/storage/latch.h
new file mode 100644
index 0000000000000000000000000000000000000000..99cc47874ac66c2f65afe97052b0e251fa107902
--- /dev/null
+++ b/pgsql/include/server/storage/latch.h
@@ -0,0 +1,194 @@
+/*-------------------------------------------------------------------------
+ *
+ * latch.h
+ * Routines for interprocess latches
+ *
+ * A latch is a boolean variable, with operations that let processes sleep
+ * until it is set. A latch can be set from another process, or a signal
+ * handler within the same process.
+ *
+ * The latch interface is a reliable replacement for the common pattern of
+ * using pg_usleep() or select() to wait until a signal arrives, where the
+ * signal handler sets a flag variable. Because on some platforms an
+ * incoming signal doesn't interrupt sleep, and even on platforms where it
+ * does there is a race condition if the signal arrives just before
+ * entering the sleep, the common pattern must periodically wake up and
+ * poll the flag variable. The pselect() system call was invented to solve
+ * this problem, but it is not portable enough. Latches are designed to
+ * overcome these limitations, allowing you to sleep without polling and
+ * ensuring quick response to signals from other processes.
+ *
+ * There are two kinds of latches: local and shared. A local latch is
+ * initialized by InitLatch, and can only be set from the same process.
+ * A local latch can be used to wait for a signal to arrive, by calling
+ * SetLatch in the signal handler. A shared latch resides in shared memory,
+ * and must be initialized at postmaster startup by InitSharedLatch. Before
+ * a shared latch can be waited on, it must be associated with a process
+ * with OwnLatch. Only the process owning the latch can wait on it, but any
+ * process can set it.
+ *
+ * There are three basic operations on a latch:
+ *
+ * SetLatch - Sets the latch
+ * ResetLatch - Clears the latch, allowing it to be set again
+ * WaitLatch - Waits for the latch to become set
+ *
+ * WaitLatch includes a provision for timeouts (which should be avoided
+ * when possible, as they incur extra overhead) and a provision for
+ * postmaster child processes to wake up immediately on postmaster death.
+ * See latch.c for detailed specifications for the exported functions.
+ *
+ * The correct pattern to wait for event(s) is:
+ *
+ * for (;;)
+ * {
+ * ResetLatch();
+ * if (work to do)
+ * Do Stuff();
+ * WaitLatch();
+ * }
+ *
+ * It's important to reset the latch *before* checking if there's work to
+ * do. Otherwise, if someone sets the latch between the check and the
+ * ResetLatch call, you will miss it and Wait will incorrectly block.
+ *
+ * Another valid coding pattern looks like:
+ *
+ * for (;;)
+ * {
+ * if (work to do)
+ * Do Stuff(); // in particular, exit loop if some condition satisfied
+ * WaitLatch();
+ * ResetLatch();
+ * }
+ *
+ * This is useful to reduce latch traffic if it's expected that the loop's
+ * termination condition will often be satisfied in the first iteration;
+ * the cost is an extra loop iteration before blocking when it is not.
+ * What must be avoided is placing any checks for asynchronous events after
+ * WaitLatch and before ResetLatch, as that creates a race condition.
+ *
+ * To wake up the waiter, you must first set a global flag or something
+ * else that the wait loop tests in the "if (work to do)" part, and call
+ * SetLatch *after* that. SetLatch is designed to return quickly if the
+ * latch is already set.
+ *
+ * On some platforms, signals will not interrupt the latch wait primitive
+ * by themselves. Therefore, it is critical that any signal handler that
+ * is meant to terminate a WaitLatch wait calls SetLatch.
+ *
+ * Note that use of the process latch (PGPROC.procLatch) is generally better
+ * than an ad-hoc shared latch for signaling auxiliary processes. This is
+ * because generic signal handlers will call SetLatch on the process latch
+ * only, so using any latch other than the process latch effectively precludes
+ * use of any generic handler.
+ *
+ *
+ * WaitEventSets allow to wait for latches being set and additional events -
+ * postmaster dying and socket readiness of several sockets currently - at the
+ * same time. On many platforms using a long lived event set is more
+ * efficient than using WaitLatch or WaitLatchOrSocket.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/latch.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LATCH_H
+#define LATCH_H
+
+#include
+
+/*
+ * Latch structure should be treated as opaque and only accessed through
+ * the public functions. It is defined here to allow embedding Latches as
+ * part of bigger structs.
+ */
+typedef struct Latch
+{
+ sig_atomic_t is_set;
+ sig_atomic_t maybe_sleeping;
+ bool is_shared;
+ int owner_pid;
+#ifdef WIN32
+ HANDLE event;
+#endif
+} Latch;
+
+/*
+ * Bitmasks for events that may wake-up WaitLatch(), WaitLatchOrSocket(), or
+ * WaitEventSetWait().
+ */
+#define WL_LATCH_SET (1 << 0)
+#define WL_SOCKET_READABLE (1 << 1)
+#define WL_SOCKET_WRITEABLE (1 << 2)
+#define WL_TIMEOUT (1 << 3) /* not for WaitEventSetWait() */
+#define WL_POSTMASTER_DEATH (1 << 4)
+#define WL_EXIT_ON_PM_DEATH (1 << 5)
+#ifdef WIN32
+#define WL_SOCKET_CONNECTED (1 << 6)
+#else
+/* avoid having to deal with case on platforms not requiring it */
+#define WL_SOCKET_CONNECTED WL_SOCKET_WRITEABLE
+#endif
+#define WL_SOCKET_CLOSED (1 << 7)
+#ifdef WIN32
+#define WL_SOCKET_ACCEPT (1 << 8)
+#else
+/* avoid having to deal with case on platforms not requiring it */
+#define WL_SOCKET_ACCEPT WL_SOCKET_READABLE
+#endif
+#define WL_SOCKET_MASK (WL_SOCKET_READABLE | \
+ WL_SOCKET_WRITEABLE | \
+ WL_SOCKET_CONNECTED | \
+ WL_SOCKET_ACCEPT | \
+ WL_SOCKET_CLOSED)
+
+typedef struct WaitEvent
+{
+ int pos; /* position in the event data structure */
+ uint32 events; /* triggered events */
+ pgsocket fd; /* socket fd associated with event */
+ void *user_data; /* pointer provided in AddWaitEventToSet */
+#ifdef WIN32
+ bool reset; /* Is reset of the event required? */
+#endif
+} WaitEvent;
+
+/* forward declaration to avoid exposing latch.c implementation details */
+typedef struct WaitEventSet WaitEventSet;
+
+/*
+ * prototypes for functions in latch.c
+ */
+extern void InitializeLatchSupport(void);
+extern void InitLatch(Latch *latch);
+extern void InitSharedLatch(Latch *latch);
+extern void OwnLatch(Latch *latch);
+extern void DisownLatch(Latch *latch);
+extern void SetLatch(Latch *latch);
+extern void ResetLatch(Latch *latch);
+extern void ShutdownLatchSupport(void);
+
+extern WaitEventSet *CreateWaitEventSet(MemoryContext context, int nevents);
+extern void FreeWaitEventSet(WaitEventSet *set);
+extern void FreeWaitEventSetAfterFork(WaitEventSet *set);
+extern int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd,
+ Latch *latch, void *user_data);
+extern void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch);
+
+extern int WaitEventSetWait(WaitEventSet *set, long timeout,
+ WaitEvent *occurred_events, int nevents,
+ uint32 wait_event_info);
+extern int WaitLatch(Latch *latch, int wakeEvents, long timeout,
+ uint32 wait_event_info);
+extern int WaitLatchOrSocket(Latch *latch, int wakeEvents,
+ pgsocket sock, long timeout, uint32 wait_event_info);
+extern void InitializeLatchWaitSet(void);
+extern int GetNumRegisteredWaitEvents(WaitEventSet *set);
+extern bool WaitEventSetCanReportClosed(void);
+
+#endif /* LATCH_H */
diff --git a/pgsql/include/server/storage/lmgr.h b/pgsql/include/server/storage/lmgr.h
new file mode 100644
index 0000000000000000000000000000000000000000..8ab833d1d4ac3b381d08ed2a3cce9ffb68278f98
--- /dev/null
+++ b/pgsql/include/server/storage/lmgr.h
@@ -0,0 +1,122 @@
+/*-------------------------------------------------------------------------
+ *
+ * lmgr.h
+ * POSTGRES lock manager definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/lmgr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LMGR_H
+#define LMGR_H
+
+#include "lib/stringinfo.h"
+#include "storage/itemptr.h"
+#include "storage/lock.h"
+#include "utils/rel.h"
+
+
+/* XactLockTableWait operations */
+typedef enum XLTW_Oper
+{
+ XLTW_None,
+ XLTW_Update,
+ XLTW_Delete,
+ XLTW_Lock,
+ XLTW_LockUpdated,
+ XLTW_InsertIndex,
+ XLTW_InsertIndexUnique,
+ XLTW_FetchUpdated,
+ XLTW_RecheckExclusionConstr
+} XLTW_Oper;
+
+extern void RelationInitLockInfo(Relation relation);
+
+/* Lock a relation */
+extern void LockRelationOid(Oid relid, LOCKMODE lockmode);
+extern void LockRelationId(LockRelId *relid, LOCKMODE lockmode);
+extern bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode);
+extern void UnlockRelationId(LockRelId *relid, LOCKMODE lockmode);
+extern void UnlockRelationOid(Oid relid, LOCKMODE lockmode);
+
+extern void LockRelation(Relation relation, LOCKMODE lockmode);
+extern bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode);
+extern void UnlockRelation(Relation relation, LOCKMODE lockmode);
+extern bool CheckRelationLockedByMe(Relation relation, LOCKMODE lockmode,
+ bool orstronger);
+extern bool LockHasWaitersRelation(Relation relation, LOCKMODE lockmode);
+
+extern void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode);
+extern void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode);
+
+/* Lock a relation for extension */
+extern void LockRelationForExtension(Relation relation, LOCKMODE lockmode);
+extern void UnlockRelationForExtension(Relation relation, LOCKMODE lockmode);
+extern bool ConditionalLockRelationForExtension(Relation relation,
+ LOCKMODE lockmode);
+extern int RelationExtensionLockWaiterCount(Relation relation);
+
+/* Lock to recompute pg_database.datfrozenxid in the current database */
+extern void LockDatabaseFrozenIds(LOCKMODE lockmode);
+
+/* Lock a page (currently only used within indexes) */
+extern void LockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode);
+extern bool ConditionalLockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode);
+extern void UnlockPage(Relation relation, BlockNumber blkno, LOCKMODE lockmode);
+
+/* Lock a tuple (see heap_lock_tuple before assuming you understand this) */
+extern void LockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode);
+extern bool ConditionalLockTuple(Relation relation, ItemPointer tid,
+ LOCKMODE lockmode);
+extern void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode);
+
+/* Lock an XID (used to wait for a transaction to finish) */
+extern void XactLockTableInsert(TransactionId xid);
+extern void XactLockTableDelete(TransactionId xid);
+extern void XactLockTableWait(TransactionId xid, Relation rel,
+ ItemPointer ctid, XLTW_Oper oper);
+extern bool ConditionalXactLockTableWait(TransactionId xid);
+
+/* Lock VXIDs, specified by conflicting locktags */
+extern void WaitForLockers(LOCKTAG heaplocktag, LOCKMODE lockmode, bool progress);
+extern void WaitForLockersMultiple(List *locktags, LOCKMODE lockmode, bool progress);
+
+/* Lock an XID for tuple insertion (used to wait for an insertion to finish) */
+extern uint32 SpeculativeInsertionLockAcquire(TransactionId xid);
+extern void SpeculativeInsertionLockRelease(TransactionId xid);
+extern void SpeculativeInsertionWait(TransactionId xid, uint32 token);
+
+/* Lock a general object (other than a relation) of the current database */
+extern void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid,
+ LOCKMODE lockmode);
+extern bool ConditionalLockDatabaseObject(Oid classid, Oid objid,
+ uint16 objsubid, LOCKMODE lockmode);
+extern void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid,
+ LOCKMODE lockmode);
+
+/* Lock a shared-across-databases object (other than a relation) */
+extern void LockSharedObject(Oid classid, Oid objid, uint16 objsubid,
+ LOCKMODE lockmode);
+extern void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid,
+ LOCKMODE lockmode);
+
+extern void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid,
+ LOCKMODE lockmode);
+extern void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid,
+ LOCKMODE lockmode);
+
+extern void LockApplyTransactionForSession(Oid suboid, TransactionId xid, uint16 objid,
+ LOCKMODE lockmode);
+extern void UnlockApplyTransactionForSession(Oid suboid, TransactionId xid, uint16 objid,
+ LOCKMODE lockmode);
+
+/* Describe a locktag for error messages */
+extern void DescribeLockTag(StringInfo buf, const LOCKTAG *tag);
+
+extern const char *GetLockNameFromTagType(uint16 locktag_type);
+
+#endif /* LMGR_H */
diff --git a/pgsql/include/server/storage/lock.h b/pgsql/include/server/storage/lock.h
new file mode 100644
index 0000000000000000000000000000000000000000..8575bea25c7640c2e0c95d52749bd258087b1d57
--- /dev/null
+++ b/pgsql/include/server/storage/lock.h
@@ -0,0 +1,624 @@
+/*-------------------------------------------------------------------------
+ *
+ * lock.h
+ * POSTGRES low-level lock mechanism
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/lock.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOCK_H_
+#define LOCK_H_
+
+#ifdef FRONTEND
+#error "lock.h may not be included from frontend code"
+#endif
+
+#include "lib/ilist.h"
+#include "storage/backendid.h"
+#include "storage/lockdefs.h"
+#include "storage/lwlock.h"
+#include "storage/shmem.h"
+#include "utils/timestamp.h"
+
+/* struct PGPROC is declared in proc.h, but must forward-reference it */
+typedef struct PGPROC PGPROC;
+
+/* GUC variables */
+extern PGDLLIMPORT int max_locks_per_xact;
+
+#ifdef LOCK_DEBUG
+extern PGDLLIMPORT int Trace_lock_oidmin;
+extern PGDLLIMPORT bool Trace_locks;
+extern PGDLLIMPORT bool Trace_userlocks;
+extern PGDLLIMPORT int Trace_lock_table;
+extern PGDLLIMPORT bool Debug_deadlocks;
+#endif /* LOCK_DEBUG */
+
+
+/*
+ * Top-level transactions are identified by VirtualTransactionIDs comprising
+ * PGPROC fields backendId and lxid. For recovered prepared transactions, the
+ * LocalTransactionId is an ordinary XID; LOCKTAG_VIRTUALTRANSACTION never
+ * refers to that kind. These are guaranteed unique over the short term, but
+ * will be reused after a database restart or XID wraparound; hence they
+ * should never be stored on disk.
+ *
+ * Note that struct VirtualTransactionId can not be assumed to be atomically
+ * assignable as a whole. However, type LocalTransactionId is assumed to
+ * be atomically assignable, and the backend ID doesn't change often enough
+ * to be a problem, so we can fetch or assign the two fields separately.
+ * We deliberately refrain from using the struct within PGPROC, to prevent
+ * coding errors from trying to use struct assignment with it; instead use
+ * GET_VXID_FROM_PGPROC().
+ */
+typedef struct
+{
+ BackendId backendId; /* backendId from PGPROC */
+ LocalTransactionId localTransactionId; /* lxid from PGPROC */
+} VirtualTransactionId;
+
+#define InvalidLocalTransactionId 0
+#define LocalTransactionIdIsValid(lxid) ((lxid) != InvalidLocalTransactionId)
+#define VirtualTransactionIdIsValid(vxid) \
+ (LocalTransactionIdIsValid((vxid).localTransactionId))
+#define VirtualTransactionIdIsRecoveredPreparedXact(vxid) \
+ ((vxid).backendId == InvalidBackendId)
+#define VirtualTransactionIdEquals(vxid1, vxid2) \
+ ((vxid1).backendId == (vxid2).backendId && \
+ (vxid1).localTransactionId == (vxid2).localTransactionId)
+#define SetInvalidVirtualTransactionId(vxid) \
+ ((vxid).backendId = InvalidBackendId, \
+ (vxid).localTransactionId = InvalidLocalTransactionId)
+#define GET_VXID_FROM_PGPROC(vxid, proc) \
+ ((vxid).backendId = (proc).backendId, \
+ (vxid).localTransactionId = (proc).lxid)
+
+/* MAX_LOCKMODES cannot be larger than the # of bits in LOCKMASK */
+#define MAX_LOCKMODES 10
+
+#define LOCKBIT_ON(lockmode) (1 << (lockmode))
+#define LOCKBIT_OFF(lockmode) (~(1 << (lockmode)))
+
+
+/*
+ * This data structure defines the locking semantics associated with a
+ * "lock method". The semantics specify the meaning of each lock mode
+ * (by defining which lock modes it conflicts with).
+ * All of this data is constant and is kept in const tables.
+ *
+ * numLockModes -- number of lock modes (READ,WRITE,etc) that
+ * are defined in this lock method. Must be less than MAX_LOCKMODES.
+ *
+ * conflictTab -- this is an array of bitmasks showing lock
+ * mode conflicts. conflictTab[i] is a mask with the j-th bit
+ * turned on if lock modes i and j conflict. Lock modes are
+ * numbered 1..numLockModes; conflictTab[0] is unused.
+ *
+ * lockModeNames -- ID strings for debug printouts.
+ *
+ * trace_flag -- pointer to GUC trace flag for this lock method. (The
+ * GUC variable is not constant, but we use "const" here to denote that
+ * it can't be changed through this reference.)
+ */
+typedef struct LockMethodData
+{
+ int numLockModes;
+ const LOCKMASK *conflictTab;
+ const char *const *lockModeNames;
+ const bool *trace_flag;
+} LockMethodData;
+
+typedef const LockMethodData *LockMethod;
+
+/*
+ * Lock methods are identified by LOCKMETHODID. (Despite the declaration as
+ * uint16, we are constrained to 256 lockmethods by the layout of LOCKTAG.)
+ */
+typedef uint16 LOCKMETHODID;
+
+/* These identify the known lock methods */
+#define DEFAULT_LOCKMETHOD 1
+#define USER_LOCKMETHOD 2
+
+/*
+ * LOCKTAG is the key information needed to look up a LOCK item in the
+ * lock hashtable. A LOCKTAG value uniquely identifies a lockable object.
+ *
+ * The LockTagType enum defines the different kinds of objects we can lock.
+ * We can handle up to 256 different LockTagTypes.
+ */
+typedef enum LockTagType
+{
+ LOCKTAG_RELATION, /* whole relation */
+ LOCKTAG_RELATION_EXTEND, /* the right to extend a relation */
+ LOCKTAG_DATABASE_FROZEN_IDS, /* pg_database.datfrozenxid */
+ LOCKTAG_PAGE, /* one page of a relation */
+ LOCKTAG_TUPLE, /* one physical tuple */
+ LOCKTAG_TRANSACTION, /* transaction (for waiting for xact done) */
+ LOCKTAG_VIRTUALTRANSACTION, /* virtual transaction (ditto) */
+ LOCKTAG_SPECULATIVE_TOKEN, /* speculative insertion Xid and token */
+ LOCKTAG_OBJECT, /* non-relation database object */
+ LOCKTAG_USERLOCK, /* reserved for old contrib/userlock code */
+ LOCKTAG_ADVISORY, /* advisory user locks */
+ LOCKTAG_APPLY_TRANSACTION /* transaction being applied on a logical
+ * replication subscriber */
+} LockTagType;
+
+#define LOCKTAG_LAST_TYPE LOCKTAG_APPLY_TRANSACTION
+
+extern PGDLLIMPORT const char *const LockTagTypeNames[];
+
+/*
+ * The LOCKTAG struct is defined with malice aforethought to fit into 16
+ * bytes with no padding. Note that this would need adjustment if we were
+ * to widen Oid, BlockNumber, or TransactionId to more than 32 bits.
+ *
+ * We include lockmethodid in the locktag so that a single hash table in
+ * shared memory can store locks of different lockmethods.
+ */
+typedef struct LOCKTAG
+{
+ uint32 locktag_field1; /* a 32-bit ID field */
+ uint32 locktag_field2; /* a 32-bit ID field */
+ uint32 locktag_field3; /* a 32-bit ID field */
+ uint16 locktag_field4; /* a 16-bit ID field */
+ uint8 locktag_type; /* see enum LockTagType */
+ uint8 locktag_lockmethodid; /* lockmethod indicator */
+} LOCKTAG;
+
+/*
+ * These macros define how we map logical IDs of lockable objects into
+ * the physical fields of LOCKTAG. Use these to set up LOCKTAG values,
+ * rather than accessing the fields directly. Note multiple eval of target!
+ */
+
+/* ID info for a relation is DB OID + REL OID; DB OID = 0 if shared */
+#define SET_LOCKTAG_RELATION(locktag,dboid,reloid) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = 0, \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_RELATION, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/* same ID info as RELATION */
+#define SET_LOCKTAG_RELATION_EXTEND(locktag,dboid,reloid) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = 0, \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_RELATION_EXTEND, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/* ID info for frozen IDs is DB OID */
+#define SET_LOCKTAG_DATABASE_FROZEN_IDS(locktag,dboid) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = 0, \
+ (locktag).locktag_field3 = 0, \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_DATABASE_FROZEN_IDS, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/* ID info for a page is RELATION info + BlockNumber */
+#define SET_LOCKTAG_PAGE(locktag,dboid,reloid,blocknum) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = (blocknum), \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_PAGE, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/* ID info for a tuple is PAGE info + OffsetNumber */
+#define SET_LOCKTAG_TUPLE(locktag,dboid,reloid,blocknum,offnum) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = (blocknum), \
+ (locktag).locktag_field4 = (offnum), \
+ (locktag).locktag_type = LOCKTAG_TUPLE, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/* ID info for a transaction is its TransactionId */
+#define SET_LOCKTAG_TRANSACTION(locktag,xid) \
+ ((locktag).locktag_field1 = (xid), \
+ (locktag).locktag_field2 = 0, \
+ (locktag).locktag_field3 = 0, \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_TRANSACTION, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/* ID info for a virtual transaction is its VirtualTransactionId */
+#define SET_LOCKTAG_VIRTUALTRANSACTION(locktag,vxid) \
+ ((locktag).locktag_field1 = (vxid).backendId, \
+ (locktag).locktag_field2 = (vxid).localTransactionId, \
+ (locktag).locktag_field3 = 0, \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_VIRTUALTRANSACTION, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/*
+ * ID info for a speculative insert is TRANSACTION info +
+ * its speculative insert counter.
+ */
+#define SET_LOCKTAG_SPECULATIVE_INSERTION(locktag,xid,token) \
+ ((locktag).locktag_field1 = (xid), \
+ (locktag).locktag_field2 = (token), \
+ (locktag).locktag_field3 = 0, \
+ (locktag).locktag_field4 = 0, \
+ (locktag).locktag_type = LOCKTAG_SPECULATIVE_TOKEN, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/*
+ * ID info for an object is DB OID + CLASS OID + OBJECT OID + SUBID
+ *
+ * Note: object ID has same representation as in pg_depend and
+ * pg_description, but notice that we are constraining SUBID to 16 bits.
+ * Also, we use DB OID = 0 for shared objects such as tablespaces.
+ */
+#define SET_LOCKTAG_OBJECT(locktag,dboid,classoid,objoid,objsubid) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (classoid), \
+ (locktag).locktag_field3 = (objoid), \
+ (locktag).locktag_field4 = (objsubid), \
+ (locktag).locktag_type = LOCKTAG_OBJECT, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+#define SET_LOCKTAG_ADVISORY(locktag,id1,id2,id3,id4) \
+ ((locktag).locktag_field1 = (id1), \
+ (locktag).locktag_field2 = (id2), \
+ (locktag).locktag_field3 = (id3), \
+ (locktag).locktag_field4 = (id4), \
+ (locktag).locktag_type = LOCKTAG_ADVISORY, \
+ (locktag).locktag_lockmethodid = USER_LOCKMETHOD)
+
+/*
+ * ID info for a remote transaction on a logical replication subscriber is: DB
+ * OID + SUBSCRIPTION OID + TRANSACTION ID + OBJID
+ */
+#define SET_LOCKTAG_APPLY_TRANSACTION(locktag,dboid,suboid,xid,objid) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (suboid), \
+ (locktag).locktag_field3 = (xid), \
+ (locktag).locktag_field4 = (objid), \
+ (locktag).locktag_type = LOCKTAG_APPLY_TRANSACTION, \
+ (locktag).locktag_lockmethodid = DEFAULT_LOCKMETHOD)
+
+/*
+ * Per-locked-object lock information:
+ *
+ * tag -- uniquely identifies the object being locked
+ * grantMask -- bitmask for all lock types currently granted on this object.
+ * waitMask -- bitmask for all lock types currently awaited on this object.
+ * procLocks -- list of PROCLOCK objects for this lock.
+ * waitProcs -- queue of processes waiting for this lock.
+ * requested -- count of each lock type currently requested on the lock
+ * (includes requests already granted!!).
+ * nRequested -- total requested locks of all types.
+ * granted -- count of each lock type currently granted on the lock.
+ * nGranted -- total granted locks of all types.
+ *
+ * Note: these counts count 1 for each backend. Internally to a backend,
+ * there may be multiple grabs on a particular lock, but this is not reflected
+ * into shared memory.
+ */
+typedef struct LOCK
+{
+ /* hash key */
+ LOCKTAG tag; /* unique identifier of lockable object */
+
+ /* data */
+ LOCKMASK grantMask; /* bitmask for lock types already granted */
+ LOCKMASK waitMask; /* bitmask for lock types awaited */
+ dlist_head procLocks; /* list of PROCLOCK objects assoc. with lock */
+ dclist_head waitProcs; /* list of PGPROC objects waiting on lock */
+ int requested[MAX_LOCKMODES]; /* counts of requested locks */
+ int nRequested; /* total of requested[] array */
+ int granted[MAX_LOCKMODES]; /* counts of granted locks */
+ int nGranted; /* total of granted[] array */
+} LOCK;
+
+#define LOCK_LOCKMETHOD(lock) ((LOCKMETHODID) (lock).tag.locktag_lockmethodid)
+#define LOCK_LOCKTAG(lock) ((LockTagType) (lock).tag.locktag_type)
+
+
+/*
+ * We may have several different backends holding or awaiting locks
+ * on the same lockable object. We need to store some per-holder/waiter
+ * information for each such holder (or would-be holder). This is kept in
+ * a PROCLOCK struct.
+ *
+ * PROCLOCKTAG is the key information needed to look up a PROCLOCK item in the
+ * proclock hashtable. A PROCLOCKTAG value uniquely identifies the combination
+ * of a lockable object and a holder/waiter for that object. (We can use
+ * pointers here because the PROCLOCKTAG need only be unique for the lifespan
+ * of the PROCLOCK, and it will never outlive the lock or the proc.)
+ *
+ * Internally to a backend, it is possible for the same lock to be held
+ * for different purposes: the backend tracks transaction locks separately
+ * from session locks. However, this is not reflected in the shared-memory
+ * state: we only track which backend(s) hold the lock. This is OK since a
+ * backend can never block itself.
+ *
+ * The holdMask field shows the already-granted locks represented by this
+ * proclock. Note that there will be a proclock object, possibly with
+ * zero holdMask, for any lock that the process is currently waiting on.
+ * Otherwise, proclock objects whose holdMasks are zero are recycled
+ * as soon as convenient.
+ *
+ * releaseMask is workspace for LockReleaseAll(): it shows the locks due
+ * to be released during the current call. This must only be examined or
+ * set by the backend owning the PROCLOCK.
+ *
+ * Each PROCLOCK object is linked into lists for both the associated LOCK
+ * object and the owning PGPROC object. Note that the PROCLOCK is entered
+ * into these lists as soon as it is created, even if no lock has yet been
+ * granted. A PGPROC that is waiting for a lock to be granted will also be
+ * linked into the lock's waitProcs queue.
+ */
+typedef struct PROCLOCKTAG
+{
+ /* NB: we assume this struct contains no padding! */
+ LOCK *myLock; /* link to per-lockable-object information */
+ PGPROC *myProc; /* link to PGPROC of owning backend */
+} PROCLOCKTAG;
+
+typedef struct PROCLOCK
+{
+ /* tag */
+ PROCLOCKTAG tag; /* unique identifier of proclock object */
+
+ /* data */
+ PGPROC *groupLeader; /* proc's lock group leader, or proc itself */
+ LOCKMASK holdMask; /* bitmask for lock types currently held */
+ LOCKMASK releaseMask; /* bitmask for lock types to be released */
+ dlist_node lockLink; /* list link in LOCK's list of proclocks */
+ dlist_node procLink; /* list link in PGPROC's list of proclocks */
+} PROCLOCK;
+
+#define PROCLOCK_LOCKMETHOD(proclock) \
+ LOCK_LOCKMETHOD(*((proclock).tag.myLock))
+
+/*
+ * Each backend also maintains a local hash table with information about each
+ * lock it is currently interested in. In particular the local table counts
+ * the number of times that lock has been acquired. This allows multiple
+ * requests for the same lock to be executed without additional accesses to
+ * shared memory. We also track the number of lock acquisitions per
+ * ResourceOwner, so that we can release just those locks belonging to a
+ * particular ResourceOwner.
+ *
+ * When holding a lock taken "normally", the lock and proclock fields always
+ * point to the associated objects in shared memory. However, if we acquired
+ * the lock via the fast-path mechanism, the lock and proclock fields are set
+ * to NULL, since there probably aren't any such objects in shared memory.
+ * (If the lock later gets promoted to normal representation, we may eventually
+ * update our locallock's lock/proclock fields after finding the shared
+ * objects.)
+ *
+ * Caution: a locallock object can be left over from a failed lock acquisition
+ * attempt. In this case its lock/proclock fields are untrustworthy, since
+ * the shared lock object is neither held nor awaited, and hence is available
+ * to be reclaimed. If nLocks > 0 then these pointers must either be valid or
+ * NULL, but when nLocks == 0 they should be considered garbage.
+ */
+typedef struct LOCALLOCKTAG
+{
+ LOCKTAG lock; /* identifies the lockable object */
+ LOCKMODE mode; /* lock mode for this table entry */
+} LOCALLOCKTAG;
+
+typedef struct LOCALLOCKOWNER
+{
+ /*
+ * Note: if owner is NULL then the lock is held on behalf of the session;
+ * otherwise it is held on behalf of my current transaction.
+ *
+ * Must use a forward struct reference to avoid circularity.
+ */
+ struct ResourceOwnerData *owner;
+ int64 nLocks; /* # of times held by this owner */
+} LOCALLOCKOWNER;
+
+typedef struct LOCALLOCK
+{
+ /* tag */
+ LOCALLOCKTAG tag; /* unique identifier of locallock entry */
+
+ /* data */
+ uint32 hashcode; /* copy of LOCKTAG's hash value */
+ LOCK *lock; /* associated LOCK object, if any */
+ PROCLOCK *proclock; /* associated PROCLOCK object, if any */
+ int64 nLocks; /* total number of times lock is held */
+ int numLockOwners; /* # of relevant ResourceOwners */
+ int maxLockOwners; /* allocated size of array */
+ LOCALLOCKOWNER *lockOwners; /* dynamically resizable array */
+ bool holdsStrongLockCount; /* bumped FastPathStrongRelationLocks */
+ bool lockCleared; /* we read all sinval msgs for lock */
+} LOCALLOCK;
+
+#define LOCALLOCK_LOCKMETHOD(llock) ((llock).tag.lock.locktag_lockmethodid)
+#define LOCALLOCK_LOCKTAG(llock) ((LockTagType) (llock).tag.lock.locktag_type)
+
+
+/*
+ * These structures hold information passed from lmgr internals to the lock
+ * listing user-level functions (in lockfuncs.c).
+ */
+
+typedef struct LockInstanceData
+{
+ LOCKTAG locktag; /* tag for locked object */
+ LOCKMASK holdMask; /* locks held by this PGPROC */
+ LOCKMODE waitLockMode; /* lock awaited by this PGPROC, if any */
+ BackendId backend; /* backend ID of this PGPROC */
+ LocalTransactionId lxid; /* local transaction ID of this PGPROC */
+ TimestampTz waitStart; /* time at which this PGPROC started waiting
+ * for lock */
+ int pid; /* pid of this PGPROC */
+ int leaderPid; /* pid of group leader; = pid if no group */
+ bool fastpath; /* taken via fastpath? */
+} LockInstanceData;
+
+typedef struct LockData
+{
+ int nelements; /* The length of the array */
+ LockInstanceData *locks; /* Array of per-PROCLOCK information */
+} LockData;
+
+typedef struct BlockedProcData
+{
+ int pid; /* pid of a blocked PGPROC */
+ /* Per-PROCLOCK information about PROCLOCKs of the lock the pid awaits */
+ /* (these fields refer to indexes in BlockedProcsData.locks[]) */
+ int first_lock; /* index of first relevant LockInstanceData */
+ int num_locks; /* number of relevant LockInstanceDatas */
+ /* PIDs of PGPROCs that are ahead of "pid" in the lock's wait queue */
+ /* (these fields refer to indexes in BlockedProcsData.waiter_pids[]) */
+ int first_waiter; /* index of first preceding waiter */
+ int num_waiters; /* number of preceding waiters */
+} BlockedProcData;
+
+typedef struct BlockedProcsData
+{
+ BlockedProcData *procs; /* Array of per-blocked-proc information */
+ LockInstanceData *locks; /* Array of per-PROCLOCK information */
+ int *waiter_pids; /* Array of PIDs of other blocked PGPROCs */
+ int nprocs; /* # of valid entries in procs[] array */
+ int maxprocs; /* Allocated length of procs[] array */
+ int nlocks; /* # of valid entries in locks[] array */
+ int maxlocks; /* Allocated length of locks[] array */
+ int npids; /* # of valid entries in waiter_pids[] array */
+ int maxpids; /* Allocated length of waiter_pids[] array */
+} BlockedProcsData;
+
+
+/* Result codes for LockAcquire() */
+typedef enum
+{
+ LOCKACQUIRE_NOT_AVAIL, /* lock not available, and dontWait=true */
+ LOCKACQUIRE_OK, /* lock successfully acquired */
+ LOCKACQUIRE_ALREADY_HELD, /* incremented count for lock already held */
+ LOCKACQUIRE_ALREADY_CLEAR /* incremented count for lock already clear */
+} LockAcquireResult;
+
+/* Deadlock states identified by DeadLockCheck() */
+typedef enum
+{
+ DS_NOT_YET_CHECKED, /* no deadlock check has run yet */
+ DS_NO_DEADLOCK, /* no deadlock detected */
+ DS_SOFT_DEADLOCK, /* deadlock avoided by queue rearrangement */
+ DS_HARD_DEADLOCK, /* deadlock, no way out but ERROR */
+ DS_BLOCKED_BY_AUTOVACUUM /* no deadlock; queue blocked by autovacuum
+ * worker */
+} DeadLockState;
+
+/*
+ * The lockmgr's shared hash tables are partitioned to reduce contention.
+ * To determine which partition a given locktag belongs to, compute the tag's
+ * hash code with LockTagHashCode(), then apply one of these macros.
+ * NB: NUM_LOCK_PARTITIONS must be a power of 2!
+ */
+#define LockHashPartition(hashcode) \
+ ((hashcode) % NUM_LOCK_PARTITIONS)
+#define LockHashPartitionLock(hashcode) \
+ (&MainLWLockArray[LOCK_MANAGER_LWLOCK_OFFSET + \
+ LockHashPartition(hashcode)].lock)
+#define LockHashPartitionLockByIndex(i) \
+ (&MainLWLockArray[LOCK_MANAGER_LWLOCK_OFFSET + (i)].lock)
+
+/*
+ * The deadlock detector needs to be able to access lockGroupLeader and
+ * related fields in the PGPROC, so we arrange for those fields to be protected
+ * by one of the lock hash partition locks. Since the deadlock detector
+ * acquires all such locks anyway, this makes it safe for it to access these
+ * fields without doing anything extra. To avoid contention as much as
+ * possible, we map different PGPROCs to different partition locks. The lock
+ * used for a given lock group is determined by the group leader's pgprocno.
+ */
+#define LockHashPartitionLockByProc(leader_pgproc) \
+ LockHashPartitionLock((leader_pgproc)->pgprocno)
+
+/*
+ * function prototypes
+ */
+extern void InitLocks(void);
+extern LockMethod GetLocksMethodTable(const LOCK *lock);
+extern LockMethod GetLockTagsMethodTable(const LOCKTAG *locktag);
+extern uint32 LockTagHashCode(const LOCKTAG *locktag);
+extern bool DoLockModesConflict(LOCKMODE mode1, LOCKMODE mode2);
+extern LockAcquireResult LockAcquire(const LOCKTAG *locktag,
+ LOCKMODE lockmode,
+ bool sessionLock,
+ bool dontWait);
+extern LockAcquireResult LockAcquireExtended(const LOCKTAG *locktag,
+ LOCKMODE lockmode,
+ bool sessionLock,
+ bool dontWait,
+ bool reportMemoryError,
+ LOCALLOCK **locallockp);
+extern void AbortStrongLockAcquire(void);
+extern void MarkLockClear(LOCALLOCK *locallock);
+extern bool LockRelease(const LOCKTAG *locktag,
+ LOCKMODE lockmode, bool sessionLock);
+extern void LockReleaseAll(LOCKMETHODID lockmethodid, bool allLocks);
+extern void LockReleaseSession(LOCKMETHODID lockmethodid);
+extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
+extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
+extern bool LockHeldByMe(const LOCKTAG *locktag, LOCKMODE lockmode);
+#ifdef USE_ASSERT_CHECKING
+extern HTAB *GetLockMethodLocalHash(void);
+#endif
+extern bool LockHasWaiters(const LOCKTAG *locktag,
+ LOCKMODE lockmode, bool sessionLock);
+extern VirtualTransactionId *GetLockConflicts(const LOCKTAG *locktag,
+ LOCKMODE lockmode, int *countp);
+extern void AtPrepare_Locks(void);
+extern void PostPrepare_Locks(TransactionId xid);
+extern bool LockCheckConflicts(LockMethod lockMethodTable,
+ LOCKMODE lockmode,
+ LOCK *lock, PROCLOCK *proclock);
+extern void GrantLock(LOCK *lock, PROCLOCK *proclock, LOCKMODE lockmode);
+extern void GrantAwaitedLock(void);
+extern void RemoveFromWaitQueue(PGPROC *proc, uint32 hashcode);
+extern Size LockShmemSize(void);
+extern LockData *GetLockStatusData(void);
+extern BlockedProcsData *GetBlockerStatusData(int blocked_pid);
+
+extern xl_standby_lock *GetRunningTransactionLocks(int *nlocks);
+extern const char *GetLockmodeName(LOCKMETHODID lockmethodid, LOCKMODE mode);
+
+extern void lock_twophase_recover(TransactionId xid, uint16 info,
+ void *recdata, uint32 len);
+extern void lock_twophase_postcommit(TransactionId xid, uint16 info,
+ void *recdata, uint32 len);
+extern void lock_twophase_postabort(TransactionId xid, uint16 info,
+ void *recdata, uint32 len);
+extern void lock_twophase_standby_recover(TransactionId xid, uint16 info,
+ void *recdata, uint32 len);
+
+extern DeadLockState DeadLockCheck(PGPROC *proc);
+extern PGPROC *GetBlockingAutoVacuumPgproc(void);
+extern void DeadLockReport(void) pg_attribute_noreturn();
+extern void RememberSimpleDeadLock(PGPROC *proc1,
+ LOCKMODE lockmode,
+ LOCK *lock,
+ PGPROC *proc2);
+extern void InitDeadLockChecking(void);
+
+extern int LockWaiterCount(const LOCKTAG *locktag);
+
+#ifdef LOCK_DEBUG
+extern void DumpLocks(PGPROC *proc);
+extern void DumpAllLocks(void);
+#endif
+
+/* Lock a VXID (used to wait for a transaction to finish) */
+extern void VirtualXactLockTableInsert(VirtualTransactionId vxid);
+extern void VirtualXactLockTableCleanup(void);
+extern bool VirtualXactLock(VirtualTransactionId vxid, bool wait);
+
+#endif /* LOCK_H_ */
diff --git a/pgsql/include/server/storage/lockdefs.h b/pgsql/include/server/storage/lockdefs.h
new file mode 100644
index 0000000000000000000000000000000000000000..e25216e03658efbf7dff5bd928b48f2e51766040
--- /dev/null
+++ b/pgsql/include/server/storage/lockdefs.h
@@ -0,0 +1,59 @@
+/*-------------------------------------------------------------------------
+ *
+ * lockdefs.h
+ * Frontend exposed parts of postgres' low level lock mechanism
+ *
+ * The split between lockdefs.h and lock.h is not very principled. This file
+ * contains definition that have to (indirectly) be available when included by
+ * FRONTEND code.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/lockdefs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LOCKDEFS_H_
+#define LOCKDEFS_H_
+
+/*
+ * LOCKMODE is an integer (1..N) indicating a lock type. LOCKMASK is a bit
+ * mask indicating a set of held or requested lock types (the bit 1<lwWaitMode,
+ * when waiting for lock to become free. Not
+ * to be used as LWLockAcquire argument */
+} LWLockMode;
+
+
+#ifdef LOCK_DEBUG
+extern PGDLLIMPORT bool Trace_lwlocks;
+#endif
+
+extern bool LWLockAcquire(LWLock *lock, LWLockMode mode);
+extern bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode);
+extern bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode);
+extern void LWLockRelease(LWLock *lock);
+extern void LWLockReleaseClearVar(LWLock *lock, uint64 *valptr, uint64 val);
+extern void LWLockReleaseAll(void);
+extern bool LWLockHeldByMe(LWLock *lock);
+extern bool LWLockAnyHeldByMe(LWLock *lock, int nlocks, size_t stride);
+extern bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode);
+
+extern bool LWLockWaitForVar(LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval);
+extern void LWLockUpdateVar(LWLock *lock, uint64 *valptr, uint64 val);
+
+extern Size LWLockShmemSize(void);
+extern void CreateLWLocks(void);
+extern void InitLWLockAccess(void);
+
+extern const char *GetLWLockIdentifier(uint32 classId, uint16 eventId);
+
+/*
+ * Extensions (or core code) can obtain an LWLocks by calling
+ * RequestNamedLWLockTranche() during postmaster startup. Subsequently,
+ * call GetNamedLWLockTranche() to obtain a pointer to an array containing
+ * the number of LWLocks requested.
+ */
+extern void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks);
+extern LWLockPadded *GetNamedLWLockTranche(const char *tranche_name);
+
+/*
+ * There is another, more flexible method of obtaining lwlocks. First, call
+ * LWLockNewTrancheId just once to obtain a tranche ID; this allocates from
+ * a shared counter. Next, each individual process using the tranche should
+ * call LWLockRegisterTranche() to associate that tranche ID with a name.
+ * Finally, LWLockInitialize should be called just once per lwlock, passing
+ * the tranche ID as an argument.
+ *
+ * It may seem strange that each process using the tranche must register it
+ * separately, but dynamic shared memory segments aren't guaranteed to be
+ * mapped at the same address in all coordinating backends, so storing the
+ * registration in the main shared memory segment wouldn't work for that case.
+ */
+extern int LWLockNewTrancheId(void);
+extern void LWLockRegisterTranche(int tranche_id, const char *tranche_name);
+extern void LWLockInitialize(LWLock *lock, int tranche_id);
+
+/*
+ * Every tranche ID less than NUM_INDIVIDUAL_LWLOCKS is reserved; also,
+ * we reserve additional tranche IDs for builtin tranches not included in
+ * the set of individual LWLocks. A call to LWLockNewTrancheId will never
+ * return a value less than LWTRANCHE_FIRST_USER_DEFINED.
+ */
+typedef enum BuiltinTrancheIds
+{
+ LWTRANCHE_XACT_BUFFER = NUM_INDIVIDUAL_LWLOCKS,
+ LWTRANCHE_COMMITTS_BUFFER,
+ LWTRANCHE_SUBTRANS_BUFFER,
+ LWTRANCHE_MULTIXACTOFFSET_BUFFER,
+ LWTRANCHE_MULTIXACTMEMBER_BUFFER,
+ LWTRANCHE_NOTIFY_BUFFER,
+ LWTRANCHE_SERIAL_BUFFER,
+ LWTRANCHE_WAL_INSERT,
+ LWTRANCHE_BUFFER_CONTENT,
+ LWTRANCHE_REPLICATION_ORIGIN_STATE,
+ LWTRANCHE_REPLICATION_SLOT_IO,
+ LWTRANCHE_LOCK_FASTPATH,
+ LWTRANCHE_BUFFER_MAPPING,
+ LWTRANCHE_LOCK_MANAGER,
+ LWTRANCHE_PREDICATE_LOCK_MANAGER,
+ LWTRANCHE_PARALLEL_HASH_JOIN,
+ LWTRANCHE_PARALLEL_QUERY_DSA,
+ LWTRANCHE_PER_SESSION_DSA,
+ LWTRANCHE_PER_SESSION_RECORD_TYPE,
+ LWTRANCHE_PER_SESSION_RECORD_TYPMOD,
+ LWTRANCHE_SHARED_TUPLESTORE,
+ LWTRANCHE_SHARED_TIDBITMAP,
+ LWTRANCHE_PARALLEL_APPEND,
+ LWTRANCHE_PER_XACT_PREDICATE_LIST,
+ LWTRANCHE_PGSTATS_DSA,
+ LWTRANCHE_PGSTATS_HASH,
+ LWTRANCHE_PGSTATS_DATA,
+ LWTRANCHE_LAUNCHER_DSA,
+ LWTRANCHE_LAUNCHER_HASH,
+ LWTRANCHE_FIRST_USER_DEFINED
+} BuiltinTrancheIds;
+
+/*
+ * Prior to PostgreSQL 9.4, we used an enum type called LWLockId to refer
+ * to LWLocks. New code should instead use LWLock *. However, for the
+ * convenience of third-party code, we include the following typedef.
+ */
+typedef LWLock *LWLockId;
+
+#endif /* LWLOCK_H */
diff --git a/pgsql/include/server/storage/lwlocknames.h b/pgsql/include/server/storage/lwlocknames.h
new file mode 100644
index 0000000000000000000000000000000000000000..c1cb21e1601f4abae6098e1a5a8d993791656aca
--- /dev/null
+++ b/pgsql/include/server/storage/lwlocknames.h
@@ -0,0 +1,50 @@
+/* autogenerated from src/backend/storage/lmgr/lwlocknames.txt, do not edit */
+/* there is deliberately not an #ifndef LWLOCKNAMES_H here */
+
+#define ShmemIndexLock (&MainLWLockArray[1].lock)
+#define OidGenLock (&MainLWLockArray[2].lock)
+#define XidGenLock (&MainLWLockArray[3].lock)
+#define ProcArrayLock (&MainLWLockArray[4].lock)
+#define SInvalReadLock (&MainLWLockArray[5].lock)
+#define SInvalWriteLock (&MainLWLockArray[6].lock)
+#define WALBufMappingLock (&MainLWLockArray[7].lock)
+#define WALWriteLock (&MainLWLockArray[8].lock)
+#define ControlFileLock (&MainLWLockArray[9].lock)
+#define XactSLRULock (&MainLWLockArray[11].lock)
+#define SubtransSLRULock (&MainLWLockArray[12].lock)
+#define MultiXactGenLock (&MainLWLockArray[13].lock)
+#define MultiXactOffsetSLRULock (&MainLWLockArray[14].lock)
+#define MultiXactMemberSLRULock (&MainLWLockArray[15].lock)
+#define RelCacheInitLock (&MainLWLockArray[16].lock)
+#define CheckpointerCommLock (&MainLWLockArray[17].lock)
+#define TwoPhaseStateLock (&MainLWLockArray[18].lock)
+#define TablespaceCreateLock (&MainLWLockArray[19].lock)
+#define BtreeVacuumLock (&MainLWLockArray[20].lock)
+#define AddinShmemInitLock (&MainLWLockArray[21].lock)
+#define AutovacuumLock (&MainLWLockArray[22].lock)
+#define AutovacuumScheduleLock (&MainLWLockArray[23].lock)
+#define SyncScanLock (&MainLWLockArray[24].lock)
+#define RelationMappingLock (&MainLWLockArray[25].lock)
+#define NotifySLRULock (&MainLWLockArray[26].lock)
+#define NotifyQueueLock (&MainLWLockArray[27].lock)
+#define SerializableXactHashLock (&MainLWLockArray[28].lock)
+#define SerializableFinishedListLock (&MainLWLockArray[29].lock)
+#define SerializablePredicateListLock (&MainLWLockArray[30].lock)
+#define SerialSLRULock (&MainLWLockArray[31].lock)
+#define SyncRepLock (&MainLWLockArray[32].lock)
+#define BackgroundWorkerLock (&MainLWLockArray[33].lock)
+#define DynamicSharedMemoryControlLock (&MainLWLockArray[34].lock)
+#define AutoFileLock (&MainLWLockArray[35].lock)
+#define ReplicationSlotAllocationLock (&MainLWLockArray[36].lock)
+#define ReplicationSlotControlLock (&MainLWLockArray[37].lock)
+#define CommitTsSLRULock (&MainLWLockArray[38].lock)
+#define CommitTsLock (&MainLWLockArray[39].lock)
+#define ReplicationOriginLock (&MainLWLockArray[40].lock)
+#define MultiXactTruncationLock (&MainLWLockArray[41].lock)
+#define OldSnapshotTimeMapLock (&MainLWLockArray[42].lock)
+#define LogicalRepWorkerLock (&MainLWLockArray[43].lock)
+#define XactTruncationLock (&MainLWLockArray[44].lock)
+#define WrapLimitsVacuumLock (&MainLWLockArray[46].lock)
+#define NotifyQueueTailLock (&MainLWLockArray[47].lock)
+
+#define NUM_INDIVIDUAL_LWLOCKS 48
diff --git a/pgsql/include/server/storage/md.h b/pgsql/include/server/storage/md.h
new file mode 100644
index 0000000000000000000000000000000000000000..941879ee6a8fda631cea27f07f8a40601fce501f
--- /dev/null
+++ b/pgsql/include/server/storage/md.h
@@ -0,0 +1,54 @@
+/*-------------------------------------------------------------------------
+ *
+ * md.h
+ * magnetic disk storage manager public interface declarations.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/md.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MD_H
+#define MD_H
+
+#include "storage/block.h"
+#include "storage/relfilelocator.h"
+#include "storage/smgr.h"
+#include "storage/sync.h"
+
+/* md storage manager functionality */
+extern void mdinit(void);
+extern void mdopen(SMgrRelation reln);
+extern void mdclose(SMgrRelation reln, ForkNumber forknum);
+extern void mdcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo);
+extern bool mdexists(SMgrRelation reln, ForkNumber forknum);
+extern void mdunlink(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo);
+extern void mdextend(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, const void *buffer, bool skipFsync);
+extern void mdzeroextend(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, int nblocks, bool skipFsync);
+extern bool mdprefetch(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum);
+extern void mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
+ void *buffer);
+extern void mdwrite(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, const void *buffer, bool skipFsync);
+extern void mdwriteback(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, BlockNumber nblocks);
+extern BlockNumber mdnblocks(SMgrRelation reln, ForkNumber forknum);
+extern void mdtruncate(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber nblocks);
+extern void mdimmedsync(SMgrRelation reln, ForkNumber forknum);
+
+extern void ForgetDatabaseSyncRequests(Oid dbid);
+extern void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo);
+
+/* md sync callbacks */
+extern int mdsyncfiletag(const FileTag *ftag, char *path);
+extern int mdunlinkfiletag(const FileTag *ftag, char *path);
+extern bool mdfiletagmatches(const FileTag *ftag, const FileTag *candidate);
+
+#endif /* MD_H */
diff --git a/pgsql/include/server/storage/off.h b/pgsql/include/server/storage/off.h
new file mode 100644
index 0000000000000000000000000000000000000000..3540308069aef93da50e1e50bc3b8f96af4ce0f8
--- /dev/null
+++ b/pgsql/include/server/storage/off.h
@@ -0,0 +1,57 @@
+/*-------------------------------------------------------------------------
+ *
+ * off.h
+ * POSTGRES disk "offset" definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/off.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef OFF_H
+#define OFF_H
+
+#include "storage/itemid.h"
+/*
+ * OffsetNumber:
+ *
+ * this is a 1-based index into the linp (ItemIdData) array in the
+ * header of each disk page.
+ */
+typedef uint16 OffsetNumber;
+
+#define InvalidOffsetNumber ((OffsetNumber) 0)
+#define FirstOffsetNumber ((OffsetNumber) 1)
+#define MaxOffsetNumber ((OffsetNumber) (BLCKSZ / sizeof(ItemIdData)))
+
+/* ----------------
+ * support macros
+ * ----------------
+ */
+
+/*
+ * OffsetNumberIsValid
+ * True iff the offset number is valid.
+ */
+#define OffsetNumberIsValid(offsetNumber) \
+ ((bool) ((offsetNumber != InvalidOffsetNumber) && \
+ (offsetNumber <= MaxOffsetNumber)))
+
+/*
+ * OffsetNumberNext
+ * OffsetNumberPrev
+ * Increments/decrements the argument. These macros look pointless
+ * but they help us disambiguate the different manipulations on
+ * OffsetNumbers (e.g., sometimes we subtract one from an
+ * OffsetNumber to move back, and sometimes we do so to form a
+ * real C array index).
+ */
+#define OffsetNumberNext(offsetNumber) \
+ ((OffsetNumber) (1 + (offsetNumber)))
+#define OffsetNumberPrev(offsetNumber) \
+ ((OffsetNumber) (-1 + (offsetNumber)))
+
+#endif /* OFF_H */
diff --git a/pgsql/include/server/storage/pg_sema.h b/pgsql/include/server/storage/pg_sema.h
new file mode 100644
index 0000000000000000000000000000000000000000..3bf03420741a80e4f529fe3133d8e2dc78fde68e
--- /dev/null
+++ b/pgsql/include/server/storage/pg_sema.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_sema.h
+ * Platform-independent API for semaphores.
+ *
+ * PostgreSQL requires counting semaphores (the kind that keep track of
+ * multiple unlock operations, and will allow an equal number of subsequent
+ * lock operations before blocking). The underlying implementation is
+ * not the same on every platform. This file defines the API that must
+ * be provided by each port.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/pg_sema.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_SEMA_H
+#define PG_SEMA_H
+
+/*
+ * struct PGSemaphoreData and pointer type PGSemaphore are the data structure
+ * representing an individual semaphore. The contents of PGSemaphoreData vary
+ * across implementations and must never be touched by platform-independent
+ * code; hence, PGSemaphoreData is declared as an opaque struct here.
+ *
+ * However, Windows is sufficiently unlike our other ports that it doesn't
+ * seem worth insisting on ABI compatibility for Windows too. Hence, on
+ * that platform just define PGSemaphore as HANDLE.
+ */
+#ifndef USE_WIN32_SEMAPHORES
+typedef struct PGSemaphoreData *PGSemaphore;
+#else
+typedef HANDLE PGSemaphore;
+#endif
+
+
+/* Report amount of shared memory needed */
+extern Size PGSemaphoreShmemSize(int maxSemas);
+
+/* Module initialization (called during postmaster start or shmem reinit) */
+extern void PGReserveSemaphores(int maxSemas);
+
+/* Allocate a PGSemaphore structure with initial count 1 */
+extern PGSemaphore PGSemaphoreCreate(void);
+
+/* Reset a previously-initialized PGSemaphore to have count 0 */
+extern void PGSemaphoreReset(PGSemaphore sema);
+
+/* Lock a semaphore (decrement count), blocking if count would be < 0 */
+extern void PGSemaphoreLock(PGSemaphore sema);
+
+/* Unlock a semaphore (increment count) */
+extern void PGSemaphoreUnlock(PGSemaphore sema);
+
+/* Lock a semaphore only if able to do so without blocking */
+extern bool PGSemaphoreTryLock(PGSemaphore sema);
+
+#endif /* PG_SEMA_H */
diff --git a/pgsql/include/server/storage/pg_shmem.h b/pgsql/include/server/storage/pg_shmem.h
new file mode 100644
index 0000000000000000000000000000000000000000..4dd05f156d54712087f0cd0870e437e0ed694310
--- /dev/null
+++ b/pgsql/include/server/storage/pg_shmem.h
@@ -0,0 +1,92 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_shmem.h
+ * Platform-independent API for shared memory support.
+ *
+ * Every port is expected to support shared memory with approximately
+ * SysV-ish semantics; in particular, a memory block is not anonymous
+ * but has an ID, and we must be able to tell whether there are any
+ * remaining processes attached to a block of a specified ID.
+ *
+ * To simplify life for the SysV implementation, the ID is assumed to
+ * consist of two unsigned long values (these are key and ID in SysV
+ * terms). Other platforms may ignore the second value if they need
+ * only one ID number.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/pg_shmem.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_SHMEM_H
+#define PG_SHMEM_H
+
+#include "storage/dsm_impl.h"
+
+typedef struct PGShmemHeader /* standard header for all Postgres shmem */
+{
+ int32 magic; /* magic # to identify Postgres segments */
+#define PGShmemMagic 679834894
+ pid_t creatorPID; /* PID of creating process (set but unread) */
+ Size totalsize; /* total size of segment */
+ Size freeoffset; /* offset to first free space */
+ dsm_handle dsm_control; /* ID of dynamic shared memory control seg */
+ void *index; /* pointer to ShmemIndex table */
+#ifndef WIN32 /* Windows doesn't have useful inode#s */
+ dev_t device; /* device data directory is on */
+ ino_t inode; /* inode number of data directory */
+#endif
+} PGShmemHeader;
+
+/* GUC variables */
+extern PGDLLIMPORT int shared_memory_type;
+extern PGDLLIMPORT int huge_pages;
+extern PGDLLIMPORT int huge_page_size;
+
+/* Possible values for huge_pages */
+typedef enum
+{
+ HUGE_PAGES_OFF,
+ HUGE_PAGES_ON,
+ HUGE_PAGES_TRY
+} HugePagesType;
+
+/* Possible values for shared_memory_type */
+typedef enum
+{
+ SHMEM_TYPE_WINDOWS,
+ SHMEM_TYPE_SYSV,
+ SHMEM_TYPE_MMAP
+} PGShmemType;
+
+#ifndef WIN32
+extern PGDLLIMPORT unsigned long UsedShmemSegID;
+#else
+extern PGDLLIMPORT HANDLE UsedShmemSegID;
+extern PGDLLIMPORT void *ShmemProtectiveRegion;
+#endif
+extern PGDLLIMPORT void *UsedShmemSegAddr;
+
+#if !defined(WIN32) && !defined(EXEC_BACKEND)
+#define DEFAULT_SHARED_MEMORY_TYPE SHMEM_TYPE_MMAP
+#elif !defined(WIN32)
+#define DEFAULT_SHARED_MEMORY_TYPE SHMEM_TYPE_SYSV
+#else
+#define DEFAULT_SHARED_MEMORY_TYPE SHMEM_TYPE_WINDOWS
+#endif
+
+#ifdef EXEC_BACKEND
+extern void PGSharedMemoryReAttach(void);
+extern void PGSharedMemoryNoReAttach(void);
+#endif
+
+extern PGShmemHeader *PGSharedMemoryCreate(Size size,
+ PGShmemHeader **shim);
+extern bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2);
+extern void PGSharedMemoryDetach(void);
+extern void GetHugePageSize(Size *hugepagesize, int *mmap_flags);
+
+#endif /* PG_SHMEM_H */
diff --git a/pgsql/include/server/storage/pmsignal.h b/pgsql/include/server/storage/pmsignal.h
new file mode 100644
index 0000000000000000000000000000000000000000..92dc764667142d782ae46759740e46555e40ea56
--- /dev/null
+++ b/pgsql/include/server/storage/pmsignal.h
@@ -0,0 +1,105 @@
+/*-------------------------------------------------------------------------
+ *
+ * pmsignal.h
+ * routines for signaling between the postmaster and its child processes
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/pmsignal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PMSIGNAL_H
+#define PMSIGNAL_H
+
+#include
+
+#ifdef HAVE_SYS_PRCTL_H
+#include "sys/prctl.h"
+#endif
+
+#ifdef HAVE_SYS_PROCCTL_H
+#include "sys/procctl.h"
+#endif
+
+/*
+ * Reasons for signaling the postmaster. We can cope with simultaneous
+ * signals for different reasons. If the same reason is signaled multiple
+ * times in quick succession, however, the postmaster is likely to observe
+ * only one notification of it. This is okay for the present uses.
+ */
+typedef enum
+{
+ PMSIGNAL_RECOVERY_STARTED, /* recovery has started */
+ PMSIGNAL_BEGIN_HOT_STANDBY, /* begin Hot Standby */
+ PMSIGNAL_ROTATE_LOGFILE, /* send SIGUSR1 to syslogger to rotate logfile */
+ PMSIGNAL_START_AUTOVAC_LAUNCHER, /* start an autovacuum launcher */
+ PMSIGNAL_START_AUTOVAC_WORKER, /* start an autovacuum worker */
+ PMSIGNAL_BACKGROUND_WORKER_CHANGE, /* background worker state change */
+ PMSIGNAL_START_WALRECEIVER, /* start a walreceiver */
+ PMSIGNAL_ADVANCE_STATE_MACHINE, /* advance postmaster's state machine */
+
+ NUM_PMSIGNALS /* Must be last value of enum! */
+} PMSignalReason;
+
+/*
+ * Reasons why the postmaster would send SIGQUIT to its children.
+ */
+typedef enum
+{
+ PMQUIT_NOT_SENT = 0, /* postmaster hasn't sent SIGQUIT */
+ PMQUIT_FOR_CRASH, /* some other backend bought the farm */
+ PMQUIT_FOR_STOP /* immediate stop was commanded */
+} QuitSignalReason;
+
+/* PMSignalData is an opaque struct, details known only within pmsignal.c */
+typedef struct PMSignalData PMSignalData;
+
+/*
+ * prototypes for functions in pmsignal.c
+ */
+extern Size PMSignalShmemSize(void);
+extern void PMSignalShmemInit(void);
+extern void SendPostmasterSignal(PMSignalReason reason);
+extern bool CheckPostmasterSignal(PMSignalReason reason);
+extern void SetQuitSignalReason(QuitSignalReason reason);
+extern QuitSignalReason GetQuitSignalReason(void);
+extern int AssignPostmasterChildSlot(void);
+extern bool ReleasePostmasterChildSlot(int slot);
+extern bool IsPostmasterChildWalSender(int slot);
+extern void MarkPostmasterChildActive(void);
+extern void MarkPostmasterChildInactive(void);
+extern void MarkPostmasterChildWalSender(void);
+extern bool PostmasterIsAliveInternal(void);
+extern void PostmasterDeathSignalInit(void);
+
+
+/*
+ * Do we have a way to ask for a signal on parent death?
+ *
+ * If we do, pmsignal.c will set up a signal handler, that sets a flag when
+ * the parent dies. Checking the flag first makes PostmasterIsAlive() a lot
+ * cheaper in usual case that the postmaster is alive.
+ */
+#if (defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_PDEATHSIG)) || \
+ (defined(HAVE_SYS_PROCCTL_H) && defined(PROC_PDEATHSIG_CTL))
+#define USE_POSTMASTER_DEATH_SIGNAL
+#endif
+
+#ifdef USE_POSTMASTER_DEATH_SIGNAL
+extern PGDLLIMPORT volatile sig_atomic_t postmaster_possibly_dead;
+
+static inline bool
+PostmasterIsAlive(void)
+{
+ if (likely(!postmaster_possibly_dead))
+ return true;
+ return PostmasterIsAliveInternal();
+}
+#else
+#define PostmasterIsAlive() PostmasterIsAliveInternal()
+#endif
+
+#endif /* PMSIGNAL_H */
diff --git a/pgsql/include/server/storage/predicate.h b/pgsql/include/server/storage/predicate.h
new file mode 100644
index 0000000000000000000000000000000000000000..cd48afa17b2670a00beb4242665d9e6f5750f6ac
--- /dev/null
+++ b/pgsql/include/server/storage/predicate.h
@@ -0,0 +1,87 @@
+/*-------------------------------------------------------------------------
+ *
+ * predicate.h
+ * POSTGRES public predicate locking definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/predicate.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PREDICATE_H
+#define PREDICATE_H
+
+#include "storage/lock.h"
+#include "utils/relcache.h"
+#include "utils/snapshot.h"
+
+
+/*
+ * GUC variables
+ */
+extern PGDLLIMPORT int max_predicate_locks_per_xact;
+extern PGDLLIMPORT int max_predicate_locks_per_relation;
+extern PGDLLIMPORT int max_predicate_locks_per_page;
+
+
+/* Number of SLRU buffers to use for Serial SLRU */
+#define NUM_SERIAL_BUFFERS 16
+
+/*
+ * A handle used for sharing SERIALIZABLEXACT objects between the participants
+ * in a parallel query.
+ */
+typedef void *SerializableXactHandle;
+
+/*
+ * function prototypes
+ */
+
+/* housekeeping for shared memory predicate lock structures */
+extern void InitPredicateLocks(void);
+extern Size PredicateLockShmemSize(void);
+
+extern void CheckPointPredicate(void);
+
+/* predicate lock reporting */
+extern bool PageIsPredicateLocked(Relation relation, BlockNumber blkno);
+
+/* predicate lock maintenance */
+extern Snapshot GetSerializableTransactionSnapshot(Snapshot snapshot);
+extern void SetSerializableTransactionSnapshot(Snapshot snapshot,
+ VirtualTransactionId *sourcevxid,
+ int sourcepid);
+extern void RegisterPredicateLockingXid(TransactionId xid);
+extern void PredicateLockRelation(Relation relation, Snapshot snapshot);
+extern void PredicateLockPage(Relation relation, BlockNumber blkno, Snapshot snapshot);
+extern void PredicateLockTID(Relation relation, ItemPointer tid, Snapshot snapshot,
+ TransactionId tuple_xid);
+extern void PredicateLockPageSplit(Relation relation, BlockNumber oldblkno, BlockNumber newblkno);
+extern void PredicateLockPageCombine(Relation relation, BlockNumber oldblkno, BlockNumber newblkno);
+extern void TransferPredicateLocksToHeapRelation(Relation relation);
+extern void ReleasePredicateLocks(bool isCommit, bool isReadOnlySafe);
+
+/* conflict detection (may also trigger rollback) */
+extern bool CheckForSerializableConflictOutNeeded(Relation relation, Snapshot snapshot);
+extern void CheckForSerializableConflictOut(Relation relation, TransactionId xid, Snapshot snapshot);
+extern void CheckForSerializableConflictIn(Relation relation, ItemPointer tid, BlockNumber blkno);
+extern void CheckTableForSerializableConflictIn(Relation relation);
+
+/* final rollback checking */
+extern void PreCommit_CheckForSerializationFailure(void);
+
+/* two-phase commit support */
+extern void AtPrepare_PredicateLocks(void);
+extern void PostPrepare_PredicateLocks(TransactionId xid);
+extern void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit);
+extern void predicatelock_twophase_recover(TransactionId xid, uint16 info,
+ void *recdata, uint32 len);
+
+/* parallel query support */
+extern SerializableXactHandle ShareSerializableXact(void);
+extern void AttachSerializableXact(SerializableXactHandle handle);
+
+#endif /* PREDICATE_H */
diff --git a/pgsql/include/server/storage/predicate_internals.h b/pgsql/include/server/storage/predicate_internals.h
new file mode 100644
index 0000000000000000000000000000000000000000..93f84500bf0c825cb357d646450e6028741680db
--- /dev/null
+++ b/pgsql/include/server/storage/predicate_internals.h
@@ -0,0 +1,478 @@
+/*-------------------------------------------------------------------------
+ *
+ * predicate_internals.h
+ * POSTGRES internal predicate locking definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/predicate_internals.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PREDICATE_INTERNALS_H
+#define PREDICATE_INTERNALS_H
+
+#include "lib/ilist.h"
+#include "storage/lock.h"
+#include "storage/lwlock.h"
+
+/*
+ * Commit number.
+ */
+typedef uint64 SerCommitSeqNo;
+
+/*
+ * Reserved commit sequence numbers:
+ * - 0 is reserved to indicate a non-existent SLRU entry; it cannot be
+ * used as a SerCommitSeqNo, even an invalid one
+ * - InvalidSerCommitSeqNo is used to indicate a transaction that
+ * hasn't committed yet, so use a number greater than all valid
+ * ones to make comparison do the expected thing
+ * - RecoverySerCommitSeqNo is used to refer to transactions that
+ * happened before a crash/recovery, since we restart the sequence
+ * at that point. It's earlier than all normal sequence numbers,
+ * and is only used by recovered prepared transactions
+ */
+#define InvalidSerCommitSeqNo ((SerCommitSeqNo) PG_UINT64_MAX)
+#define RecoverySerCommitSeqNo ((SerCommitSeqNo) 1)
+#define FirstNormalSerCommitSeqNo ((SerCommitSeqNo) 2)
+
+/*
+ * The SERIALIZABLEXACT struct contains information needed for each
+ * serializable database transaction to support SSI techniques.
+ *
+ * A home-grown list is maintained in shared memory to manage these.
+ * An entry is used when the serializable transaction acquires a snapshot.
+ * Unless the transaction is rolled back, this entry must generally remain
+ * until all concurrent transactions have completed. (There are special
+ * optimizations for READ ONLY transactions which often allow them to be
+ * cleaned up earlier.) A transaction which is rolled back is cleaned up
+ * as soon as possible.
+ *
+ * Eligibility for cleanup of committed transactions is generally determined
+ * by comparing the transaction's finishedBefore field to
+ * SxactGlobalXmin.
+ */
+typedef struct SERIALIZABLEXACT
+{
+ VirtualTransactionId vxid; /* The executing process always has one of
+ * these. */
+
+ /*
+ * We use two numbers to track the order that transactions commit. Before
+ * commit, a transaction is marked as prepared, and prepareSeqNo is set.
+ * Shortly after commit, it's marked as committed, and commitSeqNo is set.
+ * This doesn't give a strict commit order, but these two values together
+ * are good enough for us, as we can always err on the safe side and
+ * assume that there's a conflict, if we can't be sure of the exact
+ * ordering of two commits.
+ *
+ * Note that a transaction is marked as prepared for a short period during
+ * commit processing, even if two-phase commit is not used. But with
+ * two-phase commit, a transaction can stay in prepared state for some
+ * time.
+ */
+ SerCommitSeqNo prepareSeqNo;
+ SerCommitSeqNo commitSeqNo;
+
+ /* these values are not both interesting at the same time */
+ union
+ {
+ SerCommitSeqNo earliestOutConflictCommit; /* when committed with
+ * conflict out */
+ SerCommitSeqNo lastCommitBeforeSnapshot; /* when not committed or
+ * no conflict out */
+ } SeqNo;
+ dlist_head outConflicts; /* list of write transactions whose data we
+ * couldn't read. */
+ dlist_head inConflicts; /* list of read transactions which couldn't
+ * see our write. */
+ dlist_head predicateLocks; /* list of associated PREDICATELOCK objects */
+ dlist_node finishedLink; /* list link in
+ * FinishedSerializableTransactions */
+ dlist_node xactLink; /* PredXact->activeList/availableList */
+
+ /*
+ * perXactPredicateListLock is only used in parallel queries: it protects
+ * this SERIALIZABLEXACT's predicate lock list against other workers of
+ * the same session.
+ */
+ LWLock perXactPredicateListLock;
+
+ /*
+ * for r/o transactions: list of concurrent r/w transactions that we could
+ * potentially have conflicts with, and vice versa for r/w transactions
+ */
+ dlist_head possibleUnsafeConflicts;
+
+ TransactionId topXid; /* top level xid for the transaction, if one
+ * exists; else invalid */
+ TransactionId finishedBefore; /* invalid means still running; else the
+ * struct expires when no serializable
+ * xids are before this. */
+ TransactionId xmin; /* the transaction's snapshot xmin */
+ uint32 flags; /* OR'd combination of values defined below */
+ int pid; /* pid of associated process */
+ int pgprocno; /* pgprocno of associated process */
+} SERIALIZABLEXACT;
+
+#define SXACT_FLAG_COMMITTED 0x00000001 /* already committed */
+#define SXACT_FLAG_PREPARED 0x00000002 /* about to commit */
+#define SXACT_FLAG_ROLLED_BACK 0x00000004 /* already rolled back */
+#define SXACT_FLAG_DOOMED 0x00000008 /* will roll back */
+/*
+ * The following flag actually means that the flagged transaction has a
+ * conflict out *to a transaction which committed ahead of it*. It's hard
+ * to get that into a name of a reasonable length.
+ */
+#define SXACT_FLAG_CONFLICT_OUT 0x00000010
+#define SXACT_FLAG_READ_ONLY 0x00000020
+#define SXACT_FLAG_DEFERRABLE_WAITING 0x00000040
+#define SXACT_FLAG_RO_SAFE 0x00000080
+#define SXACT_FLAG_RO_UNSAFE 0x00000100
+#define SXACT_FLAG_SUMMARY_CONFLICT_IN 0x00000200
+#define SXACT_FLAG_SUMMARY_CONFLICT_OUT 0x00000400
+/*
+ * The following flag means the transaction has been partially released
+ * already, but is being preserved because parallel workers might have a
+ * reference to it. It'll be recycled by the leader at end-of-transaction.
+ */
+#define SXACT_FLAG_PARTIALLY_RELEASED 0x00000800
+
+typedef struct PredXactListData
+{
+ dlist_head availableList;
+ dlist_head activeList;
+
+ /*
+ * These global variables are maintained when registering and cleaning up
+ * serializable transactions. They must be global across all backends,
+ * but are not needed outside the predicate.c source file. Protected by
+ * SerializableXactHashLock.
+ */
+ TransactionId SxactGlobalXmin; /* global xmin for active serializable
+ * transactions */
+ int SxactGlobalXminCount; /* how many active serializable
+ * transactions have this xmin */
+ int WritableSxactCount; /* how many non-read-only serializable
+ * transactions are active */
+ SerCommitSeqNo LastSxactCommitSeqNo; /* a strictly monotonically
+ * increasing number for commits
+ * of serializable transactions */
+ /* Protected by SerializableXactHashLock. */
+ SerCommitSeqNo CanPartialClearThrough; /* can clear predicate locks and
+ * inConflicts for committed
+ * transactions through this seq
+ * no */
+ /* Protected by SerializableFinishedListLock. */
+ SerCommitSeqNo HavePartialClearedThrough; /* have cleared through this
+ * seq no */
+ SERIALIZABLEXACT *OldCommittedSxact; /* shared copy of dummy sxact */
+
+ SERIALIZABLEXACT *element;
+} PredXactListData;
+
+typedef struct PredXactListData *PredXactList;
+
+#define PredXactListDataSize \
+ ((Size)MAXALIGN(sizeof(PredXactListData)))
+
+
+/*
+ * The following types are used to provide lists of rw-conflicts between
+ * pairs of transactions. Since exactly the same information is needed,
+ * they are also used to record possible unsafe transaction relationships
+ * for purposes of identifying safe snapshots for read-only transactions.
+ *
+ * When a RWConflictData is not in use to record either type of relationship
+ * between a pair of transactions, it is kept on an "available" list. The
+ * outLink field is used for maintaining that list.
+ */
+typedef struct RWConflictData
+{
+ dlist_node outLink; /* link for list of conflicts out from a sxact */
+ dlist_node inLink; /* link for list of conflicts in to a sxact */
+ SERIALIZABLEXACT *sxactOut;
+ SERIALIZABLEXACT *sxactIn;
+} RWConflictData;
+
+typedef struct RWConflictData *RWConflict;
+
+#define RWConflictDataSize \
+ ((Size)MAXALIGN(sizeof(RWConflictData)))
+
+typedef struct RWConflictPoolHeaderData
+{
+ dlist_head availableList;
+ RWConflict element;
+} RWConflictPoolHeaderData;
+
+typedef struct RWConflictPoolHeaderData *RWConflictPoolHeader;
+
+#define RWConflictPoolHeaderDataSize \
+ ((Size)MAXALIGN(sizeof(RWConflictPoolHeaderData)))
+
+
+/*
+ * The SERIALIZABLEXIDTAG struct identifies an xid assigned to a serializable
+ * transaction or any of its subtransactions.
+ */
+typedef struct SERIALIZABLEXIDTAG
+{
+ TransactionId xid;
+} SERIALIZABLEXIDTAG;
+
+/*
+ * The SERIALIZABLEXID struct provides a link from a TransactionId for a
+ * serializable transaction to the related SERIALIZABLEXACT record, even if
+ * the transaction has completed and its connection has been closed.
+ *
+ * These are created as new top level transaction IDs are first assigned to
+ * transactions which are participating in predicate locking. This may
+ * never happen for a particular transaction if it doesn't write anything.
+ * They are removed with their related serializable transaction objects.
+ *
+ * The SubTransGetTopmostTransaction method is used where necessary to get
+ * from an XID which might be from a subtransaction to the top level XID.
+ */
+typedef struct SERIALIZABLEXID
+{
+ /* hash key */
+ SERIALIZABLEXIDTAG tag;
+
+ /* data */
+ SERIALIZABLEXACT *myXact; /* pointer to the top level transaction data */
+} SERIALIZABLEXID;
+
+
+/*
+ * The PREDICATELOCKTARGETTAG struct identifies a database object which can
+ * be the target of predicate locks.
+ *
+ * Note that the hash function being used doesn't properly respect tag
+ * length -- if the length of the structure isn't a multiple of four bytes it
+ * will go to a four byte boundary past the end of the tag. If you change
+ * this struct, make sure any slack space is initialized, so that any random
+ * bytes in the middle or at the end are not included in the hash.
+ *
+ * TODO SSI: If we always use the same fields for the same type of value, we
+ * should rename these. Holding off until it's clear there are no exceptions.
+ * Since indexes are relations with blocks and tuples, it's looking likely that
+ * the rename will be possible. If not, we may need to divide the last field
+ * and use part of it for a target type, so that we know how to interpret the
+ * data..
+ */
+typedef struct PREDICATELOCKTARGETTAG
+{
+ uint32 locktag_field1; /* a 32-bit ID field */
+ uint32 locktag_field2; /* a 32-bit ID field */
+ uint32 locktag_field3; /* a 32-bit ID field */
+ uint32 locktag_field4; /* a 32-bit ID field */
+} PREDICATELOCKTARGETTAG;
+
+/*
+ * The PREDICATELOCKTARGET struct represents a database object on which there
+ * are predicate locks.
+ *
+ * A hash list of these objects is maintained in shared memory. An entry is
+ * added when a predicate lock is requested on an object which doesn't
+ * already have one. An entry is removed when the last lock is removed from
+ * its list.
+ */
+typedef struct PREDICATELOCKTARGET
+{
+ /* hash key */
+ PREDICATELOCKTARGETTAG tag; /* unique identifier of lockable object */
+
+ /* data */
+ dlist_head predicateLocks; /* list of PREDICATELOCK objects assoc. with
+ * predicate lock target */
+} PREDICATELOCKTARGET;
+
+
+/*
+ * The PREDICATELOCKTAG struct identifies an individual predicate lock.
+ *
+ * It is the combination of predicate lock target (which is a lockable
+ * object) and a serializable transaction which has acquired a lock on that
+ * target.
+ */
+typedef struct PREDICATELOCKTAG
+{
+ PREDICATELOCKTARGET *myTarget;
+ SERIALIZABLEXACT *myXact;
+} PREDICATELOCKTAG;
+
+/*
+ * The PREDICATELOCK struct represents an individual lock.
+ *
+ * An entry can be created here when the related database object is read, or
+ * by promotion of multiple finer-grained targets. All entries related to a
+ * serializable transaction are removed when that serializable transaction is
+ * cleaned up. Entries can also be removed when they are combined into a
+ * single coarser-grained lock entry.
+ */
+typedef struct PREDICATELOCK
+{
+ /* hash key */
+ PREDICATELOCKTAG tag; /* unique identifier of lock */
+
+ /* data */
+ dlist_node targetLink; /* list link in PREDICATELOCKTARGET's list of
+ * predicate locks */
+ dlist_node xactLink; /* list link in SERIALIZABLEXACT's list of
+ * predicate locks */
+ SerCommitSeqNo commitSeqNo; /* only used for summarized predicate locks */
+} PREDICATELOCK;
+
+
+/*
+ * The LOCALPREDICATELOCK struct represents a local copy of data which is
+ * also present in the PREDICATELOCK table, organized for fast access without
+ * needing to acquire a LWLock. It is strictly for optimization.
+ *
+ * Each serializable transaction creates its own local hash table to hold a
+ * collection of these. This information is used to determine when a number
+ * of fine-grained locks should be promoted to a single coarser-grained lock.
+ * The information is maintained more-or-less in parallel to the
+ * PREDICATELOCK data, but because this data is not protected by locks and is
+ * only used in an optimization heuristic, it is allowed to drift in a few
+ * corner cases where maintaining exact data would be expensive.
+ *
+ * The hash table is created when the serializable transaction acquires its
+ * snapshot, and its memory is released upon completion of the transaction.
+ */
+typedef struct LOCALPREDICATELOCK
+{
+ /* hash key */
+ PREDICATELOCKTARGETTAG tag; /* unique identifier of lockable object */
+
+ /* data */
+ bool held; /* is lock held, or just its children? */
+ int childLocks; /* number of child locks currently held */
+} LOCALPREDICATELOCK;
+
+
+/*
+ * The types of predicate locks which can be acquired.
+ */
+typedef enum PredicateLockTargetType
+{
+ PREDLOCKTAG_RELATION,
+ PREDLOCKTAG_PAGE,
+ PREDLOCKTAG_TUPLE
+ /* TODO SSI: Other types may be needed for index locking */
+} PredicateLockTargetType;
+
+
+/*
+ * This structure is used to quickly capture a copy of all predicate
+ * locks. This is currently used only by the pg_lock_status function,
+ * which in turn is used by the pg_locks view.
+ */
+typedef struct PredicateLockData
+{
+ int nelements;
+ PREDICATELOCKTARGETTAG *locktags;
+ SERIALIZABLEXACT *xacts;
+} PredicateLockData;
+
+
+/*
+ * These macros define how we map logical IDs of lockable objects into the
+ * physical fields of PREDICATELOCKTARGETTAG. Use these to set up values,
+ * rather than accessing the fields directly. Note multiple eval of target!
+ */
+#define SET_PREDICATELOCKTARGETTAG_RELATION(locktag,dboid,reloid) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = InvalidBlockNumber, \
+ (locktag).locktag_field4 = InvalidOffsetNumber)
+
+#define SET_PREDICATELOCKTARGETTAG_PAGE(locktag,dboid,reloid,blocknum) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = (blocknum), \
+ (locktag).locktag_field4 = InvalidOffsetNumber)
+
+#define SET_PREDICATELOCKTARGETTAG_TUPLE(locktag,dboid,reloid,blocknum,offnum) \
+ ((locktag).locktag_field1 = (dboid), \
+ (locktag).locktag_field2 = (reloid), \
+ (locktag).locktag_field3 = (blocknum), \
+ (locktag).locktag_field4 = (offnum))
+
+#define GET_PREDICATELOCKTARGETTAG_DB(locktag) \
+ ((Oid) (locktag).locktag_field1)
+#define GET_PREDICATELOCKTARGETTAG_RELATION(locktag) \
+ ((Oid) (locktag).locktag_field2)
+#define GET_PREDICATELOCKTARGETTAG_PAGE(locktag) \
+ ((BlockNumber) (locktag).locktag_field3)
+#define GET_PREDICATELOCKTARGETTAG_OFFSET(locktag) \
+ ((OffsetNumber) (locktag).locktag_field4)
+#define GET_PREDICATELOCKTARGETTAG_TYPE(locktag) \
+ (((locktag).locktag_field4 != InvalidOffsetNumber) ? PREDLOCKTAG_TUPLE : \
+ (((locktag).locktag_field3 != InvalidBlockNumber) ? PREDLOCKTAG_PAGE : \
+ PREDLOCKTAG_RELATION))
+
+/*
+ * Two-phase commit statefile records. There are two types: for each
+ * transaction, we generate one per-transaction record and a variable
+ * number of per-predicate-lock records.
+ */
+typedef enum TwoPhasePredicateRecordType
+{
+ TWOPHASEPREDICATERECORD_XACT,
+ TWOPHASEPREDICATERECORD_LOCK
+} TwoPhasePredicateRecordType;
+
+/*
+ * Per-transaction information to reconstruct a SERIALIZABLEXACT. Not
+ * much is needed because most of it not meaningful for a recovered
+ * prepared transaction.
+ *
+ * In particular, we do not record the in and out conflict lists for a
+ * prepared transaction because the associated SERIALIZABLEXACTs will
+ * not be available after recovery. Instead, we simply record the
+ * existence of each type of conflict by setting the transaction's
+ * summary conflict in/out flag.
+ */
+typedef struct TwoPhasePredicateXactRecord
+{
+ TransactionId xmin;
+ uint32 flags;
+} TwoPhasePredicateXactRecord;
+
+/* Per-lock state */
+typedef struct TwoPhasePredicateLockRecord
+{
+ PREDICATELOCKTARGETTAG target;
+ uint32 filler; /* to avoid length change in back-patched fix */
+} TwoPhasePredicateLockRecord;
+
+typedef struct TwoPhasePredicateRecord
+{
+ TwoPhasePredicateRecordType type;
+ union
+ {
+ TwoPhasePredicateXactRecord xactRecord;
+ TwoPhasePredicateLockRecord lockRecord;
+ } data;
+} TwoPhasePredicateRecord;
+
+/*
+ * Define a macro to use for an "empty" SERIALIZABLEXACT reference.
+ */
+#define InvalidSerializableXact ((SERIALIZABLEXACT *) NULL)
+
+
+/*
+ * Function definitions for functions needing awareness of predicate
+ * locking internals.
+ */
+extern PredicateLockData *GetPredicateLockStatusData(void);
+extern int GetSafeSnapshotBlockingPids(int blocked_pid,
+ int *output, int output_size);
+
+#endif /* PREDICATE_INTERNALS_H */
diff --git a/pgsql/include/server/storage/proc.h b/pgsql/include/server/storage/proc.h
new file mode 100644
index 0000000000000000000000000000000000000000..ef74f3269324a40d5a2c23b56ce69cdf885f5462
--- /dev/null
+++ b/pgsql/include/server/storage/proc.h
@@ -0,0 +1,466 @@
+/*-------------------------------------------------------------------------
+ *
+ * proc.h
+ * per-process shared memory data structures
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/proc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PROC_H_
+#define _PROC_H_
+
+#include "access/clog.h"
+#include "access/xlogdefs.h"
+#include "lib/ilist.h"
+#include "storage/latch.h"
+#include "storage/lock.h"
+#include "storage/pg_sema.h"
+#include "storage/proclist_types.h"
+
+/*
+ * Each backend advertises up to PGPROC_MAX_CACHED_SUBXIDS TransactionIds
+ * for non-aborted subtransactions of its current top transaction. These
+ * have to be treated as running XIDs by other backends.
+ *
+ * We also keep track of whether the cache overflowed (ie, the transaction has
+ * generated at least one subtransaction that didn't fit in the cache).
+ * If none of the caches have overflowed, we can assume that an XID that's not
+ * listed anywhere in the PGPROC array is not a running transaction. Else we
+ * have to look at pg_subtrans.
+ *
+ * See src/test/isolation/specs/subxid-overflow.spec if you change this.
+ */
+#define PGPROC_MAX_CACHED_SUBXIDS 64 /* XXX guessed-at value */
+
+typedef struct XidCacheStatus
+{
+ /* number of cached subxids, never more than PGPROC_MAX_CACHED_SUBXIDS */
+ uint8 count;
+ /* has PGPROC->subxids overflowed */
+ bool overflowed;
+} XidCacheStatus;
+
+struct XidCache
+{
+ TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS];
+};
+
+/*
+ * Flags for PGPROC->statusFlags and PROC_HDR->statusFlags[]
+ */
+#define PROC_IS_AUTOVACUUM 0x01 /* is it an autovac worker? */
+#define PROC_IN_VACUUM 0x02 /* currently running lazy vacuum */
+#define PROC_IN_SAFE_IC 0x04 /* currently running CREATE INDEX
+ * CONCURRENTLY or REINDEX
+ * CONCURRENTLY on non-expressional,
+ * non-partial index */
+#define PROC_VACUUM_FOR_WRAPAROUND 0x08 /* set by autovac only */
+#define PROC_IN_LOGICAL_DECODING 0x10 /* currently doing logical
+ * decoding outside xact */
+#define PROC_AFFECTS_ALL_HORIZONS 0x20 /* this proc's xmin must be
+ * included in vacuum horizons
+ * in all databases */
+
+/* flags reset at EOXact */
+#define PROC_VACUUM_STATE_MASK \
+ (PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+
+/*
+ * Xmin-related flags. Make sure any flags that affect how the process' Xmin
+ * value is interpreted by VACUUM are included here.
+ */
+#define PROC_XMIN_FLAGS (PROC_IN_VACUUM | PROC_IN_SAFE_IC)
+
+/*
+ * We allow a small number of "weak" relation locks (AccessShareLock,
+ * RowShareLock, RowExclusiveLock) to be recorded in the PGPROC structure
+ * rather than the main lock table. This eases contention on the lock
+ * manager LWLocks. See storage/lmgr/README for additional details.
+ */
+#define FP_LOCK_SLOTS_PER_BACKEND 16
+
+/*
+ * An invalid pgprocno. Must be larger than the maximum number of PGPROC
+ * structures we could possibly have. See comments for MAX_BACKENDS.
+ */
+#define INVALID_PGPROCNO PG_INT32_MAX
+
+/*
+ * Flags for PGPROC.delayChkptFlags
+ *
+ * These flags can be used to delay the start or completion of a checkpoint
+ * for short periods. A flag is in effect if the corresponding bit is set in
+ * the PGPROC of any backend.
+ *
+ * For our purposes here, a checkpoint has three phases: (1) determine the
+ * location to which the redo pointer will be moved, (2) write all the
+ * data durably to disk, and (3) WAL-log the checkpoint.
+ *
+ * Setting DELAY_CHKPT_START prevents the system from moving from phase 1
+ * to phase 2. This is useful when we are performing a WAL-logged modification
+ * of data that will be flushed to disk in phase 2. By setting this flag
+ * before writing WAL and clearing it after we've both written WAL and
+ * performed the corresponding modification, we ensure that if the WAL record
+ * is inserted prior to the new redo point, the corresponding data changes will
+ * also be flushed to disk before the checkpoint can complete. (In the
+ * extremely common case where the data being modified is in shared buffers
+ * and we acquire an exclusive content lock on the relevant buffers before
+ * writing WAL, this mechanism is not needed, because phase 2 will block
+ * until we release the content lock and then flush the modified data to
+ * disk.)
+ *
+ * Setting DELAY_CHKPT_COMPLETE prevents the system from moving from phase 2
+ * to phase 3. This is useful if we are performing a WAL-logged operation that
+ * might invalidate buffers, such as relation truncation. In this case, we need
+ * to ensure that any buffers which were invalidated and thus not flushed by
+ * the checkpoint are actually destroyed on disk. Replay can cope with a file
+ * or block that doesn't exist, but not with a block that has the wrong
+ * contents.
+ */
+#define DELAY_CHKPT_START (1<<0)
+#define DELAY_CHKPT_COMPLETE (1<<1)
+
+typedef enum
+{
+ PROC_WAIT_STATUS_OK,
+ PROC_WAIT_STATUS_WAITING,
+ PROC_WAIT_STATUS_ERROR,
+} ProcWaitStatus;
+
+/*
+ * Each backend has a PGPROC struct in shared memory. There is also a list of
+ * currently-unused PGPROC structs that will be reallocated to new backends.
+ *
+ * links: list link for any list the PGPROC is in. When waiting for a lock,
+ * the PGPROC is linked into that lock's waitProcs queue. A recycled PGPROC
+ * is linked into ProcGlobal's freeProcs list.
+ *
+ * Note: twophase.c also sets up a dummy PGPROC struct for each currently
+ * prepared transaction. These PGPROCs appear in the ProcArray data structure
+ * so that the prepared transactions appear to be still running and are
+ * correctly shown as holding locks. A prepared transaction PGPROC can be
+ * distinguished from a real one at need by the fact that it has pid == 0.
+ * The semaphore and lock-activity fields in a prepared-xact PGPROC are unused,
+ * but its myProcLocks[] lists are valid.
+ *
+ * We allow many fields of this struct to be accessed without locks, such as
+ * delayChkptFlags and isBackgroundWorker. However, keep in mind that writing
+ * mirrored ones (see below) requires holding ProcArrayLock or XidGenLock in
+ * at least shared mode, so that pgxactoff does not change concurrently.
+ *
+ * Mirrored fields:
+ *
+ * Some fields in PGPROC (see "mirrored in ..." comment) are mirrored into an
+ * element of more densely packed ProcGlobal arrays. These arrays are indexed
+ * by PGPROC->pgxactoff. Both copies need to be maintained coherently.
+ *
+ * NB: The pgxactoff indexed value can *never* be accessed without holding
+ * locks.
+ *
+ * See PROC_HDR for details.
+ */
+struct PGPROC
+{
+ /* proc->links MUST BE FIRST IN STRUCT (see ProcSleep,ProcWakeup,etc) */
+ dlist_node links; /* list link if process is in a list */
+ dlist_head *procgloballist; /* procglobal list that owns this PGPROC */
+
+ PGSemaphore sem; /* ONE semaphore to sleep on */
+ ProcWaitStatus waitStatus;
+
+ Latch procLatch; /* generic latch for process */
+
+
+ TransactionId xid; /* id of top-level transaction currently being
+ * executed by this proc, if running and XID
+ * is assigned; else InvalidTransactionId.
+ * mirrored in ProcGlobal->xids[pgxactoff] */
+
+ TransactionId xmin; /* minimal running XID as it was when we were
+ * starting our xact, excluding LAZY VACUUM:
+ * vacuum must not remove tuples deleted by
+ * xid >= xmin ! */
+
+ LocalTransactionId lxid; /* local id of top-level transaction currently
+ * being executed by this proc, if running;
+ * else InvalidLocalTransactionId */
+ int pid; /* Backend's process ID; 0 if prepared xact */
+
+ int pgxactoff; /* offset into various ProcGlobal->arrays with
+ * data mirrored from this PGPROC */
+
+ int pgprocno; /* Number of this PGPROC in
+ * ProcGlobal->allProcs array. This is set
+ * once by InitProcGlobal().
+ * ProcGlobal->allProcs[n].pgprocno == n */
+
+ /* These fields are zero while a backend is still starting up: */
+ BackendId backendId; /* This backend's backend ID (if assigned) */
+ Oid databaseId; /* OID of database this backend is using */
+ Oid roleId; /* OID of role using this backend */
+
+ Oid tempNamespaceId; /* OID of temp schema this backend is
+ * using */
+
+ bool isBackgroundWorker; /* true if background worker. */
+
+ /*
+ * While in hot standby mode, shows that a conflict signal has been sent
+ * for the current transaction. Set/cleared while holding ProcArrayLock,
+ * though not required. Accessed without lock, if needed.
+ */
+ bool recoveryConflictPending;
+
+ /* Info about LWLock the process is currently waiting for, if any. */
+ uint8 lwWaiting; /* see LWLockWaitState */
+ uint8 lwWaitMode; /* lwlock mode being waited for */
+ proclist_node lwWaitLink; /* position in LW lock wait list */
+
+ /* Support for condition variables. */
+ proclist_node cvWaitLink; /* position in CV wait list */
+
+ /* Info about lock the process is currently waiting for, if any. */
+ /* waitLock and waitProcLock are NULL if not currently waiting. */
+ LOCK *waitLock; /* Lock object we're sleeping on ... */
+ PROCLOCK *waitProcLock; /* Per-holder info for awaited lock */
+ LOCKMODE waitLockMode; /* type of lock we're waiting for */
+ LOCKMASK heldLocks; /* bitmask for lock types already held on this
+ * lock object by this backend */
+ pg_atomic_uint64 waitStart; /* time at which wait for lock acquisition
+ * started */
+
+ int delayChkptFlags; /* for DELAY_CHKPT_* flags */
+
+ uint8 statusFlags; /* this backend's status flags, see PROC_*
+ * above. mirrored in
+ * ProcGlobal->statusFlags[pgxactoff] */
+
+ /*
+ * Info to allow us to wait for synchronous replication, if needed.
+ * waitLSN is InvalidXLogRecPtr if not waiting; set only by user backend.
+ * syncRepState must not be touched except by owning process or WALSender.
+ * syncRepLinks used only while holding SyncRepLock.
+ */
+ XLogRecPtr waitLSN; /* waiting for this LSN or higher */
+ int syncRepState; /* wait state for sync rep */
+ dlist_node syncRepLinks; /* list link if process is in syncrep queue */
+
+ /*
+ * All PROCLOCK objects for locks held or awaited by this backend are
+ * linked into one of these lists, according to the partition number of
+ * their lock.
+ */
+ dlist_head myProcLocks[NUM_LOCK_PARTITIONS];
+
+ XidCacheStatus subxidStatus; /* mirrored with
+ * ProcGlobal->subxidStates[i] */
+ struct XidCache subxids; /* cache for subtransaction XIDs */
+
+ /* Support for group XID clearing. */
+ /* true, if member of ProcArray group waiting for XID clear */
+ bool procArrayGroupMember;
+ /* next ProcArray group member waiting for XID clear */
+ pg_atomic_uint32 procArrayGroupNext;
+
+ /*
+ * latest transaction id among the transaction's main XID and
+ * subtransactions
+ */
+ TransactionId procArrayGroupMemberXid;
+
+ uint32 wait_event_info; /* proc's wait information */
+
+ /* Support for group transaction status update. */
+ bool clogGroupMember; /* true, if member of clog group */
+ pg_atomic_uint32 clogGroupNext; /* next clog group member */
+ TransactionId clogGroupMemberXid; /* transaction id of clog group member */
+ XidStatus clogGroupMemberXidStatus; /* transaction status of clog
+ * group member */
+ int clogGroupMemberPage; /* clog page corresponding to
+ * transaction id of clog group member */
+ XLogRecPtr clogGroupMemberLsn; /* WAL location of commit record for clog
+ * group member */
+
+ /* Lock manager data, recording fast-path locks taken by this backend. */
+ LWLock fpInfoLock; /* protects per-backend fast-path state */
+ uint64 fpLockBits; /* lock modes held for each fast-path slot */
+ Oid fpRelId[FP_LOCK_SLOTS_PER_BACKEND]; /* slots for rel oids */
+ bool fpVXIDLock; /* are we holding a fast-path VXID lock? */
+ LocalTransactionId fpLocalTransactionId; /* lxid for fast-path VXID
+ * lock */
+
+ /*
+ * Support for lock groups. Use LockHashPartitionLockByProc on the group
+ * leader to get the LWLock protecting these fields.
+ */
+ PGPROC *lockGroupLeader; /* lock group leader, if I'm a member */
+ dlist_head lockGroupMembers; /* list of members, if I'm a leader */
+ dlist_node lockGroupLink; /* my member link, if I'm a member */
+};
+
+/* NOTE: "typedef struct PGPROC PGPROC" appears in storage/lock.h. */
+
+
+extern PGDLLIMPORT PGPROC *MyProc;
+
+/*
+ * There is one ProcGlobal struct for the whole database cluster.
+ *
+ * Adding/Removing an entry into the procarray requires holding *both*
+ * ProcArrayLock and XidGenLock in exclusive mode (in that order). Both are
+ * needed because the dense arrays (see below) are accessed from
+ * GetNewTransactionId() and GetSnapshotData(), and we don't want to add
+ * further contention by both using the same lock. Adding/Removing a procarray
+ * entry is much less frequent.
+ *
+ * Some fields in PGPROC are mirrored into more densely packed arrays (e.g.
+ * xids), with one entry for each backend. These arrays only contain entries
+ * for PGPROCs that have been added to the shared array with ProcArrayAdd()
+ * (in contrast to PGPROC array which has unused PGPROCs interspersed).
+ *
+ * The dense arrays are indexed by PGPROC->pgxactoff. Any concurrent
+ * ProcArrayAdd() / ProcArrayRemove() can lead to pgxactoff of a procarray
+ * member to change. Therefore it is only safe to use PGPROC->pgxactoff to
+ * access the dense array while holding either ProcArrayLock or XidGenLock.
+ *
+ * As long as a PGPROC is in the procarray, the mirrored values need to be
+ * maintained in both places in a coherent manner.
+ *
+ * The denser separate arrays are beneficial for three main reasons: First, to
+ * allow for as tight loops accessing the data as possible. Second, to prevent
+ * updates of frequently changing data (e.g. xmin) from invalidating
+ * cachelines also containing less frequently changing data (e.g. xid,
+ * statusFlags). Third to condense frequently accessed data into as few
+ * cachelines as possible.
+ *
+ * There are two main reasons to have the data mirrored between these dense
+ * arrays and PGPROC. First, as explained above, a PGPROC's array entries can
+ * only be accessed with either ProcArrayLock or XidGenLock held, whereas the
+ * PGPROC entries do not require that (obviously there may still be locking
+ * requirements around the individual field, separate from the concerns
+ * here). That is particularly important for a backend to efficiently checks
+ * it own values, which it often can safely do without locking. Second, the
+ * PGPROC fields allow to avoid unnecessary accesses and modification to the
+ * dense arrays. A backend's own PGPROC is more likely to be in a local cache,
+ * whereas the cachelines for the dense array will be modified by other
+ * backends (often removing it from the cache for other cores/sockets). At
+ * commit/abort time a check of the PGPROC value can avoid accessing/dirtying
+ * the corresponding array value.
+ *
+ * Basically it makes sense to access the PGPROC variable when checking a
+ * single backend's data, especially when already looking at the PGPROC for
+ * other reasons already. It makes sense to look at the "dense" arrays if we
+ * need to look at many / most entries, because we then benefit from the
+ * reduced indirection and better cross-process cache-ability.
+ *
+ * When entering a PGPROC for 2PC transactions with ProcArrayAdd(), the data
+ * in the dense arrays is initialized from the PGPROC while it already holds
+ * ProcArrayLock.
+ */
+typedef struct PROC_HDR
+{
+ /* Array of PGPROC structures (not including dummies for prepared txns) */
+ PGPROC *allProcs;
+
+ /* Array mirroring PGPROC.xid for each PGPROC currently in the procarray */
+ TransactionId *xids;
+
+ /*
+ * Array mirroring PGPROC.subxidStatus for each PGPROC currently in the
+ * procarray.
+ */
+ XidCacheStatus *subxidStates;
+
+ /*
+ * Array mirroring PGPROC.statusFlags for each PGPROC currently in the
+ * procarray.
+ */
+ uint8 *statusFlags;
+
+ /* Length of allProcs array */
+ uint32 allProcCount;
+ /* Head of list of free PGPROC structures */
+ dlist_head freeProcs;
+ /* Head of list of autovacuum's free PGPROC structures */
+ dlist_head autovacFreeProcs;
+ /* Head of list of bgworker free PGPROC structures */
+ dlist_head bgworkerFreeProcs;
+ /* Head of list of walsender free PGPROC structures */
+ dlist_head walsenderFreeProcs;
+ /* First pgproc waiting for group XID clear */
+ pg_atomic_uint32 procArrayGroupFirst;
+ /* First pgproc waiting for group transaction status update */
+ pg_atomic_uint32 clogGroupFirst;
+ /* WALWriter process's latch */
+ Latch *walwriterLatch;
+ /* Checkpointer process's latch */
+ Latch *checkpointerLatch;
+ /* Current shared estimate of appropriate spins_per_delay value */
+ int spins_per_delay;
+ /* Buffer id of the buffer that Startup process waits for pin on, or -1 */
+ int startupBufferPinWaitBufId;
+} PROC_HDR;
+
+extern PGDLLIMPORT PROC_HDR *ProcGlobal;
+
+extern PGDLLIMPORT PGPROC *PreparedXactProcs;
+
+/* Accessor for PGPROC given a pgprocno. */
+#define GetPGProcByNumber(n) (&ProcGlobal->allProcs[(n)])
+
+/*
+ * We set aside some extra PGPROC structures for auxiliary processes,
+ * ie things that aren't full-fledged backends but need shmem access.
+ *
+ * Background writer, checkpointer, WAL writer and archiver run during normal
+ * operation. Startup process and WAL receiver also consume 2 slots, but WAL
+ * writer is launched only after startup has exited, so we only need 5 slots.
+ */
+#define NUM_AUXILIARY_PROCS 5
+
+/* configurable options */
+extern PGDLLIMPORT int DeadlockTimeout;
+extern PGDLLIMPORT int StatementTimeout;
+extern PGDLLIMPORT int LockTimeout;
+extern PGDLLIMPORT int IdleInTransactionSessionTimeout;
+extern PGDLLIMPORT int IdleSessionTimeout;
+extern PGDLLIMPORT bool log_lock_waits;
+
+
+/*
+ * Function Prototypes
+ */
+extern int ProcGlobalSemas(void);
+extern Size ProcGlobalShmemSize(void);
+extern void InitProcGlobal(void);
+extern void InitProcess(void);
+extern void InitProcessPhase2(void);
+extern void InitAuxiliaryProcess(void);
+
+extern void SetStartupBufferPinWaitBufId(int bufid);
+extern int GetStartupBufferPinWaitBufId(void);
+
+extern bool HaveNFreeProcs(int n, int *nfree);
+extern void ProcReleaseLocks(bool isCommit);
+
+extern ProcWaitStatus ProcSleep(LOCALLOCK *locallock, LockMethod lockMethodTable);
+extern void ProcWakeup(PGPROC *proc, ProcWaitStatus waitStatus);
+extern void ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock);
+extern void CheckDeadLockAlert(void);
+extern bool IsWaitingForLock(void);
+extern void LockErrorCleanup(void);
+
+extern void ProcWaitForSignal(uint32 wait_event_info);
+extern void ProcSendSignal(int pgprocno);
+
+extern PGPROC *AuxiliaryPidGetProc(int pid);
+
+extern void BecomeLockGroupLeader(void);
+extern bool BecomeLockGroupMember(PGPROC *leader, int pid);
+
+#endif /* _PROC_H_ */
diff --git a/pgsql/include/server/storage/procarray.h b/pgsql/include/server/storage/procarray.h
new file mode 100644
index 0000000000000000000000000000000000000000..d8cae3ce1c52154a320e444225a6095ceb32be3e
--- /dev/null
+++ b/pgsql/include/server/storage/procarray.h
@@ -0,0 +1,99 @@
+/*-------------------------------------------------------------------------
+ *
+ * procarray.h
+ * POSTGRES process array definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/procarray.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PROCARRAY_H
+#define PROCARRAY_H
+
+#include "storage/lock.h"
+#include "storage/standby.h"
+#include "utils/relcache.h"
+#include "utils/snapshot.h"
+
+
+extern Size ProcArrayShmemSize(void);
+extern void CreateSharedProcArray(void);
+extern void ProcArrayAdd(PGPROC *proc);
+extern void ProcArrayRemove(PGPROC *proc, TransactionId latestXid);
+
+extern void ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid);
+extern void ProcArrayClearTransaction(PGPROC *proc);
+
+extern void ProcArrayInitRecovery(TransactionId initializedUptoXID);
+extern void ProcArrayApplyRecoveryInfo(RunningTransactions running);
+extern void ProcArrayApplyXidAssignment(TransactionId topxid,
+ int nsubxids, TransactionId *subxids);
+
+extern void RecordKnownAssignedTransactionIds(TransactionId xid);
+extern void ExpireTreeKnownAssignedTransactionIds(TransactionId xid,
+ int nsubxids, TransactionId *subxids,
+ TransactionId max_xid);
+extern void ExpireAllKnownAssignedTransactionIds(void);
+extern void ExpireOldKnownAssignedTransactionIds(TransactionId xid);
+extern void KnownAssignedTransactionIdsIdleMaintenance(void);
+
+extern int GetMaxSnapshotXidCount(void);
+extern int GetMaxSnapshotSubxidCount(void);
+
+extern Snapshot GetSnapshotData(Snapshot snapshot);
+
+extern bool ProcArrayInstallImportedXmin(TransactionId xmin,
+ VirtualTransactionId *sourcevxid);
+extern bool ProcArrayInstallRestoredXmin(TransactionId xmin, PGPROC *proc);
+
+extern RunningTransactions GetRunningTransactionData(void);
+
+extern bool TransactionIdIsInProgress(TransactionId xid);
+extern bool TransactionIdIsActive(TransactionId xid);
+extern TransactionId GetOldestNonRemovableTransactionId(Relation rel);
+extern TransactionId GetOldestTransactionIdConsideredRunning(void);
+extern TransactionId GetOldestActiveTransactionId(void);
+extern TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly);
+extern void GetReplicationHorizons(TransactionId *xmin, TransactionId *catalog_xmin);
+
+extern VirtualTransactionId *GetVirtualXIDsDelayingChkpt(int *nvxids, int type);
+extern bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids,
+ int nvxids, int type);
+
+extern PGPROC *BackendPidGetProc(int pid);
+extern PGPROC *BackendPidGetProcWithLock(int pid);
+extern int BackendXidGetPid(TransactionId xid);
+extern bool IsBackendPid(int pid);
+
+extern VirtualTransactionId *GetCurrentVirtualXIDs(TransactionId limitXmin,
+ bool excludeXmin0, bool allDbs, int excludeVacuum,
+ int *nvxids);
+extern VirtualTransactionId *GetConflictingVirtualXIDs(TransactionId limitXmin, Oid dbOid);
+extern pid_t CancelVirtualTransaction(VirtualTransactionId vxid, ProcSignalReason sigmode);
+extern pid_t SignalVirtualTransaction(VirtualTransactionId vxid, ProcSignalReason sigmode,
+ bool conflictPending);
+
+extern bool MinimumActiveBackends(int min);
+extern int CountDBBackends(Oid databaseid);
+extern int CountDBConnections(Oid databaseid);
+extern void CancelDBBackends(Oid databaseid, ProcSignalReason sigmode, bool conflictPending);
+extern int CountUserBackends(Oid roleid);
+extern bool CountOtherDBBackends(Oid databaseId,
+ int *nbackends, int *nprepared);
+extern void TerminateOtherDBBackends(Oid databaseId);
+
+extern void XidCacheRemoveRunningXids(TransactionId xid,
+ int nxids, const TransactionId *xids,
+ TransactionId latestXid);
+
+extern void ProcArraySetReplicationSlotXmin(TransactionId xmin,
+ TransactionId catalog_xmin, bool already_locked);
+
+extern void ProcArrayGetReplicationSlotXmin(TransactionId *xmin,
+ TransactionId *catalog_xmin);
+
+#endif /* PROCARRAY_H */
diff --git a/pgsql/include/server/storage/proclist.h b/pgsql/include/server/storage/proclist.h
new file mode 100644
index 0000000000000000000000000000000000000000..e7d00e5ce12f9751c33caf37bb4db8f59a216f31
--- /dev/null
+++ b/pgsql/include/server/storage/proclist.h
@@ -0,0 +1,219 @@
+/*-------------------------------------------------------------------------
+ *
+ * proclist.h
+ * operations on doubly-linked lists of pgprocnos
+ *
+ * The interface is similar to dlist from ilist.h, but uses pgprocno instead
+ * of pointers. This allows proclist_head to be mapped at different addresses
+ * in different backends.
+ *
+ * See proclist_types.h for the structs that these functions operate on. They
+ * are separated to break a header dependency cycle with proc.h.
+ *
+ * Portions Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/storage/proclist.h
+ *-------------------------------------------------------------------------
+ */
+#ifndef PROCLIST_H
+#define PROCLIST_H
+
+#include "storage/proc.h"
+#include "storage/proclist_types.h"
+
+/*
+ * Initialize a proclist.
+ */
+static inline void
+proclist_init(proclist_head *list)
+{
+ list->head = list->tail = INVALID_PGPROCNO;
+}
+
+/*
+ * Is the list empty?
+ */
+static inline bool
+proclist_is_empty(const proclist_head *list)
+{
+ return list->head == INVALID_PGPROCNO;
+}
+
+/*
+ * Get a pointer to a proclist_node inside a given PGPROC, given a procno and
+ * the proclist_node field's offset within struct PGPROC.
+ */
+static inline proclist_node *
+proclist_node_get(int procno, size_t node_offset)
+{
+ char *entry = (char *) GetPGProcByNumber(procno);
+
+ return (proclist_node *) (entry + node_offset);
+}
+
+/*
+ * Insert a process at the beginning of a list.
+ */
+static inline void
+proclist_push_head_offset(proclist_head *list, int procno, size_t node_offset)
+{
+ proclist_node *node = proclist_node_get(procno, node_offset);
+
+ Assert(node->next == 0 && node->prev == 0);
+
+ if (list->head == INVALID_PGPROCNO)
+ {
+ Assert(list->tail == INVALID_PGPROCNO);
+ node->next = node->prev = INVALID_PGPROCNO;
+ list->head = list->tail = procno;
+ }
+ else
+ {
+ Assert(list->tail != INVALID_PGPROCNO);
+ Assert(list->head != procno);
+ Assert(list->tail != procno);
+ node->next = list->head;
+ proclist_node_get(node->next, node_offset)->prev = procno;
+ node->prev = INVALID_PGPROCNO;
+ list->head = procno;
+ }
+}
+
+/*
+ * Insert a process at the end of a list.
+ */
+static inline void
+proclist_push_tail_offset(proclist_head *list, int procno, size_t node_offset)
+{
+ proclist_node *node = proclist_node_get(procno, node_offset);
+
+ Assert(node->next == 0 && node->prev == 0);
+
+ if (list->tail == INVALID_PGPROCNO)
+ {
+ Assert(list->head == INVALID_PGPROCNO);
+ node->next = node->prev = INVALID_PGPROCNO;
+ list->head = list->tail = procno;
+ }
+ else
+ {
+ Assert(list->head != INVALID_PGPROCNO);
+ Assert(list->head != procno);
+ Assert(list->tail != procno);
+ node->prev = list->tail;
+ proclist_node_get(node->prev, node_offset)->next = procno;
+ node->next = INVALID_PGPROCNO;
+ list->tail = procno;
+ }
+}
+
+/*
+ * Delete a process from a list --- it must be in the list!
+ */
+static inline void
+proclist_delete_offset(proclist_head *list, int procno, size_t node_offset)
+{
+ proclist_node *node = proclist_node_get(procno, node_offset);
+
+ Assert(node->next != 0 || node->prev != 0);
+
+ if (node->prev == INVALID_PGPROCNO)
+ {
+ Assert(list->head == procno);
+ list->head = node->next;
+ }
+ else
+ proclist_node_get(node->prev, node_offset)->next = node->next;
+
+ if (node->next == INVALID_PGPROCNO)
+ {
+ Assert(list->tail == procno);
+ list->tail = node->prev;
+ }
+ else
+ proclist_node_get(node->next, node_offset)->prev = node->prev;
+
+ node->next = node->prev = 0;
+}
+
+/*
+ * Check if a process is currently in a list. It must be known that the
+ * process is not in any _other_ proclist that uses the same proclist_node,
+ * so that the only possibilities are that it is in this list or none.
+ */
+static inline bool
+proclist_contains_offset(const proclist_head *list, int procno,
+ size_t node_offset)
+{
+ const proclist_node *node = proclist_node_get(procno, node_offset);
+
+ /* If it's not in any list, it's definitely not in this one. */
+ if (node->prev == 0 && node->next == 0)
+ return false;
+
+ /*
+ * It must, in fact, be in this list. Ideally, in assert-enabled builds,
+ * we'd verify that. But since this function is typically used while
+ * holding a spinlock, crawling the whole list is unacceptable. However,
+ * we can verify matters in O(1) time when the node is a list head or
+ * tail, and that seems worth doing, since in practice that should often
+ * be enough to catch mistakes.
+ */
+ Assert(node->prev != INVALID_PGPROCNO || list->head == procno);
+ Assert(node->next != INVALID_PGPROCNO || list->tail == procno);
+
+ return true;
+}
+
+/*
+ * Remove and return the first process from a list (there must be one).
+ */
+static inline PGPROC *
+proclist_pop_head_node_offset(proclist_head *list, size_t node_offset)
+{
+ PGPROC *proc;
+
+ Assert(!proclist_is_empty(list));
+ proc = GetPGProcByNumber(list->head);
+ proclist_delete_offset(list, list->head, node_offset);
+ return proc;
+}
+
+/*
+ * Helper macros to avoid repetition of offsetof(PGPROC, ).
+ * 'link_member' is the name of a proclist_node member in PGPROC.
+ */
+#define proclist_delete(list, procno, link_member) \
+ proclist_delete_offset((list), (procno), offsetof(PGPROC, link_member))
+#define proclist_push_head(list, procno, link_member) \
+ proclist_push_head_offset((list), (procno), offsetof(PGPROC, link_member))
+#define proclist_push_tail(list, procno, link_member) \
+ proclist_push_tail_offset((list), (procno), offsetof(PGPROC, link_member))
+#define proclist_pop_head_node(list, link_member) \
+ proclist_pop_head_node_offset((list), offsetof(PGPROC, link_member))
+#define proclist_contains(list, procno, link_member) \
+ proclist_contains_offset((list), (procno), offsetof(PGPROC, link_member))
+
+/*
+ * Iterate through the list pointed at by 'lhead', storing the current
+ * position in 'iter'. 'link_member' is the name of a proclist_node member in
+ * PGPROC. Access the current position with iter.cur.
+ *
+ * The only list modification allowed while iterating is deleting the current
+ * node with proclist_delete(list, iter.cur, node_offset).
+ */
+#define proclist_foreach_modify(iter, lhead, link_member) \
+ for (AssertVariableIsOfTypeMacro(iter, proclist_mutable_iter), \
+ AssertVariableIsOfTypeMacro(lhead, proclist_head *), \
+ (iter).cur = (lhead)->head, \
+ (iter).next = (iter).cur == INVALID_PGPROCNO ? INVALID_PGPROCNO : \
+ proclist_node_get((iter).cur, \
+ offsetof(PGPROC, link_member))->next; \
+ (iter).cur != INVALID_PGPROCNO; \
+ (iter).cur = (iter).next, \
+ (iter).next = (iter).cur == INVALID_PGPROCNO ? INVALID_PGPROCNO : \
+ proclist_node_get((iter).cur, \
+ offsetof(PGPROC, link_member))->next)
+
+#endif /* PROCLIST_H */
diff --git a/pgsql/include/server/storage/proclist_types.h b/pgsql/include/server/storage/proclist_types.h
new file mode 100644
index 0000000000000000000000000000000000000000..526c3ea6f99b34f1c97a836299190f976a34f4ef
--- /dev/null
+++ b/pgsql/include/server/storage/proclist_types.h
@@ -0,0 +1,51 @@
+/*-------------------------------------------------------------------------
+ *
+ * proclist_types.h
+ * doubly-linked lists of pgprocnos
+ *
+ * See proclist.h for functions that operate on these types.
+ *
+ * Portions Copyright (c) 2016-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/storage/proclist_types.h
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef PROCLIST_TYPES_H
+#define PROCLIST_TYPES_H
+
+/*
+ * A node in a doubly-linked list of processes. The link fields contain
+ * the 0-based PGPROC indexes of the next and previous process, or
+ * INVALID_PGPROCNO in the next-link of the last node and the prev-link
+ * of the first node. A node that is currently not in any list
+ * should have next == prev == 0; this is not a possible state for a node
+ * that is in a list, because we disallow circularity.
+ */
+typedef struct proclist_node
+{
+ int next; /* pgprocno of the next PGPROC */
+ int prev; /* pgprocno of the prev PGPROC */
+} proclist_node;
+
+/*
+ * Header of a doubly-linked list of PGPROCs, identified by pgprocno.
+ * An empty list is represented by head == tail == INVALID_PGPROCNO.
+ */
+typedef struct proclist_head
+{
+ int head; /* pgprocno of the head PGPROC */
+ int tail; /* pgprocno of the tail PGPROC */
+} proclist_head;
+
+/*
+ * List iterator allowing some modifications while iterating.
+ */
+typedef struct proclist_mutable_iter
+{
+ int cur; /* pgprocno of the current PGPROC */
+ int next; /* pgprocno of the next PGPROC */
+} proclist_mutable_iter;
+
+#endif /* PROCLIST_TYPES_H */
diff --git a/pgsql/include/server/storage/procsignal.h b/pgsql/include/server/storage/procsignal.h
new file mode 100644
index 0000000000000000000000000000000000000000..2f52100b009cfd3617c8c31658ca0859fb3587e8
--- /dev/null
+++ b/pgsql/include/server/storage/procsignal.h
@@ -0,0 +1,73 @@
+/*-------------------------------------------------------------------------
+ *
+ * procsignal.h
+ * Routines for interprocess signaling
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/procsignal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PROCSIGNAL_H
+#define PROCSIGNAL_H
+
+#include "storage/backendid.h"
+
+
+/*
+ * Reasons for signaling a Postgres child process (a backend or an auxiliary
+ * process, like checkpointer). We can cope with concurrent signals for different
+ * reasons. However, if the same reason is signaled multiple times in quick
+ * succession, the process is likely to observe only one notification of it.
+ * This is okay for the present uses.
+ *
+ * Also, because of race conditions, it's important that all the signals be
+ * defined so that no harm is done if a process mistakenly receives one.
+ */
+typedef enum
+{
+ PROCSIG_CATCHUP_INTERRUPT, /* sinval catchup interrupt */
+ PROCSIG_NOTIFY_INTERRUPT, /* listen/notify interrupt */
+ PROCSIG_PARALLEL_MESSAGE, /* message from cooperating parallel backend */
+ PROCSIG_WALSND_INIT_STOPPING, /* ask walsenders to prepare for shutdown */
+ PROCSIG_BARRIER, /* global barrier interrupt */
+ PROCSIG_LOG_MEMORY_CONTEXT, /* ask backend to log the memory contexts */
+ PROCSIG_PARALLEL_APPLY_MESSAGE, /* Message from parallel apply workers */
+
+ /* Recovery conflict reasons */
+ PROCSIG_RECOVERY_CONFLICT_DATABASE,
+ PROCSIG_RECOVERY_CONFLICT_TABLESPACE,
+ PROCSIG_RECOVERY_CONFLICT_LOCK,
+ PROCSIG_RECOVERY_CONFLICT_SNAPSHOT,
+ PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT,
+ PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
+ PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK,
+
+ NUM_PROCSIGNALS /* Must be last! */
+} ProcSignalReason;
+
+typedef enum
+{
+ PROCSIGNAL_BARRIER_SMGRRELEASE /* ask smgr to close files */
+} ProcSignalBarrierType;
+
+/*
+ * prototypes for functions in procsignal.c
+ */
+extern Size ProcSignalShmemSize(void);
+extern void ProcSignalShmemInit(void);
+
+extern void ProcSignalInit(int pss_idx);
+extern int SendProcSignal(pid_t pid, ProcSignalReason reason,
+ BackendId backendId);
+
+extern uint64 EmitProcSignalBarrier(ProcSignalBarrierType type);
+extern void WaitForProcSignalBarrier(uint64 generation);
+extern void ProcessProcSignalBarrier(void);
+
+extern void procsignal_sigusr1_handler(SIGNAL_ARGS);
+
+#endif /* PROCSIGNAL_H */
diff --git a/pgsql/include/server/storage/reinit.h b/pgsql/include/server/storage/reinit.h
new file mode 100644
index 0000000000000000000000000000000000000000..e2bbb5abe9f3312bf2f59a0903773b4a777b575f
--- /dev/null
+++ b/pgsql/include/server/storage/reinit.h
@@ -0,0 +1,29 @@
+/*-------------------------------------------------------------------------
+ *
+ * reinit.h
+ * Reinitialization of unlogged relations
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/reinit.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef REINIT_H
+#define REINIT_H
+
+#include "common/relpath.h"
+
+
+extern void ResetUnloggedRelations(int op);
+extern bool parse_filename_for_nontemp_relation(const char *name,
+ int *relnumchars,
+ ForkNumber *fork);
+
+#define UNLOGGED_RELATION_CLEANUP 0x0001
+#define UNLOGGED_RELATION_INIT 0x0002
+
+#endif /* REINIT_H */
diff --git a/pgsql/include/server/storage/relfilelocator.h b/pgsql/include/server/storage/relfilelocator.h
new file mode 100644
index 0000000000000000000000000000000000000000..61cf0169bd749432219ff5c3912a92c9291d444e
--- /dev/null
+++ b/pgsql/include/server/storage/relfilelocator.h
@@ -0,0 +1,99 @@
+/*-------------------------------------------------------------------------
+ *
+ * relfilelocator.h
+ * Physical access information for relations.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/relfilelocator.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RELFILELOCATOR_H
+#define RELFILELOCATOR_H
+
+#include "common/relpath.h"
+#include "storage/backendid.h"
+
+/*
+ * RelFileLocator must provide all that we need to know to physically access
+ * a relation, with the exception of the backend ID, which can be provided
+ * separately. Note, however, that a "physical" relation is comprised of
+ * multiple files on the filesystem, as each fork is stored as a separate
+ * file, and each fork can be divided into multiple segments. See md.c.
+ *
+ * spcOid identifies the tablespace of the relation. It corresponds to
+ * pg_tablespace.oid.
+ *
+ * dbOid identifies the database of the relation. It is zero for
+ * "shared" relations (those common to all databases of a cluster).
+ * Nonzero dbOid values correspond to pg_database.oid.
+ *
+ * relNumber identifies the specific relation. relNumber corresponds to
+ * pg_class.relfilenode (NOT pg_class.oid, because we need to be able
+ * to assign new physical files to relations in some situations).
+ * Notice that relNumber is only unique within a database in a particular
+ * tablespace.
+ *
+ * Note: spcOid must be GLOBALTABLESPACE_OID if and only if dbOid is
+ * zero. We support shared relations only in the "global" tablespace.
+ *
+ * Note: in pg_class we allow reltablespace == 0 to denote that the
+ * relation is stored in its database's "default" tablespace (as
+ * identified by pg_database.dattablespace). However this shorthand
+ * is NOT allowed in RelFileLocator structs --- the real tablespace ID
+ * must be supplied when setting spcOid.
+ *
+ * Note: in pg_class, relfilenode can be zero to denote that the relation
+ * is a "mapped" relation, whose current true filenode number is available
+ * from relmapper.c. Again, this case is NOT allowed in RelFileLocators.
+ *
+ * Note: various places use RelFileLocator in hashtable keys. Therefore,
+ * there *must not* be any unused padding bytes in this struct. That
+ * should be safe as long as all the fields are of type Oid.
+ */
+typedef struct RelFileLocator
+{
+ Oid spcOid; /* tablespace */
+ Oid dbOid; /* database */
+ RelFileNumber relNumber; /* relation */
+} RelFileLocator;
+
+/*
+ * Augmenting a relfilelocator with the backend ID provides all the information
+ * we need to locate the physical storage. The backend ID is InvalidBackendId
+ * for regular relations (those accessible to more than one backend), or the
+ * owning backend's ID for backend-local relations. Backend-local relations
+ * are always transient and removed in case of a database crash; they are
+ * never WAL-logged or fsync'd.
+ */
+typedef struct RelFileLocatorBackend
+{
+ RelFileLocator locator;
+ BackendId backend;
+} RelFileLocatorBackend;
+
+#define RelFileLocatorBackendIsTemp(rlocator) \
+ ((rlocator).backend != InvalidBackendId)
+
+/*
+ * Note: RelFileLocatorEquals and RelFileLocatorBackendEquals compare relNumber
+ * first since that is most likely to be different in two unequal
+ * RelFileLocators. It is probably redundant to compare spcOid if the other
+ * fields are found equal, but do it anyway to be sure. Likewise for checking
+ * the backend ID in RelFileLocatorBackendEquals.
+ */
+#define RelFileLocatorEquals(locator1, locator2) \
+ ((locator1).relNumber == (locator2).relNumber && \
+ (locator1).dbOid == (locator2).dbOid && \
+ (locator1).spcOid == (locator2).spcOid)
+
+#define RelFileLocatorBackendEquals(locator1, locator2) \
+ ((locator1).locator.relNumber == (locator2).locator.relNumber && \
+ (locator1).locator.dbOid == (locator2).locator.dbOid && \
+ (locator1).backend == (locator2).backend && \
+ (locator1).locator.spcOid == (locator2).locator.spcOid)
+
+#endif /* RELFILELOCATOR_H */
diff --git a/pgsql/include/server/storage/s_lock.h b/pgsql/include/server/storage/s_lock.h
new file mode 100644
index 0000000000000000000000000000000000000000..c9fa84cc43c9dc27b55525694fb6668d8877e5ac
--- /dev/null
+++ b/pgsql/include/server/storage/s_lock.h
@@ -0,0 +1,867 @@
+/*-------------------------------------------------------------------------
+ *
+ * s_lock.h
+ * Hardware-dependent implementation of spinlocks.
+ *
+ * NOTE: none of the macros in this file are intended to be called directly.
+ * Call them through the hardware-independent macros in spin.h.
+ *
+ * The following hardware-dependent macros must be provided for each
+ * supported platform:
+ *
+ * void S_INIT_LOCK(slock_t *lock)
+ * Initialize a spinlock (to the unlocked state).
+ *
+ * int S_LOCK(slock_t *lock)
+ * Acquire a spinlock, waiting if necessary.
+ * Time out and abort() if unable to acquire the lock in a
+ * "reasonable" amount of time --- typically ~ 1 minute.
+ * Should return number of "delays"; see s_lock.c
+ *
+ * void S_UNLOCK(slock_t *lock)
+ * Unlock a previously acquired lock.
+ *
+ * bool S_LOCK_FREE(slock_t *lock)
+ * Tests if the lock is free. Returns true if free, false if locked.
+ * This does *not* change the state of the lock.
+ *
+ * void SPIN_DELAY(void)
+ * Delay operation to occur inside spinlock wait loop.
+ *
+ * Note to implementors: there are default implementations for all these
+ * macros at the bottom of the file. Check if your platform can use
+ * these or needs to override them.
+ *
+ * Usually, S_LOCK() is implemented in terms of even lower-level macros
+ * TAS() and TAS_SPIN():
+ *
+ * int TAS(slock_t *lock)
+ * Atomic test-and-set instruction. Attempt to acquire the lock,
+ * but do *not* wait. Returns 0 if successful, nonzero if unable
+ * to acquire the lock.
+ *
+ * int TAS_SPIN(slock_t *lock)
+ * Like TAS(), but this version is used when waiting for a lock
+ * previously found to be contended. By default, this is the
+ * same as TAS(), but on some architectures it's better to poll a
+ * contended lock using an unlocked instruction and retry the
+ * atomic test-and-set only when it appears free.
+ *
+ * TAS() and TAS_SPIN() are NOT part of the API, and should never be called
+ * directly.
+ *
+ * CAUTION: on some platforms TAS() and/or TAS_SPIN() may sometimes report
+ * failure to acquire a lock even when the lock is not locked. For example,
+ * on Alpha TAS() will "fail" if interrupted. Therefore a retry loop must
+ * always be used, even if you are certain the lock is free.
+ *
+ * It is the responsibility of these macros to make sure that the compiler
+ * does not re-order accesses to shared memory to precede the actual lock
+ * acquisition, or follow the lock release. Prior to PostgreSQL 9.5, this
+ * was the caller's responsibility, which meant that callers had to use
+ * volatile-qualified pointers to refer to both the spinlock itself and the
+ * shared data being accessed within the spinlocked critical section. This
+ * was notationally awkward, easy to forget (and thus error-prone), and
+ * prevented some useful compiler optimizations. For these reasons, we
+ * now require that the macros themselves prevent compiler re-ordering,
+ * so that the caller doesn't need to take special precautions.
+ *
+ * On platforms with weak memory ordering, the TAS(), TAS_SPIN(), and
+ * S_UNLOCK() macros must further include hardware-level memory fence
+ * instructions to prevent similar re-ordering at the hardware level.
+ * TAS() and TAS_SPIN() must guarantee that loads and stores issued after
+ * the macro are not executed until the lock has been obtained. Conversely,
+ * S_UNLOCK() must guarantee that loads and stores issued before the macro
+ * have been executed before the lock is released.
+ *
+ * On most supported platforms, TAS() uses a tas() function written
+ * in assembly language to execute a hardware atomic-test-and-set
+ * instruction. Equivalent OS-supplied mutex routines could be used too.
+ *
+ * If no system-specific TAS() is available (ie, HAVE_SPINLOCKS is not
+ * defined), then we fall back on an emulation that uses SysV semaphores
+ * (see spin.c). This emulation will be MUCH MUCH slower than a proper TAS()
+ * implementation, because of the cost of a kernel call per lock or unlock.
+ * An old report is that Postgres spends around 40% of its time in semop(2)
+ * when using the SysV semaphore code.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/s_lock.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef S_LOCK_H
+#define S_LOCK_H
+
+#ifdef FRONTEND
+#error "s_lock.h may not be included from frontend code"
+#endif
+
+#ifdef HAVE_SPINLOCKS /* skip spinlocks if requested */
+
+#if defined(__GNUC__) || defined(__INTEL_COMPILER)
+/*************************************************************************
+ * All the gcc inlines
+ * Gcc consistently defines the CPU as __cpu__.
+ * Other compilers use __cpu or __cpu__ so we test for both in those cases.
+ */
+
+/*----------
+ * Standard gcc asm format (assuming "volatile slock_t *lock"):
+
+ __asm__ __volatile__(
+ " instruction \n"
+ " instruction \n"
+ " instruction \n"
+: "=r"(_res), "+m"(*lock) // return register, in/out lock value
+: "r"(lock) // lock pointer, in input register
+: "memory", "cc"); // show clobbered registers here
+
+ * The output-operands list (after first colon) should always include
+ * "+m"(*lock), whether or not the asm code actually refers to this
+ * operand directly. This ensures that gcc believes the value in the
+ * lock variable is used and set by the asm code. Also, the clobbers
+ * list (after third colon) should always include "memory"; this prevents
+ * gcc from thinking it can cache the values of shared-memory fields
+ * across the asm code. Add "cc" if your asm code changes the condition
+ * code register, and also list any temp registers the code uses.
+ *----------
+ */
+
+
+#ifdef __i386__ /* 32-bit i386 */
+#define HAS_TEST_AND_SET
+
+typedef unsigned char slock_t;
+
+#define TAS(lock) tas(lock)
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ slock_t _res = 1;
+
+ /*
+ * Use a non-locking test before asserting the bus lock. Note that the
+ * extra test appears to be a small loss on some x86 platforms and a small
+ * win on others; it's by no means clear that we should keep it.
+ *
+ * When this was last tested, we didn't have separate TAS() and TAS_SPIN()
+ * macros. Nowadays it probably would be better to do a non-locking test
+ * in TAS_SPIN() but not in TAS(), like on x86_64, but no-one's done the
+ * testing to verify that. Without some empirical evidence, better to
+ * leave it alone.
+ */
+ __asm__ __volatile__(
+ " cmpb $0,%1 \n"
+ " jne 1f \n"
+ " lock \n"
+ " xchgb %0,%1 \n"
+ "1: \n"
+: "+q"(_res), "+m"(*lock)
+: /* no inputs */
+: "memory", "cc");
+ return (int) _res;
+}
+
+#define SPIN_DELAY() spin_delay()
+
+static __inline__ void
+spin_delay(void)
+{
+ /*
+ * This sequence is equivalent to the PAUSE instruction ("rep" is
+ * ignored by old IA32 processors if the following instruction is
+ * not a string operation); the IA-32 Architecture Software
+ * Developer's Manual, Vol. 3, Section 7.7.2 describes why using
+ * PAUSE in the inner loop of a spin lock is necessary for good
+ * performance:
+ *
+ * The PAUSE instruction improves the performance of IA-32
+ * processors supporting Hyper-Threading Technology when
+ * executing spin-wait loops and other routines where one
+ * thread is accessing a shared lock or semaphore in a tight
+ * polling loop. When executing a spin-wait loop, the
+ * processor can suffer a severe performance penalty when
+ * exiting the loop because it detects a possible memory order
+ * violation and flushes the core processor's pipeline. The
+ * PAUSE instruction provides a hint to the processor that the
+ * code sequence is a spin-wait loop. The processor uses this
+ * hint to avoid the memory order violation and prevent the
+ * pipeline flush. In addition, the PAUSE instruction
+ * de-pipelines the spin-wait loop to prevent it from
+ * consuming execution resources excessively.
+ */
+ __asm__ __volatile__(
+ " rep; nop \n");
+}
+
+#endif /* __i386__ */
+
+
+#ifdef __x86_64__ /* AMD Opteron, Intel EM64T */
+#define HAS_TEST_AND_SET
+
+typedef unsigned char slock_t;
+
+#define TAS(lock) tas(lock)
+
+/*
+ * On Intel EM64T, it's a win to use a non-locking test before the xchg proper,
+ * but only when spinning.
+ *
+ * See also Implementing Scalable Atomic Locks for Multi-Core Intel(tm) EM64T
+ * and IA32, by Michael Chynoweth and Mary R. Lee. As of this writing, it is
+ * available at:
+ * http://software.intel.com/en-us/articles/implementing-scalable-atomic-locks-for-multi-core-intel-em64t-and-ia32-architectures
+ */
+#define TAS_SPIN(lock) (*(lock) ? 1 : TAS(lock))
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ slock_t _res = 1;
+
+ __asm__ __volatile__(
+ " lock \n"
+ " xchgb %0,%1 \n"
+: "+q"(_res), "+m"(*lock)
+: /* no inputs */
+: "memory", "cc");
+ return (int) _res;
+}
+
+#define SPIN_DELAY() spin_delay()
+
+static __inline__ void
+spin_delay(void)
+{
+ /*
+ * Adding a PAUSE in the spin delay loop is demonstrably a no-op on
+ * Opteron, but it may be of some use on EM64T, so we keep it.
+ */
+ __asm__ __volatile__(
+ " rep; nop \n");
+}
+
+#endif /* __x86_64__ */
+
+
+/*
+ * On ARM and ARM64, we use __sync_lock_test_and_set(int *, int) if available.
+ *
+ * We use the int-width variant of the builtin because it works on more chips
+ * than other widths.
+ */
+#if defined(__arm__) || defined(__arm) || defined(__aarch64__)
+#ifdef HAVE_GCC__SYNC_INT32_TAS
+#define HAS_TEST_AND_SET
+
+#define TAS(lock) tas(lock)
+
+typedef int slock_t;
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ return __sync_lock_test_and_set(lock, 1);
+}
+
+#define S_UNLOCK(lock) __sync_lock_release(lock)
+
+/*
+ * Using an ISB instruction to delay in spinlock loops appears beneficial on
+ * high-core-count ARM64 processors. It seems mostly a wash for smaller gear,
+ * and ISB doesn't exist at all on pre-v7 ARM chips.
+ */
+#if defined(__aarch64__)
+
+#define SPIN_DELAY() spin_delay()
+
+static __inline__ void
+spin_delay(void)
+{
+ __asm__ __volatile__(
+ " isb; \n");
+}
+
+#endif /* __aarch64__ */
+#endif /* HAVE_GCC__SYNC_INT32_TAS */
+#endif /* __arm__ || __arm || __aarch64__ */
+
+
+/* S/390 and S/390x Linux (32- and 64-bit zSeries) */
+#if defined(__s390__) || defined(__s390x__)
+#define HAS_TEST_AND_SET
+
+typedef unsigned int slock_t;
+
+#define TAS(lock) tas(lock)
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ int _res = 0;
+
+ __asm__ __volatile__(
+ " cs %0,%3,0(%2) \n"
+: "+d"(_res), "+m"(*lock)
+: "a"(lock), "d"(1)
+: "memory", "cc");
+ return _res;
+}
+
+#endif /* __s390__ || __s390x__ */
+
+
+#if defined(__sparc__) /* Sparc */
+/*
+ * Solaris has always run sparc processors in TSO (total store) mode, but
+ * linux didn't use to and the *BSDs still don't. So, be careful about
+ * acquire/release semantics. The CPU will treat superfluous members as
+ * NOPs, so it's just code space.
+ */
+#define HAS_TEST_AND_SET
+
+typedef unsigned char slock_t;
+
+#define TAS(lock) tas(lock)
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ slock_t _res;
+
+ /*
+ * See comment in src/backend/port/tas/sunstudio_sparc.s for why this
+ * uses "ldstub", and that file uses "cas". gcc currently generates
+ * sparcv7-targeted binaries, so "cas" use isn't possible.
+ */
+ __asm__ __volatile__(
+ " ldstub [%2], %0 \n"
+: "=r"(_res), "+m"(*lock)
+: "r"(lock)
+: "memory");
+#if defined(__sparcv7) || defined(__sparc_v7__)
+ /*
+ * No stbar or membar available, luckily no actually produced hardware
+ * requires a barrier.
+ */
+#elif defined(__sparcv8) || defined(__sparc_v8__)
+ /* stbar is available (and required for both PSO, RMO), membar isn't */
+ __asm__ __volatile__ ("stbar \n":::"memory");
+#else
+ /*
+ * #LoadStore (RMO) | #LoadLoad (RMO) together are the appropriate acquire
+ * barrier for sparcv8+ upwards.
+ */
+ __asm__ __volatile__ ("membar #LoadStore | #LoadLoad \n":::"memory");
+#endif
+ return (int) _res;
+}
+
+#if defined(__sparcv7) || defined(__sparc_v7__)
+/*
+ * No stbar or membar available, luckily no actually produced hardware
+ * requires a barrier. We fall through to the default gcc definition of
+ * S_UNLOCK in this case.
+ */
+#elif defined(__sparcv8) || defined(__sparc_v8__)
+/* stbar is available (and required for both PSO, RMO), membar isn't */
+#define S_UNLOCK(lock) \
+do \
+{ \
+ __asm__ __volatile__ ("stbar \n":::"memory"); \
+ *((volatile slock_t *) (lock)) = 0; \
+} while (0)
+#else
+/*
+ * #LoadStore (RMO) | #StoreStore (RMO, PSO) together are the appropriate
+ * release barrier for sparcv8+ upwards.
+ */
+#define S_UNLOCK(lock) \
+do \
+{ \
+ __asm__ __volatile__ ("membar #LoadStore | #StoreStore \n":::"memory"); \
+ *((volatile slock_t *) (lock)) = 0; \
+} while (0)
+#endif
+
+#endif /* __sparc__ */
+
+
+/* PowerPC */
+#if defined(__ppc__) || defined(__powerpc__) || defined(__ppc64__) || defined(__powerpc64__)
+#define HAS_TEST_AND_SET
+
+typedef unsigned int slock_t;
+
+#define TAS(lock) tas(lock)
+
+/* On PPC, it's a win to use a non-locking test before the lwarx */
+#define TAS_SPIN(lock) (*(lock) ? 1 : TAS(lock))
+
+/*
+ * The second operand of addi can hold a constant zero or a register number,
+ * hence constraint "=&b" to avoid allocating r0. "b" stands for "address
+ * base register"; most operands having this register-or-zero property are
+ * address bases, e.g. the second operand of lwax.
+ *
+ * NOTE: per the Enhanced PowerPC Architecture manual, v1.0 dated 7-May-2002,
+ * an isync is a sufficient synchronization barrier after a lwarx/stwcx loop.
+ * But if the spinlock is in ordinary memory, we can use lwsync instead for
+ * better performance.
+ *
+ * Ordinarily, we'd code the branches here using GNU-style local symbols, that
+ * is "1f" referencing "1:" and so on. But some people run gcc on AIX with
+ * IBM's assembler as backend, and IBM's assembler doesn't do local symbols.
+ * So hand-code the branch offsets; fortunately, all PPC instructions are
+ * exactly 4 bytes each, so it's not too hard to count.
+ */
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ slock_t _t;
+ int _res;
+
+ __asm__ __volatile__(
+" lwarx %0,0,%3,1 \n"
+" cmpwi %0,0 \n"
+" bne $+16 \n" /* branch to li %1,1 */
+" addi %0,%0,1 \n"
+" stwcx. %0,0,%3 \n"
+" beq $+12 \n" /* branch to lwsync */
+" li %1,1 \n"
+" b $+12 \n" /* branch to end of asm sequence */
+" lwsync \n"
+" li %1,0 \n"
+
+: "=&b"(_t), "=r"(_res), "+m"(*lock)
+: "r"(lock)
+: "memory", "cc");
+ return _res;
+}
+
+/*
+ * PowerPC S_UNLOCK is almost standard but requires a "sync" instruction.
+ * But we can use lwsync instead for better performance.
+ */
+#define S_UNLOCK(lock) \
+do \
+{ \
+ __asm__ __volatile__ (" lwsync \n" ::: "memory"); \
+ *((volatile slock_t *) (lock)) = 0; \
+} while (0)
+
+#endif /* powerpc */
+
+
+#if defined(__mips__) && !defined(__sgi) /* non-SGI MIPS */
+#define HAS_TEST_AND_SET
+
+typedef unsigned int slock_t;
+
+#define TAS(lock) tas(lock)
+
+/*
+ * Original MIPS-I processors lacked the LL/SC instructions, but if we are
+ * so unfortunate as to be running on one of those, we expect that the kernel
+ * will handle the illegal-instruction traps and emulate them for us. On
+ * anything newer (and really, MIPS-I is extinct) LL/SC is the only sane
+ * choice because any other synchronization method must involve a kernel
+ * call. Unfortunately, many toolchains still default to MIPS-I as the
+ * codegen target; if the symbol __mips shows that that's the case, we
+ * have to force the assembler to accept LL/SC.
+ *
+ * R10000 and up processors require a separate SYNC, which has the same
+ * issues as LL/SC.
+ */
+#if __mips < 2
+#define MIPS_SET_MIPS2 " .set mips2 \n"
+#else
+#define MIPS_SET_MIPS2
+#endif
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ volatile slock_t *_l = lock;
+ int _res;
+ int _tmp;
+
+ __asm__ __volatile__(
+ " .set push \n"
+ MIPS_SET_MIPS2
+ " .set noreorder \n"
+ " .set nomacro \n"
+ " ll %0, %2 \n"
+ " or %1, %0, 1 \n"
+ " sc %1, %2 \n"
+ " xori %1, 1 \n"
+ " or %0, %0, %1 \n"
+ " sync \n"
+ " .set pop "
+: "=&r" (_res), "=&r" (_tmp), "+R" (*_l)
+: /* no inputs */
+: "memory");
+ return _res;
+}
+
+/* MIPS S_UNLOCK is almost standard but requires a "sync" instruction */
+#define S_UNLOCK(lock) \
+do \
+{ \
+ __asm__ __volatile__( \
+ " .set push \n" \
+ MIPS_SET_MIPS2 \
+ " .set noreorder \n" \
+ " .set nomacro \n" \
+ " sync \n" \
+ " .set pop " \
+: /* no outputs */ \
+: /* no inputs */ \
+: "memory"); \
+ *((volatile slock_t *) (lock)) = 0; \
+} while (0)
+
+#endif /* __mips__ && !__sgi */
+
+
+#if defined(__hppa) || defined(__hppa__) /* HP PA-RISC */
+/*
+ * HP's PA-RISC
+ *
+ * Because LDCWX requires a 16-byte-aligned address, we declare slock_t as a
+ * 16-byte struct. The active word in the struct is whichever has the aligned
+ * address; the other three words just sit at -1.
+ */
+#define HAS_TEST_AND_SET
+
+typedef struct
+{
+ int sema[4];
+} slock_t;
+
+#define TAS_ACTIVE_WORD(lock) ((volatile int *) (((uintptr_t) (lock) + 15) & ~15))
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ volatile int *lockword = TAS_ACTIVE_WORD(lock);
+ int lockval;
+
+ /*
+ * The LDCWX instruction atomically clears the target word and
+ * returns the previous value. Hence, if the instruction returns
+ * 0, someone else has already acquired the lock before we tested
+ * it (i.e., we have failed).
+ *
+ * Notice that this means that we actually clear the word to set
+ * the lock and set the word to clear the lock. This is the
+ * opposite behavior from the SPARC LDSTUB instruction. For some
+ * reason everything that H-P does is rather baroque...
+ *
+ * For details about the LDCWX instruction, see the "Precision
+ * Architecture and Instruction Reference Manual" (09740-90014 of June
+ * 1987), p. 5-38.
+ */
+ __asm__ __volatile__(
+ " ldcwx 0(0,%2),%0 \n"
+: "=r"(lockval), "+m"(*lockword)
+: "r"(lockword)
+: "memory");
+ return (lockval == 0);
+}
+
+#define S_UNLOCK(lock) \
+ do { \
+ __asm__ __volatile__("" : : : "memory"); \
+ *TAS_ACTIVE_WORD(lock) = -1; \
+ } while (0)
+
+#define S_INIT_LOCK(lock) \
+ do { \
+ volatile slock_t *lock_ = (lock); \
+ lock_->sema[0] = -1; \
+ lock_->sema[1] = -1; \
+ lock_->sema[2] = -1; \
+ lock_->sema[3] = -1; \
+ } while (0)
+
+#define S_LOCK_FREE(lock) (*TAS_ACTIVE_WORD(lock) != 0)
+
+#endif /* __hppa || __hppa__ */
+
+
+/*
+ * If we have no platform-specific knowledge, but we found that the compiler
+ * provides __sync_lock_test_and_set(), use that. Prefer the int-width
+ * version over the char-width version if we have both, on the rather dubious
+ * grounds that that's known to be more likely to work in the ARM ecosystem.
+ * (But we dealt with ARM above.)
+ */
+#if !defined(HAS_TEST_AND_SET)
+
+#if defined(HAVE_GCC__SYNC_INT32_TAS)
+#define HAS_TEST_AND_SET
+
+#define TAS(lock) tas(lock)
+
+typedef int slock_t;
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ return __sync_lock_test_and_set(lock, 1);
+}
+
+#define S_UNLOCK(lock) __sync_lock_release(lock)
+
+#elif defined(HAVE_GCC__SYNC_CHAR_TAS)
+#define HAS_TEST_AND_SET
+
+#define TAS(lock) tas(lock)
+
+typedef char slock_t;
+
+static __inline__ int
+tas(volatile slock_t *lock)
+{
+ return __sync_lock_test_and_set(lock, 1);
+}
+
+#define S_UNLOCK(lock) __sync_lock_release(lock)
+
+#endif /* HAVE_GCC__SYNC_INT32_TAS */
+
+#endif /* !defined(HAS_TEST_AND_SET) */
+
+
+/*
+ * Default implementation of S_UNLOCK() for gcc/icc.
+ *
+ * Note that this implementation is unsafe for any platform that can reorder
+ * a memory access (either load or store) after a following store. That
+ * happens not to be possible on x86 and most legacy architectures (some are
+ * single-processor!), but many modern systems have weaker memory ordering.
+ * Those that do must define their own version of S_UNLOCK() rather than
+ * relying on this one.
+ */
+#if !defined(S_UNLOCK)
+#define S_UNLOCK(lock) \
+ do { __asm__ __volatile__("" : : : "memory"); *(lock) = 0; } while (0)
+#endif
+
+#endif /* defined(__GNUC__) || defined(__INTEL_COMPILER) */
+
+
+/*
+ * ---------------------------------------------------------------------
+ * Platforms that use non-gcc inline assembly:
+ * ---------------------------------------------------------------------
+ */
+
+#if !defined(HAS_TEST_AND_SET) /* We didn't trigger above, let's try here */
+
+#if defined(_AIX) /* AIX */
+/*
+ * AIX (POWER)
+ */
+#define HAS_TEST_AND_SET
+
+#include
+
+typedef int slock_t;
+
+#define TAS(lock) _check_lock((slock_t *) (lock), 0, 1)
+#define S_UNLOCK(lock) _clear_lock((slock_t *) (lock), 0)
+#endif /* _AIX */
+
+
+/* These are in sunstudio_(sparc|x86).s */
+
+#if defined(__SUNPRO_C) && (defined(__i386) || defined(__x86_64__) || defined(__sparc__) || defined(__sparc))
+#define HAS_TEST_AND_SET
+
+#if defined(__i386) || defined(__x86_64__) || defined(__sparcv9) || defined(__sparcv8plus)
+typedef unsigned int slock_t;
+#else
+typedef unsigned char slock_t;
+#endif
+
+extern slock_t pg_atomic_cas(volatile slock_t *lock, slock_t with,
+ slock_t cmp);
+
+#define TAS(a) (pg_atomic_cas((a), 1, 0) != 0)
+#endif
+
+
+#ifdef _MSC_VER
+typedef LONG slock_t;
+
+#define HAS_TEST_AND_SET
+#define TAS(lock) (InterlockedCompareExchange(lock, 1, 0))
+
+#define SPIN_DELAY() spin_delay()
+
+/* If using Visual C++ on Win64, inline assembly is unavailable.
+ * Use a _mm_pause intrinsic instead of rep nop.
+ */
+#if defined(_WIN64)
+static __forceinline void
+spin_delay(void)
+{
+ _mm_pause();
+}
+#else
+static __forceinline void
+spin_delay(void)
+{
+ /* See comment for gcc code. Same code, MASM syntax */
+ __asm rep nop;
+}
+#endif
+
+#include
+#pragma intrinsic(_ReadWriteBarrier)
+
+#define S_UNLOCK(lock) \
+ do { _ReadWriteBarrier(); (*(lock)) = 0; } while (0)
+
+#endif
+
+
+#endif /* !defined(HAS_TEST_AND_SET) */
+
+
+/* Blow up if we didn't have any way to do spinlocks */
+#ifndef HAS_TEST_AND_SET
+#error PostgreSQL does not have native spinlock support on this platform. To continue the compilation, rerun configure using --disable-spinlocks. However, performance will be poor. Please report this to pgsql-bugs@lists.postgresql.org.
+#endif
+
+
+#else /* !HAVE_SPINLOCKS */
+
+
+/*
+ * Fake spinlock implementation using semaphores --- slow and prone
+ * to fall foul of kernel limits on number of semaphores, so don't use this
+ * unless you must! The subroutines appear in spin.c.
+ */
+typedef int slock_t;
+
+extern bool s_lock_free_sema(volatile slock_t *lock);
+extern void s_unlock_sema(volatile slock_t *lock);
+extern void s_init_lock_sema(volatile slock_t *lock, bool nested);
+extern int tas_sema(volatile slock_t *lock);
+
+#define S_LOCK_FREE(lock) s_lock_free_sema(lock)
+#define S_UNLOCK(lock) s_unlock_sema(lock)
+#define S_INIT_LOCK(lock) s_init_lock_sema(lock, false)
+#define TAS(lock) tas_sema(lock)
+
+
+#endif /* HAVE_SPINLOCKS */
+
+
+/*
+ * Default Definitions - override these above as needed.
+ */
+
+#if !defined(S_LOCK)
+#define S_LOCK(lock) \
+ (TAS(lock) ? s_lock((lock), __FILE__, __LINE__, __func__) : 0)
+#endif /* S_LOCK */
+
+#if !defined(S_LOCK_FREE)
+#define S_LOCK_FREE(lock) (*(lock) == 0)
+#endif /* S_LOCK_FREE */
+
+#if !defined(S_UNLOCK)
+/*
+ * Our default implementation of S_UNLOCK is essentially *(lock) = 0. This
+ * is unsafe if the platform can reorder a memory access (either load or
+ * store) after a following store; platforms where this is possible must
+ * define their own S_UNLOCK. But CPU reordering is not the only concern:
+ * if we simply defined S_UNLOCK() as an inline macro, the compiler might
+ * reorder instructions from inside the critical section to occur after the
+ * lock release. Since the compiler probably can't know what the external
+ * function s_unlock is doing, putting the same logic there should be adequate.
+ * A sufficiently-smart globally optimizing compiler could break that
+ * assumption, though, and the cost of a function call for every spinlock
+ * release may hurt performance significantly, so we use this implementation
+ * only for platforms where we don't know of a suitable intrinsic. For the
+ * most part, those are relatively obscure platform/compiler combinations to
+ * which the PostgreSQL project does not have access.
+ */
+#define USE_DEFAULT_S_UNLOCK
+extern void s_unlock(volatile slock_t *lock);
+#define S_UNLOCK(lock) s_unlock(lock)
+#endif /* S_UNLOCK */
+
+#if !defined(S_INIT_LOCK)
+#define S_INIT_LOCK(lock) S_UNLOCK(lock)
+#endif /* S_INIT_LOCK */
+
+#if !defined(SPIN_DELAY)
+#define SPIN_DELAY() ((void) 0)
+#endif /* SPIN_DELAY */
+
+#if !defined(TAS)
+extern int tas(volatile slock_t *lock); /* in port/.../tas.s, or
+ * s_lock.c */
+
+#define TAS(lock) tas(lock)
+#endif /* TAS */
+
+#if !defined(TAS_SPIN)
+#define TAS_SPIN(lock) TAS(lock)
+#endif /* TAS_SPIN */
+
+extern PGDLLIMPORT slock_t dummy_spinlock;
+
+/*
+ * Platform-independent out-of-line support routines
+ */
+extern int s_lock(volatile slock_t *lock, const char *file, int line, const char *func);
+
+/* Support for dynamic adjustment of spins_per_delay */
+#define DEFAULT_SPINS_PER_DELAY 100
+
+extern void set_spins_per_delay(int shared_spins_per_delay);
+extern int update_spins_per_delay(int shared_spins_per_delay);
+
+/*
+ * Support for spin delay which is useful in various places where
+ * spinlock-like procedures take place.
+ */
+typedef struct
+{
+ int spins;
+ int delays;
+ int cur_delay;
+ const char *file;
+ int line;
+ const char *func;
+} SpinDelayStatus;
+
+static inline void
+init_spin_delay(SpinDelayStatus *status,
+ const char *file, int line, const char *func)
+{
+ status->spins = 0;
+ status->delays = 0;
+ status->cur_delay = 0;
+ status->file = file;
+ status->line = line;
+ status->func = func;
+}
+
+#define init_local_spin_delay(status) init_spin_delay(status, __FILE__, __LINE__, __func__)
+extern void perform_spin_delay(SpinDelayStatus *status);
+extern void finish_spin_delay(SpinDelayStatus *status);
+
+#endif /* S_LOCK_H */
diff --git a/pgsql/include/server/storage/sharedfileset.h b/pgsql/include/server/storage/sharedfileset.h
new file mode 100644
index 0000000000000000000000000000000000000000..aa6f97f8c70816f8fc20a73672d143b8b1313979
--- /dev/null
+++ b/pgsql/include/server/storage/sharedfileset.h
@@ -0,0 +1,37 @@
+/*-------------------------------------------------------------------------
+ *
+ * sharedfileset.h
+ * Shared temporary file management.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/sharedfileset.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef SHAREDFILESET_H
+#define SHAREDFILESET_H
+
+#include "storage/dsm.h"
+#include "storage/fd.h"
+#include "storage/fileset.h"
+#include "storage/spin.h"
+
+/*
+ * A set of temporary files that can be shared by multiple backends.
+ */
+typedef struct SharedFileSet
+{
+ FileSet fs;
+ slock_t mutex; /* mutex protecting the reference count */
+ int refcnt; /* number of attached backends */
+} SharedFileSet;
+
+extern void SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg);
+extern void SharedFileSetAttach(SharedFileSet *fileset, dsm_segment *seg);
+extern void SharedFileSetDeleteAll(SharedFileSet *fileset);
+
+#endif
diff --git a/pgsql/include/server/storage/shm_mq.h b/pgsql/include/server/storage/shm_mq.h
new file mode 100644
index 0000000000000000000000000000000000000000..2e04e4183781b36d197f655cbf420afa9752c8c8
--- /dev/null
+++ b/pgsql/include/server/storage/shm_mq.h
@@ -0,0 +1,86 @@
+/*-------------------------------------------------------------------------
+ *
+ * shm_mq.h
+ * single-reader, single-writer shared memory message queue
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/shm_mq.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SHM_MQ_H
+#define SHM_MQ_H
+
+#include "postmaster/bgworker.h"
+#include "storage/dsm.h"
+#include "storage/proc.h"
+
+/* The queue itself, in shared memory. */
+struct shm_mq;
+typedef struct shm_mq shm_mq;
+
+/* Backend-private state. */
+struct shm_mq_handle;
+typedef struct shm_mq_handle shm_mq_handle;
+
+/* Descriptors for a single write spanning multiple locations. */
+typedef struct
+{
+ const char *data;
+ Size len;
+} shm_mq_iovec;
+
+/* Possible results of a send or receive operation. */
+typedef enum
+{
+ SHM_MQ_SUCCESS, /* Sent or received a message. */
+ SHM_MQ_WOULD_BLOCK, /* Not completed; retry later. */
+ SHM_MQ_DETACHED /* Other process has detached queue. */
+} shm_mq_result;
+
+/*
+ * Primitives to create a queue and set the sender and receiver.
+ *
+ * Both the sender and the receiver must be set before any messages are read
+ * or written, but they need not be set by the same process. Each must be
+ * set exactly once.
+ */
+extern shm_mq *shm_mq_create(void *address, Size size);
+extern void shm_mq_set_receiver(shm_mq *mq, PGPROC *);
+extern void shm_mq_set_sender(shm_mq *mq, PGPROC *);
+
+/* Accessor methods for sender and receiver. */
+extern PGPROC *shm_mq_get_receiver(shm_mq *);
+extern PGPROC *shm_mq_get_sender(shm_mq *);
+
+/* Set up backend-local queue state. */
+extern shm_mq_handle *shm_mq_attach(shm_mq *mq, dsm_segment *seg,
+ BackgroundWorkerHandle *handle);
+
+/* Associate worker handle with shm_mq. */
+extern void shm_mq_set_handle(shm_mq_handle *, BackgroundWorkerHandle *);
+
+/* Break connection, release handle resources. */
+extern void shm_mq_detach(shm_mq_handle *mqh);
+
+/* Get the shm_mq from handle. */
+extern shm_mq *shm_mq_get_queue(shm_mq_handle *mqh);
+
+/* Send or receive messages. */
+extern shm_mq_result shm_mq_send(shm_mq_handle *mqh,
+ Size nbytes, const void *data, bool nowait,
+ bool force_flush);
+extern shm_mq_result shm_mq_sendv(shm_mq_handle *mqh, shm_mq_iovec *iov,
+ int iovcnt, bool nowait, bool force_flush);
+extern shm_mq_result shm_mq_receive(shm_mq_handle *mqh,
+ Size *nbytesp, void **datap, bool nowait);
+
+/* Wait for our counterparty to attach to the queue. */
+extern shm_mq_result shm_mq_wait_for_attach(shm_mq_handle *mqh);
+
+/* Smallest possible queue. */
+extern PGDLLIMPORT const Size shm_mq_minimum_size;
+
+#endif /* SHM_MQ_H */
diff --git a/pgsql/include/server/storage/shm_toc.h b/pgsql/include/server/storage/shm_toc.h
new file mode 100644
index 0000000000000000000000000000000000000000..7a2f8e993493f26a0609b60082600e71b68a4f44
--- /dev/null
+++ b/pgsql/include/server/storage/shm_toc.h
@@ -0,0 +1,58 @@
+/*-------------------------------------------------------------------------
+ *
+ * shm_toc.h
+ * shared memory segment table of contents
+ *
+ * This is intended to provide a simple way to divide a chunk of shared
+ * memory (probably dynamic shared memory allocated via dsm_create) into
+ * a number of regions and keep track of the addresses of those regions or
+ * key data structures within those regions. This is not intended to
+ * scale to a large number of keys and will perform poorly if used that
+ * way; if you need a large number of pointers, store them within some
+ * other data structure within the segment and only put the pointer to
+ * the data structure itself in the table of contents.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/shm_toc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SHM_TOC_H
+#define SHM_TOC_H
+
+#include "storage/shmem.h" /* for add_size() */
+
+/* shm_toc is an opaque type known only within shm_toc.c */
+typedef struct shm_toc shm_toc;
+
+extern shm_toc *shm_toc_create(uint64 magic, void *address, Size nbytes);
+extern shm_toc *shm_toc_attach(uint64 magic, void *address);
+extern void *shm_toc_allocate(shm_toc *toc, Size nbytes);
+extern Size shm_toc_freespace(shm_toc *toc);
+extern void shm_toc_insert(shm_toc *toc, uint64 key, void *address);
+extern void *shm_toc_lookup(shm_toc *toc, uint64 key, bool noError);
+
+/*
+ * Tools for estimating how large a chunk of shared memory will be needed
+ * to store a TOC and its dependent objects. Note: we don't really support
+ * large numbers of keys, but it's convenient to declare number_of_keys
+ * as a Size anyway.
+ */
+typedef struct
+{
+ Size space_for_chunks;
+ Size number_of_keys;
+} shm_toc_estimator;
+
+#define shm_toc_initialize_estimator(e) \
+ ((e)->space_for_chunks = 0, (e)->number_of_keys = 0)
+#define shm_toc_estimate_chunk(e, sz) \
+ ((e)->space_for_chunks = add_size((e)->space_for_chunks, BUFFERALIGN(sz)))
+#define shm_toc_estimate_keys(e, cnt) \
+ ((e)->number_of_keys = add_size((e)->number_of_keys, cnt))
+
+extern Size shm_toc_estimate(shm_toc_estimator *e);
+
+#endif /* SHM_TOC_H */
diff --git a/pgsql/include/server/storage/shmem.h b/pgsql/include/server/storage/shmem.h
new file mode 100644
index 0000000000000000000000000000000000000000..0e1fb2006c188514fad119f148889ef3055d3e57
--- /dev/null
+++ b/pgsql/include/server/storage/shmem.h
@@ -0,0 +1,59 @@
+/*-------------------------------------------------------------------------
+ *
+ * shmem.h
+ * shared memory management structures
+ *
+ * Historical note:
+ * A long time ago, Postgres' shared memory region was allowed to be mapped
+ * at a different address in each process, and shared memory "pointers" were
+ * passed around as offsets relative to the start of the shared memory region.
+ * That is no longer the case: each process must map the shared memory region
+ * at the same address. This means shared memory pointers can be passed
+ * around directly between different processes.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/shmem.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SHMEM_H
+#define SHMEM_H
+
+#include "utils/hsearch.h"
+
+
+/* shmem.c */
+extern void InitShmemAccess(void *seghdr);
+extern void InitShmemAllocation(void);
+extern void *ShmemAlloc(Size size);
+extern void *ShmemAllocNoError(Size size);
+extern void *ShmemAllocUnlocked(Size size);
+extern bool ShmemAddrIsValid(const void *addr);
+extern void InitShmemIndex(void);
+extern HTAB *ShmemInitHash(const char *name, long init_size, long max_size,
+ HASHCTL *infoP, int hash_flags);
+extern void *ShmemInitStruct(const char *name, Size size, bool *foundPtr);
+extern Size add_size(Size s1, Size s2);
+extern Size mul_size(Size s1, Size s2);
+
+/* ipci.c */
+extern void RequestAddinShmemSpace(Size size);
+
+/* size constants for the shmem index table */
+ /* max size of data structure string name */
+#define SHMEM_INDEX_KEYSIZE (48)
+ /* estimated size of the shmem index table (not a hard limit) */
+#define SHMEM_INDEX_SIZE (64)
+
+/* this is a hash bucket in the shmem index table */
+typedef struct
+{
+ char key[SHMEM_INDEX_KEYSIZE]; /* string name */
+ void *location; /* location in shared mem */
+ Size size; /* # bytes requested for the structure */
+ Size allocated_size; /* # bytes actually allocated */
+} ShmemIndexEnt;
+
+#endif /* SHMEM_H */
diff --git a/pgsql/include/server/storage/sinval.h b/pgsql/include/server/storage/sinval.h
new file mode 100644
index 0000000000000000000000000000000000000000..0721e4d20588752f7b64048edf7f01eaa9c8d47c
--- /dev/null
+++ b/pgsql/include/server/storage/sinval.h
@@ -0,0 +1,153 @@
+/*-------------------------------------------------------------------------
+ *
+ * sinval.h
+ * POSTGRES shared cache invalidation communication definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/sinval.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SINVAL_H
+#define SINVAL_H
+
+#include
+
+#include "storage/relfilelocator.h"
+
+/*
+ * We support several types of shared-invalidation messages:
+ * * invalidate a specific tuple in a specific catcache
+ * * invalidate all catcache entries from a given system catalog
+ * * invalidate a relcache entry for a specific logical relation
+ * * invalidate all relcache entries
+ * * invalidate an smgr cache entry for a specific physical relation
+ * * invalidate the mapped-relation mapping for a given database
+ * * invalidate any saved snapshot that might be used to scan a given relation
+ * More types could be added if needed. The message type is identified by
+ * the first "int8" field of the message struct. Zero or positive means a
+ * specific-catcache inval message (and also serves as the catcache ID field).
+ * Negative values identify the other message types, as per codes below.
+ *
+ * Catcache inval events are initially driven by detecting tuple inserts,
+ * updates and deletions in system catalogs (see CacheInvalidateHeapTuple).
+ * An update can generate two inval events, one for the old tuple and one for
+ * the new, but this is reduced to one event if the tuple's hash key doesn't
+ * change. Note that the inval events themselves don't actually say whether
+ * the tuple is being inserted or deleted. Also, since we transmit only a
+ * hash key, there is a small risk of unnecessary invalidations due to chance
+ * matches of hash keys.
+ *
+ * Note that some system catalogs have multiple caches on them (with different
+ * indexes). On detecting a tuple invalidation in such a catalog, separate
+ * catcache inval messages must be generated for each of its caches, since
+ * the hash keys will generally be different.
+ *
+ * Catcache, relcache, and snapshot invalidations are transactional, and so
+ * are sent to other backends upon commit. Internally to the generating
+ * backend, they are also processed at CommandCounterIncrement so that later
+ * commands in the same transaction see the new state. The generating backend
+ * also has to process them at abort, to flush out any cache state it's loaded
+ * from no-longer-valid entries.
+ *
+ * smgr and relation mapping invalidations are non-transactional: they are
+ * sent immediately when the underlying file change is made.
+ */
+
+typedef struct
+{
+ int8 id; /* cache ID --- must be first */
+ Oid dbId; /* database ID, or 0 if a shared relation */
+ uint32 hashValue; /* hash value of key for this catcache */
+} SharedInvalCatcacheMsg;
+
+#define SHAREDINVALCATALOG_ID (-1)
+
+typedef struct
+{
+ int8 id; /* type field --- must be first */
+ Oid dbId; /* database ID, or 0 if a shared catalog */
+ Oid catId; /* ID of catalog whose contents are invalid */
+} SharedInvalCatalogMsg;
+
+#define SHAREDINVALRELCACHE_ID (-2)
+
+typedef struct
+{
+ int8 id; /* type field --- must be first */
+ Oid dbId; /* database ID, or 0 if a shared relation */
+ Oid relId; /* relation ID, or 0 if whole relcache */
+} SharedInvalRelcacheMsg;
+
+#define SHAREDINVALSMGR_ID (-3)
+
+typedef struct
+{
+ /* note: field layout chosen to pack into 16 bytes */
+ int8 id; /* type field --- must be first */
+ int8 backend_hi; /* high bits of backend ID, if temprel */
+ uint16 backend_lo; /* low bits of backend ID, if temprel */
+ RelFileLocator rlocator; /* spcOid, dbOid, relNumber */
+} SharedInvalSmgrMsg;
+
+#define SHAREDINVALRELMAP_ID (-4)
+
+typedef struct
+{
+ int8 id; /* type field --- must be first */
+ Oid dbId; /* database ID, or 0 for shared catalogs */
+} SharedInvalRelmapMsg;
+
+#define SHAREDINVALSNAPSHOT_ID (-5)
+
+typedef struct
+{
+ int8 id; /* type field --- must be first */
+ Oid dbId; /* database ID, or 0 if a shared relation */
+ Oid relId; /* relation ID */
+} SharedInvalSnapshotMsg;
+
+typedef union
+{
+ int8 id; /* type field --- must be first */
+ SharedInvalCatcacheMsg cc;
+ SharedInvalCatalogMsg cat;
+ SharedInvalRelcacheMsg rc;
+ SharedInvalSmgrMsg sm;
+ SharedInvalRelmapMsg rm;
+ SharedInvalSnapshotMsg sn;
+} SharedInvalidationMessage;
+
+
+/* Counter of messages processed; don't worry about overflow. */
+extern PGDLLIMPORT uint64 SharedInvalidMessageCounter;
+
+extern PGDLLIMPORT volatile sig_atomic_t catchupInterruptPending;
+
+extern void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs,
+ int n);
+extern void ReceiveSharedInvalidMessages(void (*invalFunction) (SharedInvalidationMessage *msg),
+ void (*resetFunction) (void));
+
+/* signal handler for catchup events (PROCSIG_CATCHUP_INTERRUPT) */
+extern void HandleCatchupInterrupt(void);
+
+/*
+ * enable/disable processing of catchup events directly from signal handler.
+ * The enable routine first performs processing of any catchup events that
+ * have occurred since the last disable.
+ */
+extern void ProcessCatchupInterrupt(void);
+
+extern int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs,
+ bool *RelcacheInitFileInval);
+extern void ProcessCommittedInvalidationMessages(SharedInvalidationMessage *msgs,
+ int nmsgs, bool RelcacheInitFileInval,
+ Oid dbid, Oid tsid);
+
+extern void LocalExecuteInvalidationMessage(SharedInvalidationMessage *msg);
+
+#endif /* SINVAL_H */
diff --git a/pgsql/include/server/storage/sinvaladt.h b/pgsql/include/server/storage/sinvaladt.h
new file mode 100644
index 0000000000000000000000000000000000000000..db38819bfd7269917457542819eab63c4b16e4b6
--- /dev/null
+++ b/pgsql/include/server/storage/sinvaladt.h
@@ -0,0 +1,45 @@
+/*-------------------------------------------------------------------------
+ *
+ * sinvaladt.h
+ * POSTGRES shared cache invalidation data manager.
+ *
+ * The shared cache invalidation manager is responsible for transmitting
+ * invalidation messages between backends. Any message sent by any backend
+ * must be delivered to all already-running backends before it can be
+ * forgotten. (If we run out of space, we instead deliver a "RESET"
+ * message to backends that have fallen too far behind.)
+ *
+ * The struct type SharedInvalidationMessage, defining the contents of
+ * a single message, is defined in sinval.h.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/sinvaladt.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SINVALADT_H
+#define SINVALADT_H
+
+#include "storage/lock.h"
+#include "storage/sinval.h"
+
+/*
+ * prototypes for functions in sinvaladt.c
+ */
+extern Size SInvalShmemSize(void);
+extern void CreateSharedInvalidationState(void);
+extern void SharedInvalBackendInit(bool sendOnly);
+extern PGPROC *BackendIdGetProc(int backendID);
+extern void BackendIdGetTransactionIds(int backendID, TransactionId *xid,
+ TransactionId *xmin, int *nsubxid,
+ bool *overflowed);
+
+extern void SIInsertDataEntries(const SharedInvalidationMessage *data, int n);
+extern int SIGetDataEntries(SharedInvalidationMessage *data, int datasize);
+extern void SICleanupQueue(bool callerHasWriteLock, int minFree);
+
+extern LocalTransactionId GetNextLocalTransactionId(void);
+
+#endif /* SINVALADT_H */
diff --git a/pgsql/include/server/storage/smgr.h b/pgsql/include/server/storage/smgr.h
new file mode 100644
index 0000000000000000000000000000000000000000..a9a179aabacc488b7bd5d1e9de88c05df3891c3a
--- /dev/null
+++ b/pgsql/include/server/storage/smgr.h
@@ -0,0 +1,113 @@
+/*-------------------------------------------------------------------------
+ *
+ * smgr.h
+ * storage manager switch public interface declarations.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/smgr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SMGR_H
+#define SMGR_H
+
+#include "lib/ilist.h"
+#include "storage/block.h"
+#include "storage/relfilelocator.h"
+
+/*
+ * smgr.c maintains a table of SMgrRelation objects, which are essentially
+ * cached file handles. An SMgrRelation is created (if not already present)
+ * by smgropen(), and destroyed by smgrclose(). Note that neither of these
+ * operations imply I/O, they just create or destroy a hashtable entry.
+ * (But smgrclose() may release associated resources, such as OS-level file
+ * descriptors.)
+ *
+ * An SMgrRelation may have an "owner", which is just a pointer to it from
+ * somewhere else; smgr.c will clear this pointer if the SMgrRelation is
+ * closed. We use this to avoid dangling pointers from relcache to smgr
+ * without having to make the smgr explicitly aware of relcache. There
+ * can't be more than one "owner" pointer per SMgrRelation, but that's
+ * all we need.
+ *
+ * SMgrRelations that do not have an "owner" are considered to be transient,
+ * and are deleted at end of transaction.
+ */
+typedef struct SMgrRelationData
+{
+ /* rlocator is the hashtable lookup key, so it must be first! */
+ RelFileLocatorBackend smgr_rlocator; /* relation physical identifier */
+
+ /* pointer to owning pointer, or NULL if none */
+ struct SMgrRelationData **smgr_owner;
+
+ /*
+ * The following fields are reset to InvalidBlockNumber upon a cache flush
+ * event, and hold the last known size for each fork. This information is
+ * currently only reliable during recovery, since there is no cache
+ * invalidation for fork extension.
+ */
+ BlockNumber smgr_targblock; /* current insertion target block */
+ BlockNumber smgr_cached_nblocks[MAX_FORKNUM + 1]; /* last known size */
+
+ /* additional public fields may someday exist here */
+
+ /*
+ * Fields below here are intended to be private to smgr.c and its
+ * submodules. Do not touch them from elsewhere.
+ */
+ int smgr_which; /* storage manager selector */
+
+ /*
+ * for md.c; per-fork arrays of the number of open segments
+ * (md_num_open_segs) and the segments themselves (md_seg_fds).
+ */
+ int md_num_open_segs[MAX_FORKNUM + 1];
+ struct _MdfdVec *md_seg_fds[MAX_FORKNUM + 1];
+
+ /* if unowned, list link in list of all unowned SMgrRelations */
+ dlist_node node;
+} SMgrRelationData;
+
+typedef SMgrRelationData *SMgrRelation;
+
+#define SmgrIsTemp(smgr) \
+ RelFileLocatorBackendIsTemp((smgr)->smgr_rlocator)
+
+extern void smgrinit(void);
+extern SMgrRelation smgropen(RelFileLocator rlocator, BackendId backend);
+extern bool smgrexists(SMgrRelation reln, ForkNumber forknum);
+extern void smgrsetowner(SMgrRelation *owner, SMgrRelation reln);
+extern void smgrclearowner(SMgrRelation *owner, SMgrRelation reln);
+extern void smgrclose(SMgrRelation reln);
+extern void smgrcloseall(void);
+extern void smgrcloserellocator(RelFileLocatorBackend rlocator);
+extern void smgrrelease(SMgrRelation reln);
+extern void smgrreleaseall(void);
+extern void smgrcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo);
+extern void smgrdosyncall(SMgrRelation *rels, int nrels);
+extern void smgrdounlinkall(SMgrRelation *rels, int nrels, bool isRedo);
+extern void smgrextend(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, const void *buffer, bool skipFsync);
+extern void smgrzeroextend(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, int nblocks, bool skipFsync);
+extern bool smgrprefetch(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum);
+extern void smgrread(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, void *buffer);
+extern void smgrwrite(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, const void *buffer, bool skipFsync);
+extern void smgrwriteback(SMgrRelation reln, ForkNumber forknum,
+ BlockNumber blocknum, BlockNumber nblocks);
+extern BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum);
+extern BlockNumber smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum);
+extern void smgrtruncate(SMgrRelation reln, ForkNumber *forknum,
+ int nforks, BlockNumber *nblocks);
+extern void smgrimmedsync(SMgrRelation reln, ForkNumber forknum);
+extern void AtEOXact_SMgr(void);
+extern bool ProcessBarrierSmgrRelease(void);
+
+#endif /* SMGR_H */
diff --git a/pgsql/include/server/storage/spin.h b/pgsql/include/server/storage/spin.h
new file mode 100644
index 0000000000000000000000000000000000000000..5d809cc980c392998781840b2f1cffa8967d304d
--- /dev/null
+++ b/pgsql/include/server/storage/spin.h
@@ -0,0 +1,77 @@
+/*-------------------------------------------------------------------------
+ *
+ * spin.h
+ * Hardware-independent implementation of spinlocks.
+ *
+ *
+ * The hardware-independent interface to spinlocks is defined by the
+ * typedef "slock_t" and these macros:
+ *
+ * void SpinLockInit(volatile slock_t *lock)
+ * Initialize a spinlock (to the unlocked state).
+ *
+ * void SpinLockAcquire(volatile slock_t *lock)
+ * Acquire a spinlock, waiting if necessary.
+ * Time out and abort() if unable to acquire the lock in a
+ * "reasonable" amount of time --- typically ~ 1 minute.
+ *
+ * void SpinLockRelease(volatile slock_t *lock)
+ * Unlock a previously acquired lock.
+ *
+ * bool SpinLockFree(slock_t *lock)
+ * Tests if the lock is free. Returns true if free, false if locked.
+ * This does *not* change the state of the lock.
+ *
+ * Callers must beware that the macro argument may be evaluated multiple
+ * times!
+ *
+ * Load and store operations in calling code are guaranteed not to be
+ * reordered with respect to these operations, because they include a
+ * compiler barrier. (Before PostgreSQL 9.5, callers needed to use a
+ * volatile qualifier to access data protected by spinlocks.)
+ *
+ * Keep in mind the coding rule that spinlocks must not be held for more
+ * than a few instructions. In particular, we assume it is not possible
+ * for a CHECK_FOR_INTERRUPTS() to occur while holding a spinlock, and so
+ * it is not necessary to do HOLD/RESUME_INTERRUPTS() in these macros.
+ *
+ * These macros are implemented in terms of hardware-dependent macros
+ * supplied by s_lock.h. There is not currently any extra functionality
+ * added by this header, but there has been in the past and may someday
+ * be again.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/spin.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SPIN_H
+#define SPIN_H
+
+#include "storage/s_lock.h"
+#ifndef HAVE_SPINLOCKS
+#include "storage/pg_sema.h"
+#endif
+
+
+#define SpinLockInit(lock) S_INIT_LOCK(lock)
+
+#define SpinLockAcquire(lock) S_LOCK(lock)
+
+#define SpinLockRelease(lock) S_UNLOCK(lock)
+
+#define SpinLockFree(lock) S_LOCK_FREE(lock)
+
+
+extern int SpinlockSemas(void);
+extern Size SpinlockSemaSize(void);
+
+#ifndef HAVE_SPINLOCKS
+extern void SpinlockSemaInit(void);
+extern PGDLLIMPORT PGSemaphore *SpinlockSemaArray;
+#endif
+
+#endif /* SPIN_H */
diff --git a/pgsql/include/server/storage/standby.h b/pgsql/include/server/storage/standby.h
new file mode 100644
index 0000000000000000000000000000000000000000..e8f505694912368b23e959b745d8c532a46638e5
--- /dev/null
+++ b/pgsql/include/server/storage/standby.h
@@ -0,0 +1,99 @@
+/*-------------------------------------------------------------------------
+ *
+ * standby.h
+ * Definitions for hot standby mode.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/standby.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef STANDBY_H
+#define STANDBY_H
+
+#include "datatype/timestamp.h"
+#include "storage/lock.h"
+#include "storage/procsignal.h"
+#include "storage/relfilelocator.h"
+#include "storage/standbydefs.h"
+
+/* User-settable GUC parameters */
+extern PGDLLIMPORT int max_standby_archive_delay;
+extern PGDLLIMPORT int max_standby_streaming_delay;
+extern PGDLLIMPORT bool log_recovery_conflict_waits;
+
+extern void InitRecoveryTransactionEnvironment(void);
+extern void ShutdownRecoveryTransactionEnvironment(void);
+
+extern void ResolveRecoveryConflictWithSnapshot(TransactionId snapshotConflictHorizon,
+ bool isCatalogRel,
+ RelFileLocator locator);
+extern void ResolveRecoveryConflictWithSnapshotFullXid(FullTransactionId snapshotConflictHorizon,
+ bool isCatalogRel,
+ RelFileLocator locator);
+extern void ResolveRecoveryConflictWithTablespace(Oid tsid);
+extern void ResolveRecoveryConflictWithDatabase(Oid dbid);
+
+extern void ResolveRecoveryConflictWithLock(LOCKTAG locktag, bool logging_conflict);
+extern void ResolveRecoveryConflictWithBufferPin(void);
+extern void CheckRecoveryConflictDeadlock(void);
+extern void StandbyDeadLockHandler(void);
+extern void StandbyTimeoutHandler(void);
+extern void StandbyLockTimeoutHandler(void);
+extern void LogRecoveryConflict(ProcSignalReason reason, TimestampTz wait_start,
+ TimestampTz now, VirtualTransactionId *wait_list,
+ bool still_waiting);
+
+/*
+ * Standby Rmgr (RM_STANDBY_ID)
+ *
+ * Standby recovery manager exists to perform actions that are required
+ * to make hot standby work. That includes logging AccessExclusiveLocks taken
+ * by transactions and running-xacts snapshots.
+ */
+extern void StandbyAcquireAccessExclusiveLock(TransactionId xid, Oid dbOid, Oid relOid);
+extern void StandbyReleaseLockTree(TransactionId xid,
+ int nsubxids, TransactionId *subxids);
+extern void StandbyReleaseAllLocks(void);
+extern void StandbyReleaseOldLocks(TransactionId oldxid);
+
+#define MinSizeOfXactRunningXacts offsetof(xl_running_xacts, xids)
+
+
+/*
+ * Declarations for GetRunningTransactionData(). Similar to Snapshots, but
+ * not quite. This has nothing at all to do with visibility on this server,
+ * so this is completely separate from snapmgr.c and snapmgr.h.
+ * This data is important for creating the initial snapshot state on a
+ * standby server. We need lots more information than a normal snapshot,
+ * hence we use a specific data structure for our needs. This data
+ * is written to WAL as a separate record immediately after each
+ * checkpoint. That means that wherever we start a standby from we will
+ * almost immediately see the data we need to begin executing queries.
+ */
+
+typedef struct RunningTransactionsData
+{
+ int xcnt; /* # of xact ids in xids[] */
+ int subxcnt; /* # of subxact ids in xids[] */
+ bool subxid_overflow; /* snapshot overflowed, subxids missing */
+ TransactionId nextXid; /* xid from ShmemVariableCache->nextXid */
+ TransactionId oldestRunningXid; /* *not* oldestXmin */
+ TransactionId latestCompletedXid; /* so we can set xmax */
+
+ TransactionId *xids; /* array of (sub)xids still running */
+} RunningTransactionsData;
+
+typedef RunningTransactionsData *RunningTransactions;
+
+extern void LogAccessExclusiveLock(Oid dbOid, Oid relOid);
+extern void LogAccessExclusiveLockPrepare(void);
+
+extern XLogRecPtr LogStandbySnapshot(void);
+extern void LogStandbyInvalidations(int nmsgs, SharedInvalidationMessage *msgs,
+ bool relcacheInitFileInval);
+
+#endif /* STANDBY_H */
diff --git a/pgsql/include/server/storage/standbydefs.h b/pgsql/include/server/storage/standbydefs.h
new file mode 100644
index 0000000000000000000000000000000000000000..188e348618abb582cf87028a2a569a134e8fc694
--- /dev/null
+++ b/pgsql/include/server/storage/standbydefs.h
@@ -0,0 +1,74 @@
+/*-------------------------------------------------------------------------
+ *
+ * standbydefs.h
+ * Frontend exposed definitions for hot standby mode.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/standbydefs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef STANDBYDEFS_H
+#define STANDBYDEFS_H
+
+#include "access/xlogreader.h"
+#include "lib/stringinfo.h"
+#include "storage/lockdefs.h"
+#include "storage/sinval.h"
+
+/* Recovery handlers for the Standby Rmgr (RM_STANDBY_ID) */
+extern void standby_redo(XLogReaderState *record);
+extern void standby_desc(StringInfo buf, XLogReaderState *record);
+extern const char *standby_identify(uint8 info);
+extern void standby_desc_invalidations(StringInfo buf,
+ int nmsgs, SharedInvalidationMessage *msgs,
+ Oid dbId, Oid tsId,
+ bool relcacheInitFileInval);
+
+/*
+ * XLOG message types
+ */
+#define XLOG_STANDBY_LOCK 0x00
+#define XLOG_RUNNING_XACTS 0x10
+#define XLOG_INVALIDATIONS 0x20
+
+typedef struct xl_standby_locks
+{
+ int nlocks; /* number of entries in locks array */
+ xl_standby_lock locks[FLEXIBLE_ARRAY_MEMBER];
+} xl_standby_locks;
+
+/*
+ * When we write running xact data to WAL, we use this structure.
+ */
+typedef struct xl_running_xacts
+{
+ int xcnt; /* # of xact ids in xids[] */
+ int subxcnt; /* # of subxact ids in xids[] */
+ bool subxid_overflow; /* snapshot overflowed, subxids missing */
+ TransactionId nextXid; /* xid from ShmemVariableCache->nextXid */
+ TransactionId oldestRunningXid; /* *not* oldestXmin */
+ TransactionId latestCompletedXid; /* so we can set xmax */
+
+ TransactionId xids[FLEXIBLE_ARRAY_MEMBER];
+} xl_running_xacts;
+
+/*
+ * Invalidations for standby, currently only when transactions without an
+ * assigned xid commit.
+ */
+typedef struct xl_invalidations
+{
+ Oid dbId; /* MyDatabaseId */
+ Oid tsId; /* MyDatabaseTableSpace */
+ bool relcacheInitFileInval; /* invalidate relcache init files */
+ int nmsgs; /* number of shared inval msgs */
+ SharedInvalidationMessage msgs[FLEXIBLE_ARRAY_MEMBER];
+} xl_invalidations;
+
+#define MinSizeOfInvalidations offsetof(xl_invalidations, msgs)
+
+#endif /* STANDBYDEFS_H */
diff --git a/pgsql/include/server/storage/sync.h b/pgsql/include/server/storage/sync.h
new file mode 100644
index 0000000000000000000000000000000000000000..cfbcfa6797d8381372619fd00fec5fa7ebb431e9
--- /dev/null
+++ b/pgsql/include/server/storage/sync.h
@@ -0,0 +1,66 @@
+/*-------------------------------------------------------------------------
+ *
+ * sync.h
+ * File synchronization management code.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/sync.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SYNC_H
+#define SYNC_H
+
+#include "storage/relfilelocator.h"
+
+/*
+ * Type of sync request. These are used to manage the set of pending
+ * requests to call a sync handler's sync or unlink functions at the next
+ * checkpoint.
+ */
+typedef enum SyncRequestType
+{
+ SYNC_REQUEST, /* schedule a call of sync function */
+ SYNC_UNLINK_REQUEST, /* schedule a call of unlink function */
+ SYNC_FORGET_REQUEST, /* forget all calls for a tag */
+ SYNC_FILTER_REQUEST /* forget all calls satisfying match fn */
+} SyncRequestType;
+
+/*
+ * Which set of functions to use to handle a given request. The values of
+ * the enumerators must match the indexes of the function table in sync.c.
+ */
+typedef enum SyncRequestHandler
+{
+ SYNC_HANDLER_MD = 0,
+ SYNC_HANDLER_CLOG,
+ SYNC_HANDLER_COMMIT_TS,
+ SYNC_HANDLER_MULTIXACT_OFFSET,
+ SYNC_HANDLER_MULTIXACT_MEMBER,
+ SYNC_HANDLER_NONE
+} SyncRequestHandler;
+
+/*
+ * A tag identifying a file. Currently it has the members required for md.c's
+ * usage, but sync.c has no knowledge of the internal structure, and it is
+ * liable to change as required by future handlers.
+ */
+typedef struct FileTag
+{
+ int16 handler; /* SyncRequestHandler value, saving space */
+ int16 forknum; /* ForkNumber, saving space */
+ RelFileLocator rlocator;
+ uint32 segno;
+} FileTag;
+
+extern void InitSync(void);
+extern void SyncPreCheckpoint(void);
+extern void SyncPostCheckpoint(void);
+extern void ProcessSyncRequests(void);
+extern void RememberSyncRequest(const FileTag *ftag, SyncRequestType type);
+extern bool RegisterSyncRequest(const FileTag *ftag, SyncRequestType type,
+ bool retryOnError);
+
+#endif /* SYNC_H */
diff --git a/pgsql/include/server/tcop/cmdtag.h b/pgsql/include/server/tcop/cmdtag.h
new file mode 100644
index 0000000000000000000000000000000000000000..1e7514dcff75dff052672dabf17dc67a1e2fc11c
--- /dev/null
+++ b/pgsql/include/server/tcop/cmdtag.h
@@ -0,0 +1,63 @@
+/*-------------------------------------------------------------------------
+ *
+ * cmdtag.h
+ * Declarations for commandtag names and enumeration.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/cmdtag.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef CMDTAG_H
+#define CMDTAG_H
+
+/* buffer size required for command completion tags */
+#define COMPLETION_TAG_BUFSIZE 64
+
+#define PG_CMDTAG(tag, name, evtrgok, rwrok, rowcnt) \
+ tag,
+
+typedef enum CommandTag
+{
+#include "tcop/cmdtaglist.h"
+ COMMAND_TAG_NEXTTAG
+} CommandTag;
+
+#undef PG_CMDTAG
+
+typedef struct QueryCompletion
+{
+ CommandTag commandTag;
+ uint64 nprocessed;
+} QueryCompletion;
+
+
+static inline void
+SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag,
+ uint64 nprocessed)
+{
+ qc->commandTag = commandTag;
+ qc->nprocessed = nprocessed;
+}
+
+static inline void
+CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
+{
+ dst->commandTag = src->commandTag;
+ dst->nprocessed = src->nprocessed;
+}
+
+
+extern void InitializeQueryCompletion(QueryCompletion *qc);
+extern const char *GetCommandTagName(CommandTag commandTag);
+extern const char *GetCommandTagNameAndLen(CommandTag commandTag, Size *len);
+extern bool command_tag_display_rowcount(CommandTag commandTag);
+extern bool command_tag_event_trigger_ok(CommandTag commandTag);
+extern bool command_tag_table_rewrite_ok(CommandTag commandTag);
+extern CommandTag GetCommandTagEnum(const char *commandname);
+extern Size BuildQueryCompletionString(char *buff, const QueryCompletion *qc,
+ bool nameonly);
+
+#endif /* CMDTAG_H */
diff --git a/pgsql/include/server/tcop/cmdtaglist.h b/pgsql/include/server/tcop/cmdtaglist.h
new file mode 100644
index 0000000000000000000000000000000000000000..e738ac1c097327fb54a774e35e466edc1dec1df4
--- /dev/null
+++ b/pgsql/include/server/tcop/cmdtaglist.h
@@ -0,0 +1,218 @@
+/*----------------------------------------------------------------------
+ *
+ * cmdtaglist.h
+ * Command tags
+ *
+ * The command tag list is kept in its own source file for possible use
+ * by automatic tools. The exact representation of a command tag is
+ * determined by the PG_CMDTAG macro, which is not defined in this file;
+ * it can be defined by the caller for special purposes.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/cmdtaglist.h
+ *
+ *----------------------------------------------------------------------
+ */
+
+/* there is deliberately not an #ifndef CMDTAGLIST_H here */
+
+/*
+ * List of command tags. The entries must be sorted alphabetically on their
+ * textual name, so that we can bsearch on it; see GetCommandTagEnum().
+ */
+
+/* symbol name, textual name, event_trigger_ok, table_rewrite_ok, rowcount */
+PG_CMDTAG(CMDTAG_UNKNOWN, "???", false, false, false)
+PG_CMDTAG(CMDTAG_ALTER_ACCESS_METHOD, "ALTER ACCESS METHOD", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_AGGREGATE, "ALTER AGGREGATE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_CAST, "ALTER CAST", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_COLLATION, "ALTER COLLATION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_CONSTRAINT, "ALTER CONSTRAINT", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_CONVERSION, "ALTER CONVERSION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_DATABASE, "ALTER DATABASE", false, false, false)
+PG_CMDTAG(CMDTAG_ALTER_DEFAULT_PRIVILEGES, "ALTER DEFAULT PRIVILEGES", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_DOMAIN, "ALTER DOMAIN", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_EVENT_TRIGGER, "ALTER EVENT TRIGGER", false, false, false)
+PG_CMDTAG(CMDTAG_ALTER_EXTENSION, "ALTER EXTENSION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_FOREIGN_DATA_WRAPPER, "ALTER FOREIGN DATA WRAPPER", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_FOREIGN_TABLE, "ALTER FOREIGN TABLE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_FUNCTION, "ALTER FUNCTION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_INDEX, "ALTER INDEX", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_LANGUAGE, "ALTER LANGUAGE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_LARGE_OBJECT, "ALTER LARGE OBJECT", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_MATERIALIZED_VIEW, "ALTER MATERIALIZED VIEW", true, true, false)
+PG_CMDTAG(CMDTAG_ALTER_OPERATOR, "ALTER OPERATOR", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_OPERATOR_CLASS, "ALTER OPERATOR CLASS", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_OPERATOR_FAMILY, "ALTER OPERATOR FAMILY", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_POLICY, "ALTER POLICY", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_PROCEDURE, "ALTER PROCEDURE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_PUBLICATION, "ALTER PUBLICATION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_ROLE, "ALTER ROLE", false, false, false)
+PG_CMDTAG(CMDTAG_ALTER_ROUTINE, "ALTER ROUTINE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_RULE, "ALTER RULE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_SCHEMA, "ALTER SCHEMA", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_SEQUENCE, "ALTER SEQUENCE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_SERVER, "ALTER SERVER", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_STATISTICS, "ALTER STATISTICS", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_SUBSCRIPTION, "ALTER SUBSCRIPTION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_SYSTEM, "ALTER SYSTEM", false, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TABLE, "ALTER TABLE", true, true, false)
+PG_CMDTAG(CMDTAG_ALTER_TABLESPACE, "ALTER TABLESPACE", false, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TEXT_SEARCH_CONFIGURATION, "ALTER TEXT SEARCH CONFIGURATION", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TEXT_SEARCH_DICTIONARY, "ALTER TEXT SEARCH DICTIONARY", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TEXT_SEARCH_PARSER, "ALTER TEXT SEARCH PARSER", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TEXT_SEARCH_TEMPLATE, "ALTER TEXT SEARCH TEMPLATE", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TRANSFORM, "ALTER TRANSFORM", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TRIGGER, "ALTER TRIGGER", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_TYPE, "ALTER TYPE", true, true, false)
+PG_CMDTAG(CMDTAG_ALTER_USER_MAPPING, "ALTER USER MAPPING", true, false, false)
+PG_CMDTAG(CMDTAG_ALTER_VIEW, "ALTER VIEW", true, false, false)
+PG_CMDTAG(CMDTAG_ANALYZE, "ANALYZE", false, false, false)
+PG_CMDTAG(CMDTAG_BEGIN, "BEGIN", false, false, false)
+PG_CMDTAG(CMDTAG_CALL, "CALL", false, false, false)
+PG_CMDTAG(CMDTAG_CHECKPOINT, "CHECKPOINT", false, false, false)
+PG_CMDTAG(CMDTAG_CLOSE, "CLOSE", false, false, false)
+PG_CMDTAG(CMDTAG_CLOSE_CURSOR, "CLOSE CURSOR", false, false, false)
+PG_CMDTAG(CMDTAG_CLOSE_CURSOR_ALL, "CLOSE CURSOR ALL", false, false, false)
+PG_CMDTAG(CMDTAG_CLUSTER, "CLUSTER", false, false, false)
+PG_CMDTAG(CMDTAG_COMMENT, "COMMENT", true, false, false)
+PG_CMDTAG(CMDTAG_COMMIT, "COMMIT", false, false, false)
+PG_CMDTAG(CMDTAG_COMMIT_PREPARED, "COMMIT PREPARED", false, false, false)
+PG_CMDTAG(CMDTAG_COPY, "COPY", false, false, true)
+PG_CMDTAG(CMDTAG_COPY_FROM, "COPY FROM", false, false, false)
+PG_CMDTAG(CMDTAG_CREATE_ACCESS_METHOD, "CREATE ACCESS METHOD", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_AGGREGATE, "CREATE AGGREGATE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_CAST, "CREATE CAST", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_COLLATION, "CREATE COLLATION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_CONSTRAINT, "CREATE CONSTRAINT", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_CONVERSION, "CREATE CONVERSION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_DATABASE, "CREATE DATABASE", false, false, false)
+PG_CMDTAG(CMDTAG_CREATE_DOMAIN, "CREATE DOMAIN", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_EVENT_TRIGGER, "CREATE EVENT TRIGGER", false, false, false)
+PG_CMDTAG(CMDTAG_CREATE_EXTENSION, "CREATE EXTENSION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_FOREIGN_DATA_WRAPPER, "CREATE FOREIGN DATA WRAPPER", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_FOREIGN_TABLE, "CREATE FOREIGN TABLE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_FUNCTION, "CREATE FUNCTION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_INDEX, "CREATE INDEX", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_LANGUAGE, "CREATE LANGUAGE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_MATERIALIZED_VIEW, "CREATE MATERIALIZED VIEW", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_OPERATOR, "CREATE OPERATOR", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_OPERATOR_CLASS, "CREATE OPERATOR CLASS", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_OPERATOR_FAMILY, "CREATE OPERATOR FAMILY", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_POLICY, "CREATE POLICY", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_PROCEDURE, "CREATE PROCEDURE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_PUBLICATION, "CREATE PUBLICATION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_ROLE, "CREATE ROLE", false, false, false)
+PG_CMDTAG(CMDTAG_CREATE_ROUTINE, "CREATE ROUTINE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_RULE, "CREATE RULE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_SCHEMA, "CREATE SCHEMA", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_SEQUENCE, "CREATE SEQUENCE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_SERVER, "CREATE SERVER", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_STATISTICS, "CREATE STATISTICS", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_SUBSCRIPTION, "CREATE SUBSCRIPTION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TABLE, "CREATE TABLE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TABLE_AS, "CREATE TABLE AS", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TABLESPACE, "CREATE TABLESPACE", false, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TEXT_SEARCH_CONFIGURATION, "CREATE TEXT SEARCH CONFIGURATION", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TEXT_SEARCH_DICTIONARY, "CREATE TEXT SEARCH DICTIONARY", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TEXT_SEARCH_PARSER, "CREATE TEXT SEARCH PARSER", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TEXT_SEARCH_TEMPLATE, "CREATE TEXT SEARCH TEMPLATE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TRANSFORM, "CREATE TRANSFORM", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TRIGGER, "CREATE TRIGGER", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_TYPE, "CREATE TYPE", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_USER_MAPPING, "CREATE USER MAPPING", true, false, false)
+PG_CMDTAG(CMDTAG_CREATE_VIEW, "CREATE VIEW", true, false, false)
+PG_CMDTAG(CMDTAG_DEALLOCATE, "DEALLOCATE", false, false, false)
+PG_CMDTAG(CMDTAG_DEALLOCATE_ALL, "DEALLOCATE ALL", false, false, false)
+PG_CMDTAG(CMDTAG_DECLARE_CURSOR, "DECLARE CURSOR", false, false, false)
+PG_CMDTAG(CMDTAG_DELETE, "DELETE", false, false, true)
+PG_CMDTAG(CMDTAG_DISCARD, "DISCARD", false, false, false)
+PG_CMDTAG(CMDTAG_DISCARD_ALL, "DISCARD ALL", false, false, false)
+PG_CMDTAG(CMDTAG_DISCARD_PLANS, "DISCARD PLANS", false, false, false)
+PG_CMDTAG(CMDTAG_DISCARD_SEQUENCES, "DISCARD SEQUENCES", false, false, false)
+PG_CMDTAG(CMDTAG_DISCARD_TEMP, "DISCARD TEMP", false, false, false)
+PG_CMDTAG(CMDTAG_DO, "DO", false, false, false)
+PG_CMDTAG(CMDTAG_DROP_ACCESS_METHOD, "DROP ACCESS METHOD", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_AGGREGATE, "DROP AGGREGATE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_CAST, "DROP CAST", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_COLLATION, "DROP COLLATION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_CONSTRAINT, "DROP CONSTRAINT", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_CONVERSION, "DROP CONVERSION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_DATABASE, "DROP DATABASE", false, false, false)
+PG_CMDTAG(CMDTAG_DROP_DOMAIN, "DROP DOMAIN", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_EVENT_TRIGGER, "DROP EVENT TRIGGER", false, false, false)
+PG_CMDTAG(CMDTAG_DROP_EXTENSION, "DROP EXTENSION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_FOREIGN_DATA_WRAPPER, "DROP FOREIGN DATA WRAPPER", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_FOREIGN_TABLE, "DROP FOREIGN TABLE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_FUNCTION, "DROP FUNCTION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_INDEX, "DROP INDEX", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_LANGUAGE, "DROP LANGUAGE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_MATERIALIZED_VIEW, "DROP MATERIALIZED VIEW", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_OPERATOR, "DROP OPERATOR", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_OPERATOR_CLASS, "DROP OPERATOR CLASS", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_OPERATOR_FAMILY, "DROP OPERATOR FAMILY", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_OWNED, "DROP OWNED", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_POLICY, "DROP POLICY", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_PROCEDURE, "DROP PROCEDURE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_PUBLICATION, "DROP PUBLICATION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_ROLE, "DROP ROLE", false, false, false)
+PG_CMDTAG(CMDTAG_DROP_ROUTINE, "DROP ROUTINE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_RULE, "DROP RULE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_SCHEMA, "DROP SCHEMA", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_SEQUENCE, "DROP SEQUENCE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_SERVER, "DROP SERVER", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_STATISTICS, "DROP STATISTICS", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_SUBSCRIPTION, "DROP SUBSCRIPTION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TABLE, "DROP TABLE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TABLESPACE, "DROP TABLESPACE", false, false, false)
+PG_CMDTAG(CMDTAG_DROP_TEXT_SEARCH_CONFIGURATION, "DROP TEXT SEARCH CONFIGURATION", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TEXT_SEARCH_DICTIONARY, "DROP TEXT SEARCH DICTIONARY", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TEXT_SEARCH_PARSER, "DROP TEXT SEARCH PARSER", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TEXT_SEARCH_TEMPLATE, "DROP TEXT SEARCH TEMPLATE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TRANSFORM, "DROP TRANSFORM", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TRIGGER, "DROP TRIGGER", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_TYPE, "DROP TYPE", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_USER_MAPPING, "DROP USER MAPPING", true, false, false)
+PG_CMDTAG(CMDTAG_DROP_VIEW, "DROP VIEW", true, false, false)
+PG_CMDTAG(CMDTAG_EXECUTE, "EXECUTE", false, false, false)
+PG_CMDTAG(CMDTAG_EXPLAIN, "EXPLAIN", false, false, false)
+PG_CMDTAG(CMDTAG_FETCH, "FETCH", false, false, true)
+PG_CMDTAG(CMDTAG_GRANT, "GRANT", true, false, false)
+PG_CMDTAG(CMDTAG_GRANT_ROLE, "GRANT ROLE", false, false, false)
+PG_CMDTAG(CMDTAG_IMPORT_FOREIGN_SCHEMA, "IMPORT FOREIGN SCHEMA", true, false, false)
+PG_CMDTAG(CMDTAG_INSERT, "INSERT", false, false, true)
+PG_CMDTAG(CMDTAG_LISTEN, "LISTEN", false, false, false)
+PG_CMDTAG(CMDTAG_LOAD, "LOAD", false, false, false)
+PG_CMDTAG(CMDTAG_LOCK_TABLE, "LOCK TABLE", false, false, false)
+PG_CMDTAG(CMDTAG_MERGE, "MERGE", false, false, true)
+PG_CMDTAG(CMDTAG_MOVE, "MOVE", false, false, true)
+PG_CMDTAG(CMDTAG_NOTIFY, "NOTIFY", false, false, false)
+PG_CMDTAG(CMDTAG_PREPARE, "PREPARE", false, false, false)
+PG_CMDTAG(CMDTAG_PREPARE_TRANSACTION, "PREPARE TRANSACTION", false, false, false)
+PG_CMDTAG(CMDTAG_REASSIGN_OWNED, "REASSIGN OWNED", false, false, false)
+PG_CMDTAG(CMDTAG_REFRESH_MATERIALIZED_VIEW, "REFRESH MATERIALIZED VIEW", true, false, false)
+PG_CMDTAG(CMDTAG_REINDEX, "REINDEX", false, false, false)
+PG_CMDTAG(CMDTAG_RELEASE, "RELEASE", false, false, false)
+PG_CMDTAG(CMDTAG_RESET, "RESET", false, false, false)
+PG_CMDTAG(CMDTAG_REVOKE, "REVOKE", true, false, false)
+PG_CMDTAG(CMDTAG_REVOKE_ROLE, "REVOKE ROLE", false, false, false)
+PG_CMDTAG(CMDTAG_ROLLBACK, "ROLLBACK", false, false, false)
+PG_CMDTAG(CMDTAG_ROLLBACK_PREPARED, "ROLLBACK PREPARED", false, false, false)
+PG_CMDTAG(CMDTAG_SAVEPOINT, "SAVEPOINT", false, false, false)
+PG_CMDTAG(CMDTAG_SECURITY_LABEL, "SECURITY LABEL", true, false, false)
+PG_CMDTAG(CMDTAG_SELECT, "SELECT", false, false, true)
+PG_CMDTAG(CMDTAG_SELECT_FOR_KEY_SHARE, "SELECT FOR KEY SHARE", false, false, false)
+PG_CMDTAG(CMDTAG_SELECT_FOR_NO_KEY_UPDATE, "SELECT FOR NO KEY UPDATE", false, false, false)
+PG_CMDTAG(CMDTAG_SELECT_FOR_SHARE, "SELECT FOR SHARE", false, false, false)
+PG_CMDTAG(CMDTAG_SELECT_FOR_UPDATE, "SELECT FOR UPDATE", false, false, false)
+PG_CMDTAG(CMDTAG_SELECT_INTO, "SELECT INTO", true, false, false)
+PG_CMDTAG(CMDTAG_SET, "SET", false, false, false)
+PG_CMDTAG(CMDTAG_SET_CONSTRAINTS, "SET CONSTRAINTS", false, false, false)
+PG_CMDTAG(CMDTAG_SHOW, "SHOW", false, false, false)
+PG_CMDTAG(CMDTAG_START_TRANSACTION, "START TRANSACTION", false, false, false)
+PG_CMDTAG(CMDTAG_TRUNCATE_TABLE, "TRUNCATE TABLE", false, false, false)
+PG_CMDTAG(CMDTAG_UNLISTEN, "UNLISTEN", false, false, false)
+PG_CMDTAG(CMDTAG_UPDATE, "UPDATE", false, false, true)
+PG_CMDTAG(CMDTAG_VACUUM, "VACUUM", false, false, false)
diff --git a/pgsql/include/server/tcop/deparse_utility.h b/pgsql/include/server/tcop/deparse_utility.h
new file mode 100644
index 0000000000000000000000000000000000000000..b585810b9a692779bdf0f7aff3ae47f2062d4159
--- /dev/null
+++ b/pgsql/include/server/tcop/deparse_utility.h
@@ -0,0 +1,108 @@
+/*-------------------------------------------------------------------------
+ *
+ * deparse_utility.h
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/deparse_utility.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DEPARSE_UTILITY_H
+#define DEPARSE_UTILITY_H
+
+#include "access/attnum.h"
+#include "catalog/objectaddress.h"
+#include "nodes/nodes.h"
+#include "utils/aclchk_internal.h"
+
+
+/*
+ * Support for keeping track of collected commands.
+ */
+typedef enum CollectedCommandType
+{
+ SCT_Simple,
+ SCT_AlterTable,
+ SCT_Grant,
+ SCT_AlterOpFamily,
+ SCT_AlterDefaultPrivileges,
+ SCT_CreateOpClass,
+ SCT_AlterTSConfig
+} CollectedCommandType;
+
+/*
+ * For ALTER TABLE commands, we keep a list of the subcommands therein.
+ */
+typedef struct CollectedATSubcmd
+{
+ ObjectAddress address; /* affected column, constraint, index, ... */
+ Node *parsetree;
+} CollectedATSubcmd;
+
+typedef struct CollectedCommand
+{
+ CollectedCommandType type;
+
+ bool in_extension;
+ Node *parsetree;
+
+ union
+ {
+ /* most commands */
+ struct
+ {
+ ObjectAddress address;
+ ObjectAddress secondaryObject;
+ } simple;
+
+ /* ALTER TABLE, and internal uses thereof */
+ struct
+ {
+ Oid objectId;
+ Oid classId;
+ List *subcmds;
+ } alterTable;
+
+ /* GRANT / REVOKE */
+ struct
+ {
+ InternalGrant *istmt;
+ } grant;
+
+ /* ALTER OPERATOR FAMILY */
+ struct
+ {
+ ObjectAddress address;
+ List *operators;
+ List *procedures;
+ } opfam;
+
+ /* CREATE OPERATOR CLASS */
+ struct
+ {
+ ObjectAddress address;
+ List *operators;
+ List *procedures;
+ } createopc;
+
+ /* ALTER TEXT SEARCH CONFIGURATION ADD/ALTER/DROP MAPPING */
+ struct
+ {
+ ObjectAddress address;
+ Oid *dictIds;
+ int ndicts;
+ } atscfg;
+
+ /* ALTER DEFAULT PRIVILEGES */
+ struct
+ {
+ ObjectType objtype;
+ } defprivs;
+ } d;
+
+ struct CollectedCommand *parent; /* when nested */
+} CollectedCommand;
+
+#endif /* DEPARSE_UTILITY_H */
diff --git a/pgsql/include/server/tcop/dest.h b/pgsql/include/server/tcop/dest.h
new file mode 100644
index 0000000000000000000000000000000000000000..a7d86e7abd4d0de6d7ceda1481e4ecad7435be2d
--- /dev/null
+++ b/pgsql/include/server/tcop/dest.h
@@ -0,0 +1,147 @@
+/*-------------------------------------------------------------------------
+ *
+ * dest.h
+ * support for communication destinations
+ *
+ * Whenever the backend executes a query that returns tuples, the results
+ * have to go someplace. For example:
+ *
+ * - stdout is the destination only when we are running a
+ * standalone backend (no postmaster) and are returning results
+ * back to an interactive user.
+ *
+ * - a remote process is the destination when we are
+ * running a backend with a frontend and the frontend executes
+ * PQexec() or PQfn(). In this case, the results are sent
+ * to the frontend via the functions in backend/libpq.
+ *
+ * - DestNone is the destination when the system executes
+ * a query internally. The results are discarded.
+ *
+ * dest.c defines three functions that implement destination management:
+ *
+ * BeginCommand: initialize the destination at start of command.
+ * CreateDestReceiver: return a pointer to a struct of destination-specific
+ * receiver functions.
+ * EndCommand: clean up the destination at end of command.
+ *
+ * BeginCommand/EndCommand are executed once per received SQL query.
+ *
+ * CreateDestReceiver returns a receiver object appropriate to the specified
+ * destination. The executor, as well as utility statements that can return
+ * tuples, are passed the resulting DestReceiver* pointer. Each executor run
+ * or utility execution calls the receiver's rStartup method, then the
+ * receiveSlot method (zero or more times), then the rShutdown method.
+ * The same receiver object may be re-used multiple times; eventually it is
+ * destroyed by calling its rDestroy method.
+ *
+ * In some cases, receiver objects require additional parameters that must
+ * be passed to them after calling CreateDestReceiver. Since the set of
+ * parameters varies for different receiver types, this is not handled by
+ * this module, but by direct calls from the calling code to receiver type
+ * specific functions.
+ *
+ * The DestReceiver object returned by CreateDestReceiver may be a statically
+ * allocated object (for destination types that require no local state),
+ * in which case rDestroy is a no-op. Alternatively it can be a palloc'd
+ * object that has DestReceiver as its first field and contains additional
+ * fields (see printtup.c for an example). These additional fields are then
+ * accessible to the DestReceiver functions by casting the DestReceiver*
+ * pointer passed to them. The palloc'd object is pfree'd by the rDestroy
+ * method. Note that the caller of CreateDestReceiver should take care to
+ * do so in a memory context that is long-lived enough for the receiver
+ * object not to disappear while still needed.
+ *
+ * Special provision: None_Receiver is a permanently available receiver
+ * object for the DestNone destination. This avoids useless creation/destroy
+ * calls in portal and cursor manipulations.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/dest.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DEST_H
+#define DEST_H
+
+#include "executor/tuptable.h"
+#include "tcop/cmdtag.h"
+
+
+
+
+/* ----------------
+ * CommandDest is a simplistic means of identifying the desired
+ * destination. Someday this will probably need to be improved.
+ *
+ * Note: only the values DestNone, DestDebug, DestRemote are legal for the
+ * global variable whereToSendOutput. The other values may be used
+ * as the destination for individual commands.
+ * ----------------
+ */
+typedef enum
+{
+ DestNone, /* results are discarded */
+ DestDebug, /* results go to debugging output */
+ DestRemote, /* results sent to frontend process */
+ DestRemoteExecute, /* sent to frontend, in Execute command */
+ DestRemoteSimple, /* sent to frontend, w/no catalog access */
+ DestSPI, /* results sent to SPI manager */
+ DestTuplestore, /* results sent to Tuplestore */
+ DestIntoRel, /* results sent to relation (SELECT INTO) */
+ DestCopyOut, /* results sent to COPY TO code */
+ DestSQLFunction, /* results sent to SQL-language func mgr */
+ DestTransientRel, /* results sent to transient relation */
+ DestTupleQueue /* results sent to tuple queue */
+} CommandDest;
+
+/* ----------------
+ * DestReceiver is a base type for destination-specific local state.
+ * In the simplest cases, there is no state info, just the function
+ * pointers that the executor must call.
+ *
+ * Note: the receiveSlot routine must be passed a slot containing a TupleDesc
+ * identical to the one given to the rStartup routine. It returns bool where
+ * a "true" value means "continue processing" and a "false" value means
+ * "stop early, just as if we'd reached the end of the scan".
+ * ----------------
+ */
+typedef struct _DestReceiver DestReceiver;
+
+struct _DestReceiver
+{
+ /* Called for each tuple to be output: */
+ bool (*receiveSlot) (TupleTableSlot *slot,
+ DestReceiver *self);
+ /* Per-executor-run initialization and shutdown: */
+ void (*rStartup) (DestReceiver *self,
+ int operation,
+ TupleDesc typeinfo);
+ void (*rShutdown) (DestReceiver *self);
+ /* Destroy the receiver object itself (if dynamically allocated) */
+ void (*rDestroy) (DestReceiver *self);
+ /* CommandDest code for this receiver */
+ CommandDest mydest;
+ /* Private fields might appear beyond this point... */
+};
+
+extern PGDLLIMPORT DestReceiver *None_Receiver; /* permanent receiver for
+ * DestNone */
+
+/* The primary destination management functions */
+
+extern void BeginCommand(CommandTag commandTag, CommandDest dest);
+extern DestReceiver *CreateDestReceiver(CommandDest dest);
+extern void EndCommand(const QueryCompletion *qc, CommandDest dest,
+ bool force_undecorated_output);
+extern void EndReplicationCommand(const char *commandTag);
+
+/* Additional functions that go with destination management, more or less. */
+
+extern void NullCommand(CommandDest dest);
+extern void ReadyForQuery(CommandDest dest);
+
+#endif /* DEST_H */
diff --git a/pgsql/include/server/tcop/fastpath.h b/pgsql/include/server/tcop/fastpath.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d57f79def9d01f4c44d04e2ad4e91a627dd21be
--- /dev/null
+++ b/pgsql/include/server/tcop/fastpath.h
@@ -0,0 +1,20 @@
+/*-------------------------------------------------------------------------
+ *
+ * fastpath.h
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/fastpath.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FASTPATH_H
+#define FASTPATH_H
+
+#include "lib/stringinfo.h"
+
+extern void HandleFunctionRequest(StringInfo msgBuf);
+
+#endif /* FASTPATH_H */
diff --git a/pgsql/include/server/tcop/pquery.h b/pgsql/include/server/tcop/pquery.h
new file mode 100644
index 0000000000000000000000000000000000000000..a5e65b98aa30b7072cd975b8f4cc901accabfbe1
--- /dev/null
+++ b/pgsql/include/server/tcop/pquery.h
@@ -0,0 +1,51 @@
+/*-------------------------------------------------------------------------
+ *
+ * pquery.h
+ * prototypes for pquery.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/pquery.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PQUERY_H
+#define PQUERY_H
+
+#include "nodes/parsenodes.h"
+#include "utils/portal.h"
+
+struct PlannedStmt; /* avoid including plannodes.h here */
+
+
+extern PGDLLIMPORT Portal ActivePortal;
+
+
+extern PortalStrategy ChoosePortalStrategy(List *stmts);
+
+extern List *FetchPortalTargetList(Portal portal);
+
+extern List *FetchStatementTargetList(Node *stmt);
+
+extern void PortalStart(Portal portal, ParamListInfo params,
+ int eflags, Snapshot snapshot);
+
+extern void PortalSetResultFormat(Portal portal, int nFormats,
+ int16 *formats);
+
+extern bool PortalRun(Portal portal, long count, bool isTopLevel,
+ bool run_once, DestReceiver *dest, DestReceiver *altdest,
+ QueryCompletion *qc);
+
+extern uint64 PortalRunFetch(Portal portal,
+ FetchDirection fdirection,
+ long count,
+ DestReceiver *dest);
+
+extern bool PlannedStmtRequiresSnapshot(struct PlannedStmt *pstmt);
+
+extern void EnsurePortalSnapshotExists(void);
+
+#endif /* PQUERY_H */
diff --git a/pgsql/include/server/tcop/tcopprot.h b/pgsql/include/server/tcop/tcopprot.h
new file mode 100644
index 0000000000000000000000000000000000000000..abd7b4fff33dd157b0d1fc4460154c3d8d97a48b
--- /dev/null
+++ b/pgsql/include/server/tcop/tcopprot.h
@@ -0,0 +1,94 @@
+/*-------------------------------------------------------------------------
+ *
+ * tcopprot.h
+ * prototypes for postgres.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/tcopprot.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TCOPPROT_H
+#define TCOPPROT_H
+
+#include "nodes/params.h"
+#include "nodes/parsenodes.h"
+#include "nodes/plannodes.h"
+#include "storage/procsignal.h"
+#include "utils/guc.h"
+#include "utils/queryenvironment.h"
+
+
+/* Required daylight between max_stack_depth and the kernel limit, in bytes */
+#define STACK_DEPTH_SLOP (512 * 1024L)
+
+extern PGDLLIMPORT CommandDest whereToSendOutput;
+extern PGDLLIMPORT const char *debug_query_string;
+extern PGDLLIMPORT int max_stack_depth;
+extern PGDLLIMPORT int PostAuthDelay;
+extern PGDLLIMPORT int client_connection_check_interval;
+
+/* GUC-configurable parameters */
+
+typedef enum
+{
+ LOGSTMT_NONE, /* log no statements */
+ LOGSTMT_DDL, /* log data definition statements */
+ LOGSTMT_MOD, /* log modification statements, plus DDL */
+ LOGSTMT_ALL /* log all statements */
+} LogStmtLevel;
+
+extern PGDLLIMPORT int log_statement;
+
+extern List *pg_parse_query(const char *query_string);
+extern List *pg_rewrite_query(Query *query);
+extern List *pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree,
+ const char *query_string,
+ const Oid *paramTypes, int numParams,
+ QueryEnvironment *queryEnv);
+extern List *pg_analyze_and_rewrite_varparams(RawStmt *parsetree,
+ const char *query_string,
+ Oid **paramTypes,
+ int *numParams,
+ QueryEnvironment *queryEnv);
+extern List *pg_analyze_and_rewrite_withcb(RawStmt *parsetree,
+ const char *query_string,
+ ParserSetupHook parserSetup,
+ void *parserSetupArg,
+ QueryEnvironment *queryEnv);
+extern PlannedStmt *pg_plan_query(Query *querytree, const char *query_string,
+ int cursorOptions,
+ ParamListInfo boundParams);
+extern List *pg_plan_queries(List *querytrees, const char *query_string,
+ int cursorOptions,
+ ParamListInfo boundParams);
+
+extern void die(SIGNAL_ARGS);
+extern void quickdie(SIGNAL_ARGS) pg_attribute_noreturn();
+extern void StatementCancelHandler(SIGNAL_ARGS);
+extern void FloatExceptionHandler(SIGNAL_ARGS) pg_attribute_noreturn();
+extern void RecoveryConflictInterrupt(ProcSignalReason reason); /* called from SIGUSR1
+ * handler */
+extern void ProcessClientReadInterrupt(bool blocked);
+extern void ProcessClientWriteInterrupt(bool blocked);
+
+extern void process_postgres_switches(int argc, char *argv[],
+ GucContext ctx, const char **dbname);
+extern void PostgresSingleUserMain(int argc, char *argv[],
+ const char *username) pg_attribute_noreturn();
+extern void PostgresMain(const char *dbname,
+ const char *username) pg_attribute_noreturn();
+extern long get_stack_depth_rlimit(void);
+extern void ResetUsage(void);
+extern void ShowUsage(const char *title);
+extern int check_log_duration(char *msec_str, bool was_logged);
+extern void set_debug_options(int debug_flag,
+ GucContext context, GucSource source);
+extern bool set_plan_disabling_options(const char *arg,
+ GucContext context, GucSource source);
+extern const char *get_stats_option_name(const char *arg);
+
+#endif /* TCOPPROT_H */
diff --git a/pgsql/include/server/tcop/utility.h b/pgsql/include/server/tcop/utility.h
new file mode 100644
index 0000000000000000000000000000000000000000..59e64aea07355afe7b0896f252e8ad4b8fd77c8d
--- /dev/null
+++ b/pgsql/include/server/tcop/utility.h
@@ -0,0 +1,112 @@
+/*-------------------------------------------------------------------------
+ *
+ * utility.h
+ * prototypes for utility.c.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tcop/utility.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef UTILITY_H
+#define UTILITY_H
+
+#include "tcop/cmdtag.h"
+#include "tcop/tcopprot.h"
+
+typedef enum
+{
+ PROCESS_UTILITY_TOPLEVEL, /* toplevel interactive command */
+ PROCESS_UTILITY_QUERY, /* a complete query, but not toplevel */
+ PROCESS_UTILITY_QUERY_NONATOMIC, /* a complete query, nonatomic
+ * execution context */
+ PROCESS_UTILITY_SUBCOMMAND /* a portion of a query */
+} ProcessUtilityContext;
+
+/* Info needed when recursing from ALTER TABLE */
+typedef struct AlterTableUtilityContext
+{
+ PlannedStmt *pstmt; /* PlannedStmt for outer ALTER TABLE command */
+ const char *queryString; /* its query string */
+ Oid relid; /* OID of ALTER's target table */
+ ParamListInfo params; /* any parameters available to ALTER TABLE */
+ QueryEnvironment *queryEnv; /* execution environment for ALTER TABLE */
+} AlterTableUtilityContext;
+
+/*
+ * These constants are used to describe the extent to which a particular
+ * command is read-only.
+ *
+ * COMMAND_OK_IN_READ_ONLY_TXN means that the command is permissible even when
+ * XactReadOnly is set. This bit should be set for commands that don't change
+ * the state of the database (data or schema) in a way that would affect the
+ * output of pg_dump.
+ *
+ * COMMAND_OK_IN_PARALLEL_MODE means that the command is permissible even
+ * when in parallel mode. Writing tuples is forbidden, as is anything that
+ * might confuse cooperating processes.
+ *
+ * COMMAND_OK_IN_RECOVERY means that the command is permissible even when in
+ * recovery. It can't write WAL, nor can it do things that would imperil
+ * replay of future WAL received from the primary.
+ */
+#define COMMAND_OK_IN_READ_ONLY_TXN 0x0001
+#define COMMAND_OK_IN_PARALLEL_MODE 0x0002
+#define COMMAND_OK_IN_RECOVERY 0x0004
+
+/*
+ * We say that a command is strictly read-only if it is sufficiently read-only
+ * for all purposes. For clarity, we also have a constant for commands that are
+ * in no way read-only.
+ */
+#define COMMAND_IS_STRICTLY_READ_ONLY \
+ (COMMAND_OK_IN_READ_ONLY_TXN | COMMAND_OK_IN_RECOVERY | \
+ COMMAND_OK_IN_PARALLEL_MODE)
+#define COMMAND_IS_NOT_READ_ONLY 0
+
+/* Hook for plugins to get control in ProcessUtility() */
+typedef void (*ProcessUtility_hook_type) (PlannedStmt *pstmt,
+ const char *queryString,
+ bool readOnlyTree,
+ ProcessUtilityContext context,
+ ParamListInfo params,
+ QueryEnvironment *queryEnv,
+ DestReceiver *dest, QueryCompletion *qc);
+extern PGDLLIMPORT ProcessUtility_hook_type ProcessUtility_hook;
+
+extern void ProcessUtility(PlannedStmt *pstmt, const char *queryString,
+ bool readOnlyTree,
+ ProcessUtilityContext context, ParamListInfo params,
+ QueryEnvironment *queryEnv,
+ DestReceiver *dest, QueryCompletion *qc);
+extern void standard_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
+ bool readOnlyTree,
+ ProcessUtilityContext context, ParamListInfo params,
+ QueryEnvironment *queryEnv,
+ DestReceiver *dest, QueryCompletion *qc);
+
+extern void ProcessUtilityForAlterTable(Node *stmt,
+ AlterTableUtilityContext *context);
+
+extern bool UtilityReturnsTuples(Node *parsetree);
+
+extern TupleDesc UtilityTupleDescriptor(Node *parsetree);
+
+extern Query *UtilityContainsQuery(Node *parsetree);
+
+extern CommandTag CreateCommandTag(Node *parsetree);
+
+static inline const char *
+CreateCommandName(Node *parsetree)
+{
+ return GetCommandTagName(CreateCommandTag(parsetree));
+}
+
+extern LogStmtLevel GetCommandLogLevel(Node *parsetree);
+
+extern bool CommandIsReadOnly(PlannedStmt *pstmt);
+
+#endif /* UTILITY_H */
diff --git a/pgsql/include/server/tsearch/dicts/regis.h b/pgsql/include/server/tsearch/dicts/regis.h
new file mode 100644
index 0000000000000000000000000000000000000000..0b81729128776a4a0187def21b5484f5e6107e96
--- /dev/null
+++ b/pgsql/include/server/tsearch/dicts/regis.h
@@ -0,0 +1,49 @@
+/*-------------------------------------------------------------------------
+ *
+ * regis.h
+ *
+ * Declarations for fast regex subset, used by ISpell
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/tsearch/dicts/regis.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef __REGIS_H__
+#define __REGIS_H__
+
+typedef struct RegisNode
+{
+ uint32
+ type:2,
+ len:16,
+ unused:14;
+ struct RegisNode *next;
+ unsigned char data[FLEXIBLE_ARRAY_MEMBER];
+} RegisNode;
+
+#define RNHDRSZ (offsetof(RegisNode,data))
+
+#define RSF_ONEOF 1
+#define RSF_NONEOF 2
+
+typedef struct Regis
+{
+ RegisNode *node;
+ uint32
+ issuffix:1,
+ nchar:16,
+ unused:15;
+} Regis;
+
+extern bool RS_isRegis(const char *str);
+
+extern void RS_compile(Regis *r, bool issuffix, const char *str);
+extern void RS_free(Regis *r);
+
+/*returns true if matches */
+extern bool RS_execute(Regis *r, char *str);
+
+#endif
diff --git a/pgsql/include/server/tsearch/dicts/spell.h b/pgsql/include/server/tsearch/dicts/spell.h
new file mode 100644
index 0000000000000000000000000000000000000000..0763f9ffe7b04ba19f92c8c51140c745d7f8b0c7
--- /dev/null
+++ b/pgsql/include/server/tsearch/dicts/spell.h
@@ -0,0 +1,241 @@
+/*-------------------------------------------------------------------------
+ *
+ * spell.h
+ *
+ * Declarations for ISpell dictionary
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/tsearch/dicts/spell.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef __SPELL_H__
+#define __SPELL_H__
+
+#include "regex/regex.h"
+#include "tsearch/dicts/regis.h"
+#include "tsearch/ts_public.h"
+
+/*
+ * SPNode and SPNodeData are used to represent prefix tree (Trie) to store
+ * a words list.
+ */
+struct SPNode;
+
+typedef struct
+{
+ uint32 val:8,
+ isword:1,
+ /* Stores compound flags listed below */
+ compoundflag:4,
+ /* Reference to an entry of the AffixData field */
+ affix:19;
+ struct SPNode *node;
+} SPNodeData;
+
+/*
+ * Names of FF_ are correlated with Hunspell options in affix file
+ * https://hunspell.github.io/
+ */
+#define FF_COMPOUNDONLY 0x01
+#define FF_COMPOUNDBEGIN 0x02
+#define FF_COMPOUNDMIDDLE 0x04
+#define FF_COMPOUNDLAST 0x08
+#define FF_COMPOUNDFLAG ( FF_COMPOUNDBEGIN | FF_COMPOUNDMIDDLE | \
+ FF_COMPOUNDLAST )
+#define FF_COMPOUNDFLAGMASK 0x0f
+
+typedef struct SPNode
+{
+ uint32 length;
+ SPNodeData data[FLEXIBLE_ARRAY_MEMBER];
+} SPNode;
+
+#define SPNHDRSZ (offsetof(SPNode,data))
+
+/*
+ * Represents an entry in a words list.
+ */
+typedef struct spell_struct
+{
+ union
+ {
+ /*
+ * flag is filled in by NIImportDictionary(). After
+ * NISortDictionary(), d is used instead of flag.
+ */
+ char *flag;
+ /* d is used in mkSPNode() */
+ struct
+ {
+ /* Reference to an entry of the AffixData field */
+ int affix;
+ /* Length of the word */
+ int len;
+ } d;
+ } p;
+ char word[FLEXIBLE_ARRAY_MEMBER];
+} SPELL;
+
+#define SPELLHDRSZ (offsetof(SPELL, word))
+
+/*
+ * Represents an entry in an affix list.
+ */
+typedef struct aff_struct
+{
+ char *flag;
+ /* FF_SUFFIX or FF_PREFIX */
+ uint32 type:1,
+ flagflags:7,
+ issimple:1,
+ isregis:1,
+ replen:14;
+ char *find;
+ char *repl;
+ union
+ {
+ /*
+ * Arrays of AFFIX are moved and sorted. We'll use a pointer to
+ * regex_t to keep this struct small, and avoid assuming that regex_t
+ * is movable.
+ */
+ regex_t *pregex;
+ Regis regis;
+ } reg;
+} AFFIX;
+
+/*
+ * affixes use dictionary flags too
+ */
+#define FF_COMPOUNDPERMITFLAG 0x10
+#define FF_COMPOUNDFORBIDFLAG 0x20
+#define FF_CROSSPRODUCT 0x40
+
+/*
+ * Don't change the order of these. Initialization sorts by these,
+ * and expects prefixes to come first after sorting.
+ */
+#define FF_SUFFIX 1
+#define FF_PREFIX 0
+
+/*
+ * AffixNode and AffixNodeData are used to represent prefix tree (Trie) to store
+ * an affix list.
+ */
+struct AffixNode;
+
+typedef struct
+{
+ uint32 val:8,
+ naff:24;
+ AFFIX **aff;
+ struct AffixNode *node;
+} AffixNodeData;
+
+typedef struct AffixNode
+{
+ uint32 isvoid:1,
+ length:31;
+ AffixNodeData data[FLEXIBLE_ARRAY_MEMBER];
+} AffixNode;
+
+#define ANHRDSZ (offsetof(AffixNode, data))
+
+typedef struct
+{
+ char *affix;
+ int len;
+ bool issuffix;
+} CMPDAffix;
+
+/*
+ * Type of encoding affix flags in Hunspell dictionaries
+ */
+typedef enum
+{
+ FM_CHAR, /* one character (like ispell) */
+ FM_LONG, /* two characters */
+ FM_NUM /* number, >= 0 and < 65536 */
+} FlagMode;
+
+/*
+ * Structure to store Hunspell options. Flag representation depends on flag
+ * type. These flags are about support of compound words.
+ */
+typedef struct CompoundAffixFlag
+{
+ union
+ {
+ /* Flag name if flagMode is FM_CHAR or FM_LONG */
+ char *s;
+ /* Flag name if flagMode is FM_NUM */
+ uint32 i;
+ } flag;
+ /* we don't have a bsearch_arg version, so, copy FlagMode */
+ FlagMode flagMode;
+ uint32 value;
+} CompoundAffixFlag;
+
+#define FLAGNUM_MAXSIZE (1 << 16)
+
+typedef struct
+{
+ int maffixes;
+ int naffixes;
+ AFFIX *Affix;
+
+ AffixNode *Suffix;
+ AffixNode *Prefix;
+
+ SPNode *Dictionary;
+ /* Array of sets of affixes */
+ char **AffixData;
+ int lenAffixData;
+ int nAffixData;
+ bool useFlagAliases;
+
+ CMPDAffix *CompoundAffix;
+
+ bool usecompound;
+ FlagMode flagMode;
+
+ /*
+ * All follow fields are actually needed only for initialization
+ */
+
+ /* Array of Hunspell options in affix file */
+ CompoundAffixFlag *CompoundAffixFlags;
+ /* number of entries in CompoundAffixFlags array */
+ int nCompoundAffixFlag;
+ /* allocated length of CompoundAffixFlags array */
+ int mCompoundAffixFlag;
+
+ /*
+ * Remaining fields are only used during dictionary construction; they are
+ * set up by NIStartBuild and cleared by NIFinishBuild.
+ */
+ MemoryContext buildCxt; /* temp context for construction */
+
+ /* Temporary array of all words in the dict file */
+ SPELL **Spell;
+ int nspell; /* number of valid entries in Spell array */
+ int mspell; /* allocated length of Spell array */
+
+ /* These are used to allocate "compact" data without palloc overhead */
+ char *firstfree; /* first free address (always maxaligned) */
+ size_t avail; /* free space remaining at firstfree */
+} IspellDict;
+
+extern TSLexeme *NINormalizeWord(IspellDict *Conf, char *word);
+
+extern void NIStartBuild(IspellDict *Conf);
+extern void NIImportAffixes(IspellDict *Conf, const char *filename);
+extern void NIImportDictionary(IspellDict *Conf, const char *filename);
+extern void NISortDictionary(IspellDict *Conf);
+extern void NISortAffixes(IspellDict *Conf);
+extern void NIFinishBuild(IspellDict *Conf);
+
+#endif
diff --git a/pgsql/include/server/tsearch/ts_cache.h b/pgsql/include/server/tsearch/ts_cache.h
new file mode 100644
index 0000000000000000000000000000000000000000..d432bd0ace4c0cd1038dbae36735f219feadbdce
--- /dev/null
+++ b/pgsql/include/server/tsearch/ts_cache.h
@@ -0,0 +1,96 @@
+/*-------------------------------------------------------------------------
+ *
+ * ts_cache.h
+ * Tsearch related object caches.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/tsearch/ts_cache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TS_CACHE_H
+#define TS_CACHE_H
+
+#include "fmgr.h"
+
+
+/*
+ * All TS*CacheEntry structs must share this common header
+ * (see InvalidateTSCacheCallBack)
+ */
+typedef struct TSAnyCacheEntry
+{
+ Oid objId;
+ bool isvalid;
+} TSAnyCacheEntry;
+
+
+typedef struct TSParserCacheEntry
+{
+ /* prsId is the hash lookup key and MUST BE FIRST */
+ Oid prsId; /* OID of the parser */
+ bool isvalid;
+
+ Oid startOid;
+ Oid tokenOid;
+ Oid endOid;
+ Oid headlineOid;
+ Oid lextypeOid;
+
+ /*
+ * Pre-set-up fmgr call of most needed parser's methods
+ */
+ FmgrInfo prsstart;
+ FmgrInfo prstoken;
+ FmgrInfo prsend;
+ FmgrInfo prsheadline;
+} TSParserCacheEntry;
+
+typedef struct TSDictionaryCacheEntry
+{
+ /* dictId is the hash lookup key and MUST BE FIRST */
+ Oid dictId;
+ bool isvalid;
+
+ /* most frequent fmgr call */
+ Oid lexizeOid;
+ FmgrInfo lexize;
+
+ MemoryContext dictCtx; /* memory context to store private data */
+ void *dictData;
+} TSDictionaryCacheEntry;
+
+typedef struct
+{
+ int len;
+ Oid *dictIds;
+} ListDictionary;
+
+typedef struct
+{
+ /* cfgId is the hash lookup key and MUST BE FIRST */
+ Oid cfgId;
+ bool isvalid;
+
+ Oid prsId;
+
+ int lenmap;
+ ListDictionary *map;
+} TSConfigCacheEntry;
+
+
+/*
+ * GUC variable for current configuration
+ */
+extern PGDLLIMPORT char *TSCurrentConfig;
+
+
+extern TSParserCacheEntry *lookup_ts_parser_cache(Oid prsId);
+extern TSDictionaryCacheEntry *lookup_ts_dictionary_cache(Oid dictId);
+extern TSConfigCacheEntry *lookup_ts_config_cache(Oid cfgId);
+
+extern Oid getTSCurrentConfig(bool emitError);
+
+#endif /* TS_CACHE_H */
diff --git a/pgsql/include/server/tsearch/ts_locale.h b/pgsql/include/server/tsearch/ts_locale.h
new file mode 100644
index 0000000000000000000000000000000000000000..58d594d400698ec86ec324ba4fbb0fc406ca6846
--- /dev/null
+++ b/pgsql/include/server/tsearch/ts_locale.h
@@ -0,0 +1,56 @@
+/*-------------------------------------------------------------------------
+ *
+ * ts_locale.h
+ * locale compatibility layer for tsearch
+ *
+ * Copyright (c) 1998-2023, PostgreSQL Global Development Group
+ *
+ * src/include/tsearch/ts_locale.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef __TSLOCALE_H__
+#define __TSLOCALE_H__
+
+#include
+#include
+#include
+
+#include "lib/stringinfo.h"
+#include "mb/pg_wchar.h"
+#include "utils/pg_locale.h"
+
+/* working state for tsearch_readline (should be a local var in caller) */
+typedef struct
+{
+ FILE *fp;
+ const char *filename;
+ int lineno;
+ StringInfoData buf; /* current input line, in UTF-8 */
+ char *curline; /* current input line, in DB's encoding */
+ /* curline may be NULL, or equal to buf.data, or a palloc'd string */
+ ErrorContextCallback cb;
+} tsearch_readline_state;
+
+#define TOUCHAR(x) (*((const unsigned char *) (x)))
+
+/* The second argument of t_iseq() must be a plain ASCII character */
+#define t_iseq(x,c) (TOUCHAR(x) == (unsigned char) (c))
+
+#define COPYCHAR(d,s) memcpy(d, s, pg_mblen(s))
+
+extern int t_isdigit(const char *ptr);
+extern int t_isspace(const char *ptr);
+extern int t_isalpha(const char *ptr);
+extern int t_isalnum(const char *ptr);
+extern int t_isprint(const char *ptr);
+
+extern char *lowerstr(const char *str);
+extern char *lowerstr_with_len(const char *str, int len);
+
+extern bool tsearch_readline_begin(tsearch_readline_state *stp,
+ const char *filename);
+extern char *tsearch_readline(tsearch_readline_state *stp);
+extern void tsearch_readline_end(tsearch_readline_state *stp);
+
+#endif /* __TSLOCALE_H__ */
diff --git a/pgsql/include/server/tsearch/ts_public.h b/pgsql/include/server/tsearch/ts_public.h
new file mode 100644
index 0000000000000000000000000000000000000000..0c9bc1498efa284601dec5f42545d183b7344f25
--- /dev/null
+++ b/pgsql/include/server/tsearch/ts_public.h
@@ -0,0 +1,159 @@
+/*-------------------------------------------------------------------------
+ *
+ * ts_public.h
+ * Public interface to various tsearch modules, such as
+ * parsers and dictionaries.
+ *
+ * Copyright (c) 1998-2023, PostgreSQL Global Development Group
+ *
+ * src/include/tsearch/ts_public.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PG_TS_PUBLIC_H_
+#define _PG_TS_PUBLIC_H_
+
+#include "tsearch/ts_type.h"
+
+/*
+ * Parser's framework
+ */
+
+/*
+ * returning type for prslextype method of parser
+ */
+typedef struct
+{
+ int lexid;
+ char *alias;
+ char *descr;
+} LexDescr;
+
+/*
+ * Interface to headline generator (tsparser's prsheadline function)
+ *
+ * HeadlineParsedText describes the text that is to be highlighted.
+ * Some fields are passed from the core code to the prsheadline function,
+ * while others are output from the prsheadline function.
+ *
+ * The principal data is words[], an array of HeadlineWordEntry,
+ * one entry per token, of length curwords.
+ * The fields of HeadlineWordEntry are:
+ *
+ * in, selected, replace, skip: these flags are initially zero
+ * and may be set by the prsheadline function. A consecutive group
+ * of tokens marked "in" form a "fragment" to be output.
+ * Such tokens may additionally be marked selected, replace, or skip
+ * to modify how they are shown. (If you set more than one of those
+ * bits, you get an unspecified one of those behaviors.)
+ *
+ * type, len, pos, word: filled by core code to describe the token.
+ *
+ * item: if the token matches any operand of the tsquery of interest,
+ * a pointer to such an operand. (If there are multiple matching
+ * operands, we generate extra copies of the HeadlineWordEntry to hold
+ * all the pointers. The extras are marked with repeated = 1 and should
+ * be ignored except for checking the item pointer.)
+ */
+typedef struct
+{
+ uint32 selected:1, /* token is to be highlighted */
+ in:1, /* token is part of headline */
+ replace:1, /* token is to be replaced with a space */
+ repeated:1, /* duplicate entry to hold item pointer */
+ skip:1, /* token is to be skipped (not output) */
+ unused:3, /* available bits */
+ type:8, /* parser's token category */
+ len:16; /* length of token */
+ WordEntryPos pos; /* position of token */
+ char *word; /* text of token (not null-terminated) */
+ QueryOperand *item; /* a matching query operand, or NULL if none */
+} HeadlineWordEntry;
+
+typedef struct
+{
+ /* Fields filled by core code before calling prsheadline function: */
+ HeadlineWordEntry *words;
+ int32 lenwords; /* allocated length of words[] */
+ int32 curwords; /* current number of valid entries */
+ int32 vectorpos; /* used by ts_parse.c in filling pos fields */
+
+ /* The prsheadline function must fill these fields: */
+ /* Strings for marking selected tokens and separating fragments: */
+ char *startsel; /* palloc'd strings */
+ char *stopsel;
+ char *fragdelim;
+ int16 startsellen; /* lengths of strings */
+ int16 stopsellen;
+ int16 fragdelimlen;
+} HeadlineParsedText;
+
+/*
+ * Common useful things for tsearch subsystem
+ */
+extern char *get_tsearch_config_filename(const char *basename,
+ const char *extension);
+
+/*
+ * Often useful stopword list management
+ */
+typedef struct
+{
+ int len;
+ char **stop;
+} StopList;
+
+extern void readstoplist(const char *fname, StopList *s,
+ char *(*wordop) (const char *));
+extern bool searchstoplist(StopList *s, char *key);
+
+/*
+ * Interface with dictionaries
+ */
+
+/* return struct for any lexize function */
+typedef struct
+{
+ /*----------
+ * Number of current variant of split word. For example the Norwegian
+ * word 'fotballklubber' has two variants to split: ( fotball, klubb )
+ * and ( fot, ball, klubb ). So, dictionary should return:
+ *
+ * nvariant lexeme
+ * 1 fotball
+ * 1 klubb
+ * 2 fot
+ * 2 ball
+ * 2 klubb
+ *
+ * In general, a TSLexeme will be considered to belong to the same split
+ * variant as the previous one if they have the same nvariant value.
+ * The exact values don't matter, only changes from one lexeme to next.
+ *----------
+ */
+ uint16 nvariant;
+
+ uint16 flags; /* See flag bits below */
+
+ char *lexeme; /* C string */
+} TSLexeme;
+
+/* Flag bits that can appear in TSLexeme.flags */
+#define TSL_ADDPOS 0x01
+#define TSL_PREFIX 0x02
+#define TSL_FILTER 0x04
+
+/*
+ * Struct for supporting complex dictionaries like thesaurus.
+ * 4th argument for dictlexize method is a pointer to this
+ */
+typedef struct
+{
+ bool isend; /* in: marks for lexize_info about text end is
+ * reached */
+ bool getnext; /* out: dict wants next lexeme */
+ void *private_state; /* internal dict state between calls with
+ * getnext == true */
+} DictSubState;
+
+#endif /* _PG_TS_PUBLIC_H_ */
diff --git a/pgsql/include/server/tsearch/ts_type.h b/pgsql/include/server/tsearch/ts_type.h
new file mode 100644
index 0000000000000000000000000000000000000000..b076039c1c1a1d4dbd9f11e71ce2a107fcfd2a59
--- /dev/null
+++ b/pgsql/include/server/tsearch/ts_type.h
@@ -0,0 +1,272 @@
+/*-------------------------------------------------------------------------
+ *
+ * ts_type.h
+ * Definitions for the tsvector and tsquery types
+ *
+ * Copyright (c) 1998-2023, PostgreSQL Global Development Group
+ *
+ * src/include/tsearch/ts_type.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PG_TSTYPE_H_
+#define _PG_TSTYPE_H_
+
+#include "fmgr.h"
+#include "utils/memutils.h"
+
+
+/*
+ * TSVector type.
+ *
+ * Structure of tsvector datatype:
+ * 1) standard varlena header
+ * 2) int32 size - number of lexemes (WordEntry array entries)
+ * 3) Array of WordEntry - one per lexeme; must be sorted according to
+ * tsCompareString() (ie, memcmp of lexeme strings).
+ * WordEntry->pos gives the number of bytes from end of WordEntry
+ * array to start of lexeme's string, which is of length len.
+ * 4) Per-lexeme data storage:
+ * lexeme string (not null-terminated)
+ * if haspos is true:
+ * padding byte if necessary to make the position data 2-byte aligned
+ * uint16 number of positions that follow
+ * WordEntryPos[] positions
+ *
+ * The positions for each lexeme must be sorted.
+ *
+ * Note, tsvectorsend/recv believe that sizeof(WordEntry) == 4
+ */
+
+typedef struct
+{
+ uint32
+ haspos:1,
+ len:11, /* MAX 2Kb */
+ pos:20; /* MAX 1Mb */
+} WordEntry;
+
+#define MAXSTRLEN ( (1<<11) - 1)
+#define MAXSTRPOS ( (1<<20) - 1)
+
+extern int compareWordEntryPos(const void *a, const void *b);
+
+/*
+ * Equivalent to
+ * typedef struct {
+ * uint16
+ * weight:2,
+ * pos:14;
+ * }
+ */
+
+typedef uint16 WordEntryPos;
+
+typedef struct
+{
+ uint16 npos;
+ WordEntryPos pos[FLEXIBLE_ARRAY_MEMBER];
+} WordEntryPosVector;
+
+/* WordEntryPosVector with exactly 1 entry */
+typedef struct
+{
+ uint16 npos;
+ WordEntryPos pos[1];
+} WordEntryPosVector1;
+
+
+#define WEP_GETWEIGHT(x) ( (x) >> 14 )
+#define WEP_GETPOS(x) ( (x) & 0x3fff )
+
+#define WEP_SETWEIGHT(x,v) ( (x) = ( (v) << 14 ) | ( (x) & 0x3fff ) )
+#define WEP_SETPOS(x,v) ( (x) = ( (x) & 0xc000 ) | ( (v) & 0x3fff ) )
+
+#define MAXENTRYPOS (1<<14)
+#define MAXNUMPOS (256)
+#define LIMITPOS(x) ( ( (x) >= MAXENTRYPOS ) ? (MAXENTRYPOS-1) : (x) )
+
+/* This struct represents a complete tsvector datum */
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int32 size;
+ WordEntry entries[FLEXIBLE_ARRAY_MEMBER];
+ /* lexemes follow the entries[] array */
+} TSVectorData;
+
+typedef TSVectorData *TSVector;
+
+#define DATAHDRSIZE (offsetof(TSVectorData, entries))
+#define CALCDATASIZE(nentries, lenstr) (DATAHDRSIZE + (nentries) * sizeof(WordEntry) + (lenstr) )
+
+/* pointer to start of a tsvector's WordEntry array */
+#define ARRPTR(x) ( (x)->entries )
+
+/* pointer to start of a tsvector's lexeme storage */
+#define STRPTR(x) ( (char *) &(x)->entries[(x)->size] )
+
+#define _POSVECPTR(x, e) ((WordEntryPosVector *)(STRPTR(x) + SHORTALIGN((e)->pos + (e)->len)))
+#define POSDATALEN(x,e) ( ( (e)->haspos ) ? (_POSVECPTR(x,e)->npos) : 0 )
+#define POSDATAPTR(x,e) (_POSVECPTR(x,e)->pos)
+
+/*
+ * fmgr interface functions
+ */
+
+static inline TSVector
+DatumGetTSVector(Datum X)
+{
+ return (TSVector) PG_DETOAST_DATUM(X);
+}
+
+static inline TSVector
+DatumGetTSVectorCopy(Datum X)
+{
+ return (TSVector) PG_DETOAST_DATUM_COPY(X);
+}
+
+static inline Datum
+TSVectorGetDatum(const TSVectorData *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_TSVECTOR(n) DatumGetTSVector(PG_GETARG_DATUM(n))
+#define PG_GETARG_TSVECTOR_COPY(n) DatumGetTSVectorCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_TSVECTOR(x) return TSVectorGetDatum(x)
+
+
+/*
+ * TSQuery
+ *
+ *
+ */
+
+typedef int8 QueryItemType;
+
+/* Valid values for QueryItemType: */
+#define QI_VAL 1
+#define QI_OPR 2
+#define QI_VALSTOP 3 /* This is only used in an intermediate stack
+ * representation in parse_tsquery. It's not a
+ * legal type elsewhere. */
+
+/*
+ * QueryItem is one node in tsquery - operator or operand.
+ */
+typedef struct
+{
+ QueryItemType type; /* operand or kind of operator (ts_tokentype) */
+ uint8 weight; /* weights of operand to search. It's a
+ * bitmask of allowed weights. if it =0 then
+ * any weight are allowed. Weights and bit
+ * map: A: 1<<3 B: 1<<2 C: 1<<1 D: 1<<0 */
+ bool prefix; /* true if it's a prefix search */
+ int32 valcrc; /* XXX: pg_crc32 would be a more appropriate
+ * data type, but we use comparisons to signed
+ * integers in the code. They would need to be
+ * changed as well. */
+
+ /* pointer to text value of operand, must correlate with WordEntry */
+ uint32
+ length:12,
+ distance:20;
+} QueryOperand;
+
+
+/*
+ * Legal values for QueryOperator.operator.
+ */
+#define OP_NOT 1
+#define OP_AND 2
+#define OP_OR 3
+#define OP_PHRASE 4 /* highest code, tsquery_cleanup.c */
+#define OP_COUNT 4
+
+extern PGDLLIMPORT const int tsearch_op_priority[OP_COUNT];
+
+/* get operation priority by its code */
+#define OP_PRIORITY(x) ( tsearch_op_priority[(x) - 1] )
+/* get QueryOperator priority */
+#define QO_PRIORITY(x) OP_PRIORITY(((QueryOperator *) (x))->oper)
+
+typedef struct
+{
+ QueryItemType type;
+ int8 oper; /* see above */
+ int16 distance; /* distance between agrs for OP_PHRASE */
+ uint32 left; /* pointer to left operand. Right operand is
+ * item + 1, left operand is placed
+ * item+item->left */
+} QueryOperator;
+
+/*
+ * Note: TSQuery is 4-bytes aligned, so make sure there's no fields
+ * inside QueryItem requiring 8-byte alignment, like int64.
+ */
+typedef union
+{
+ QueryItemType type;
+ QueryOperator qoperator;
+ QueryOperand qoperand;
+} QueryItem;
+
+/*
+ * Storage:
+ * (len)(size)(array of QueryItem)(operands as '\0'-terminated c-strings)
+ */
+
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int32 size; /* number of QueryItems */
+ char data[FLEXIBLE_ARRAY_MEMBER]; /* data starts here */
+} TSQueryData;
+
+typedef TSQueryData *TSQuery;
+
+#define HDRSIZETQ ( VARHDRSZ + sizeof(int32) )
+
+/* Computes the size of header and all QueryItems. size is the number of
+ * QueryItems, and lenofoperand is the total length of all operands
+ */
+#define COMPUTESIZE(size, lenofoperand) ( HDRSIZETQ + (size) * sizeof(QueryItem) + (lenofoperand) )
+#define TSQUERY_TOO_BIG(size, lenofoperand) \
+ ((size) > (MaxAllocSize - HDRSIZETQ - (lenofoperand)) / sizeof(QueryItem))
+
+/* Returns a pointer to the first QueryItem in a TSQuery */
+#define GETQUERY(x) ((QueryItem*)( (char*)(x)+HDRSIZETQ ))
+
+/* Returns a pointer to the beginning of operands in a TSQuery */
+#define GETOPERAND(x) ( (char*)GETQUERY(x) + ((TSQuery)(x))->size * sizeof(QueryItem) )
+
+/*
+ * fmgr interface functions
+ * Note, TSQuery type marked as plain storage, so it can't be toasted
+ * but PG_DETOAST_DATUM_COPY is used for simplicity
+ */
+
+static inline TSQuery
+DatumGetTSQuery(Datum X)
+{
+ return (TSQuery) DatumGetPointer(X);
+}
+
+static inline TSQuery
+DatumGetTSQueryCopy(Datum X)
+{
+ return (TSQuery) PG_DETOAST_DATUM_COPY(X);
+}
+
+static inline Datum
+TSQueryGetDatum(const TSQueryData *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_TSQUERY(n) DatumGetTSQuery(PG_GETARG_DATUM(n))
+#define PG_GETARG_TSQUERY_COPY(n) DatumGetTSQueryCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_TSQUERY(x) return TSQueryGetDatum(x)
+
+#endif /* _PG_TSTYPE_H_ */
diff --git a/pgsql/include/server/tsearch/ts_utils.h b/pgsql/include/server/tsearch/ts_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..d3dc8bae47585a507396a3ce88f442b92924cb6c
--- /dev/null
+++ b/pgsql/include/server/tsearch/ts_utils.h
@@ -0,0 +1,283 @@
+/*-------------------------------------------------------------------------
+ *
+ * ts_utils.h
+ * helper utilities for tsearch
+ *
+ * Copyright (c) 1998-2023, PostgreSQL Global Development Group
+ *
+ * src/include/tsearch/ts_utils.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PG_TS_UTILS_H_
+#define _PG_TS_UTILS_H_
+
+#include "nodes/pg_list.h"
+#include "tsearch/ts_public.h"
+#include "tsearch/ts_type.h"
+
+/*
+ * Common parse definitions for tsvector and tsquery
+ */
+
+/* tsvector parser support. */
+
+struct TSVectorParseStateData; /* opaque struct in tsvector_parser.c */
+typedef struct TSVectorParseStateData *TSVectorParseState;
+
+/* flag bits that can be passed to init_tsvector_parser: */
+#define P_TSV_OPR_IS_DELIM (1 << 0)
+#define P_TSV_IS_TSQUERY (1 << 1)
+#define P_TSV_IS_WEB (1 << 2)
+
+extern TSVectorParseState init_tsvector_parser(char *input, int flags,
+ Node *escontext);
+extern void reset_tsvector_parser(TSVectorParseState state, char *input);
+extern bool gettoken_tsvector(TSVectorParseState state,
+ char **strval, int *lenval,
+ WordEntryPos **pos_ptr, int *poslen,
+ char **endptr);
+extern void close_tsvector_parser(TSVectorParseState state);
+
+/* phrase operator begins with '<' */
+#define ISOPERATOR(x) \
+ ( pg_mblen(x) == 1 && ( *(x) == '!' || \
+ *(x) == '&' || \
+ *(x) == '|' || \
+ *(x) == '(' || \
+ *(x) == ')' || \
+ *(x) == '<' \
+ ) )
+
+/* parse_tsquery */
+
+struct TSQueryParserStateData; /* private in backend/utils/adt/tsquery.c */
+typedef struct TSQueryParserStateData *TSQueryParserState;
+
+typedef void (*PushFunction) (Datum opaque, TSQueryParserState state,
+ char *token, int tokenlen,
+ int16 tokenweights, /* bitmap as described in
+ * QueryOperand struct */
+ bool prefix);
+
+/* flag bits that can be passed to parse_tsquery: */
+#define P_TSQ_PLAIN (1 << 0)
+#define P_TSQ_WEB (1 << 1)
+
+extern TSQuery parse_tsquery(char *buf,
+ PushFunction pushval,
+ Datum opaque,
+ int flags,
+ Node *escontext);
+
+/* Functions for use by PushFunction implementations */
+extern void pushValue(TSQueryParserState state,
+ char *strval, int lenval, int16 weight, bool prefix);
+extern void pushStop(TSQueryParserState state);
+extern void pushOperator(TSQueryParserState state, int8 oper, int16 distance);
+
+/*
+ * parse plain text and lexize words
+ */
+typedef struct
+{
+ uint16 len;
+ uint16 nvariant;
+ union
+ {
+ uint16 pos;
+
+ /*
+ * When apos array is used, apos[0] is the number of elements in the
+ * array (excluding apos[0]), and alen is the allocated size of the
+ * array.
+ */
+ uint16 *apos;
+ } pos;
+ uint16 flags; /* currently, only TSL_PREFIX */
+ char *word;
+ uint32 alen;
+} ParsedWord;
+
+typedef struct
+{
+ ParsedWord *words;
+ int32 lenwords;
+ int32 curwords;
+ int32 pos;
+} ParsedText;
+
+extern void parsetext(Oid cfgId, ParsedText *prs, char *buf, int32 buflen);
+
+/*
+ * headline framework, flow in common to generate:
+ * 1 parse text with hlparsetext
+ * 2 parser-specific function to find part
+ * 3 generateHeadline to generate result text
+ */
+
+extern void hlparsetext(Oid cfgId, HeadlineParsedText *prs, TSQuery query,
+ char *buf, int32 buflen);
+extern text *generateHeadline(HeadlineParsedText *prs);
+
+/*
+ * TSQuery execution support
+ *
+ * TS_execute() executes a tsquery against data that can be represented in
+ * various forms. The TSExecuteCallback callback function is called to check
+ * whether a given primitive tsquery value is matched in the data.
+ */
+
+/* TS_execute requires ternary logic to handle NOT with phrase matches */
+typedef enum
+{
+ TS_NO, /* definitely no match */
+ TS_YES, /* definitely does match */
+ TS_MAYBE /* can't verify match for lack of pos data */
+} TSTernaryValue;
+
+/*
+ * struct ExecPhraseData is passed to a TSExecuteCallback function if we need
+ * lexeme position data (because of a phrase-match operator in the tsquery).
+ * The callback should fill in position data when it returns TS_YES (success).
+ * If it cannot return position data, it should leave "data" unchanged and
+ * return TS_MAYBE. The caller of TS_execute() must then arrange for a later
+ * recheck with position data available.
+ *
+ * The reported lexeme positions must be sorted and unique. Callers must only
+ * consult the position bits of the pos array, ie, WEP_GETPOS(data->pos[i]).
+ * This allows the returned "pos" to point directly to the WordEntryPos
+ * portion of a tsvector value. If "allocated" is true then the pos array
+ * is palloc'd workspace and caller may free it when done.
+ *
+ * "negate" means that the pos array contains positions where the query does
+ * not match, rather than positions where it does. "width" is positive when
+ * the match is wider than one lexeme. Neither of these fields normally need
+ * to be touched by TSExecuteCallback functions; they are used for
+ * phrase-search processing within TS_execute.
+ *
+ * All fields of the ExecPhraseData struct are initially zeroed by caller.
+ */
+typedef struct ExecPhraseData
+{
+ int npos; /* number of positions reported */
+ bool allocated; /* pos points to palloc'd data? */
+ bool negate; /* positions are where query is NOT matched */
+ WordEntryPos *pos; /* ordered, non-duplicate lexeme positions */
+ int width; /* width of match in lexemes, less 1 */
+} ExecPhraseData;
+
+/*
+ * Signature for TSQuery lexeme check functions
+ *
+ * arg: opaque value passed through from caller of TS_execute
+ * val: lexeme to test for presence of
+ * data: to be filled with lexeme positions; NULL if position data not needed
+ *
+ * Return TS_YES if lexeme is present in data, TS_MAYBE if it might be
+ * present, TS_NO if it definitely is not present. If data is not NULL,
+ * it must be filled with lexeme positions if available. If position data
+ * is not available, leave *data as zeroes and return TS_MAYBE, never TS_YES.
+ */
+typedef TSTernaryValue (*TSExecuteCallback) (void *arg, QueryOperand *val,
+ ExecPhraseData *data);
+
+/*
+ * Flag bits for TS_execute
+ */
+#define TS_EXEC_EMPTY (0x00)
+/*
+ * If TS_EXEC_SKIP_NOT is set, then NOT sub-expressions are automatically
+ * evaluated to be true. This was formerly the default behavior. It's now
+ * deprecated because it tends to give silly answers, but some applications
+ * might still have a use for it.
+ */
+#define TS_EXEC_SKIP_NOT (0x01)
+/*
+ * If TS_EXEC_PHRASE_NO_POS is set, allow OP_PHRASE to be executed lossily
+ * in the absence of position information: a true result indicates that the
+ * phrase might be present. Without this flag, OP_PHRASE always returns
+ * false if lexeme position information is not available.
+ */
+#define TS_EXEC_PHRASE_NO_POS (0x02)
+
+extern bool TS_execute(QueryItem *curitem, void *arg, uint32 flags,
+ TSExecuteCallback chkcond);
+extern TSTernaryValue TS_execute_ternary(QueryItem *curitem, void *arg,
+ uint32 flags,
+ TSExecuteCallback chkcond);
+extern List *TS_execute_locations(QueryItem *curitem, void *arg,
+ uint32 flags,
+ TSExecuteCallback chkcond);
+extern bool tsquery_requires_match(QueryItem *curitem);
+
+/*
+ * to_ts* - text transformation to tsvector, tsquery
+ */
+extern TSVector make_tsvector(ParsedText *prs);
+extern int32 tsCompareString(char *a, int lena, char *b, int lenb, bool prefix);
+
+/*
+ * Possible strategy numbers for indexes
+ * TSearchStrategyNumber - (tsvector|text) @@ tsquery
+ * TSearchWithClassStrategyNumber - tsvector @@@ tsquery
+ */
+#define TSearchStrategyNumber 1
+#define TSearchWithClassStrategyNumber 2
+
+/*
+ * TSQuery Utilities
+ */
+extern QueryItem *clean_NOT(QueryItem *ptr, int32 *len);
+extern TSQuery cleanup_tsquery_stopwords(TSQuery in, bool noisy);
+
+typedef struct QTNode
+{
+ QueryItem *valnode;
+ uint32 flags;
+ int32 nchild;
+ char *word;
+ uint32 sign;
+ struct QTNode **child;
+} QTNode;
+
+/* bits in QTNode.flags */
+#define QTN_NEEDFREE 0x01
+#define QTN_NOCHANGE 0x02
+#define QTN_WORDFREE 0x04
+
+typedef uint64 TSQuerySign;
+
+#define TSQS_SIGLEN (sizeof(TSQuerySign)*BITS_PER_BYTE)
+
+static inline Datum
+TSQuerySignGetDatum(TSQuerySign X)
+{
+ return Int64GetDatum((int64) X);
+}
+
+static inline TSQuerySign
+DatumGetTSQuerySign(Datum X)
+{
+ return (TSQuerySign) DatumGetInt64(X);
+}
+
+#define PG_RETURN_TSQUERYSIGN(X) return TSQuerySignGetDatum(X)
+#define PG_GETARG_TSQUERYSIGN(n) DatumGetTSQuerySign(PG_GETARG_DATUM(n))
+
+
+extern QTNode *QT2QTN(QueryItem *in, char *operand);
+extern TSQuery QTN2QT(QTNode *in);
+extern void QTNFree(QTNode *in);
+extern void QTNSort(QTNode *in);
+extern void QTNTernary(QTNode *in);
+extern void QTNBinary(QTNode *in);
+extern int QTNodeCompare(QTNode *an, QTNode *bn);
+extern QTNode *QTNCopy(QTNode *in);
+extern void QTNClearFlags(QTNode *in, uint32 flags);
+extern bool QTNEq(QTNode *a, QTNode *b);
+extern TSQuerySign makeTSQuerySign(TSQuery a);
+extern QTNode *findsubquery(QTNode *root, QTNode *ex, QTNode *subs,
+ bool *isfind);
+
+#endif /* _PG_TS_UTILS_H_ */
diff --git a/pgsql/include/server/utils/acl.h b/pgsql/include/server/utils/acl.h
new file mode 100644
index 0000000000000000000000000000000000000000..aba1afa971c82c0ca2f5426027a34559628f742a
--- /dev/null
+++ b/pgsql/include/server/utils/acl.h
@@ -0,0 +1,278 @@
+/*-------------------------------------------------------------------------
+ *
+ * acl.h
+ * Definition of (and support for) access control list data structures.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/acl.h
+ *
+ * NOTES
+ * An ACL array is simply an array of AclItems, representing the union
+ * of the privileges represented by the individual items. A zero-length
+ * array represents "no privileges".
+ *
+ * The order of items in the array is important as client utilities (in
+ * particular, pg_dump, though possibly other clients) expect to be able
+ * to issue GRANTs in the ordering of the items in the array. The reason
+ * this matters is that GRANTs WITH GRANT OPTION must be before any GRANTs
+ * which depend on it. This happens naturally in the backend during
+ * operations as we update ACLs in-place, new items are appended, and
+ * existing entries are only removed if there's no dependency on them (no
+ * GRANT can been based on it, or, if there was, those GRANTs are also
+ * removed).
+ *
+ * For backward-compatibility purposes we have to allow null ACL entries
+ * in system catalogs. A null ACL will be treated as meaning "default
+ * protection" (i.e., whatever acldefault() returns).
+ *-------------------------------------------------------------------------
+ */
+#ifndef ACL_H
+#define ACL_H
+
+#include "access/htup.h"
+#include "nodes/parsenodes.h"
+#include "parser/parse_node.h"
+#include "utils/snapshot.h"
+
+
+/*
+ * typedef AclMode is declared in parsenodes.h, also the individual privilege
+ * bit meanings are defined there
+ */
+
+#define ACL_ID_PUBLIC 0 /* placeholder for id in a PUBLIC acl item */
+
+/*
+ * AclItem
+ *
+ * Note: must be same size on all platforms, because the size is hardcoded
+ * in the pg_type.h entry for aclitem.
+ */
+typedef struct AclItem
+{
+ Oid ai_grantee; /* ID that this item grants privs to */
+ Oid ai_grantor; /* grantor of privs */
+ AclMode ai_privs; /* privilege bits */
+} AclItem;
+
+/*
+ * The upper 32 bits of the ai_privs field of an AclItem are the grant option
+ * bits, and the lower 32 bits are the actual privileges. We use "rights"
+ * to mean the combined grant option and privilege bits fields.
+ */
+#define ACLITEM_GET_PRIVS(item) ((item).ai_privs & 0xFFFFFFFF)
+#define ACLITEM_GET_GOPTIONS(item) (((item).ai_privs >> 32) & 0xFFFFFFFF)
+#define ACLITEM_GET_RIGHTS(item) ((item).ai_privs)
+
+#define ACL_GRANT_OPTION_FOR(privs) (((AclMode) (privs) & 0xFFFFFFFF) << 32)
+#define ACL_OPTION_TO_PRIVS(privs) (((AclMode) (privs) >> 32) & 0xFFFFFFFF)
+
+#define ACLITEM_SET_PRIVS(item,privs) \
+ ((item).ai_privs = ((item).ai_privs & ~((AclMode) 0xFFFFFFFF)) | \
+ ((AclMode) (privs) & 0xFFFFFFFF))
+#define ACLITEM_SET_GOPTIONS(item,goptions) \
+ ((item).ai_privs = ((item).ai_privs & ~(((AclMode) 0xFFFFFFFF) << 32)) | \
+ (((AclMode) (goptions) & 0xFFFFFFFF) << 32))
+#define ACLITEM_SET_RIGHTS(item,rights) \
+ ((item).ai_privs = (AclMode) (rights))
+
+#define ACLITEM_SET_PRIVS_GOPTIONS(item,privs,goptions) \
+ ((item).ai_privs = ((AclMode) (privs) & 0xFFFFFFFF) | \
+ (((AclMode) (goptions) & 0xFFFFFFFF) << 32))
+
+
+#define ACLITEM_ALL_PRIV_BITS ((AclMode) 0xFFFFFFFF)
+#define ACLITEM_ALL_GOPTION_BITS ((AclMode) 0xFFFFFFFF << 32)
+
+/*
+ * Definitions for convenient access to Acl (array of AclItem).
+ * These are standard PostgreSQL arrays, but are restricted to have one
+ * dimension and no nulls. We also ignore the lower bound when reading,
+ * and set it to one when writing.
+ *
+ * CAUTION: as of PostgreSQL 7.1, these arrays are toastable (just like all
+ * other array types). Therefore, be careful to detoast them with the
+ * macros provided, unless you know for certain that a particular array
+ * can't have been toasted.
+ */
+
+
+/*
+ * Acl a one-dimensional array of AclItem
+ */
+typedef struct ArrayType Acl;
+
+#define ACL_NUM(ACL) (ARR_DIMS(ACL)[0])
+#define ACL_DAT(ACL) ((AclItem *) ARR_DATA_PTR(ACL))
+#define ACL_N_SIZE(N) (ARR_OVERHEAD_NONULLS(1) + ((N) * sizeof(AclItem)))
+#define ACL_SIZE(ACL) ARR_SIZE(ACL)
+
+/*
+ * fmgr macros for these types
+ */
+#define DatumGetAclItemP(X) ((AclItem *) DatumGetPointer(X))
+#define PG_GETARG_ACLITEM_P(n) DatumGetAclItemP(PG_GETARG_DATUM(n))
+#define PG_RETURN_ACLITEM_P(x) PG_RETURN_POINTER(x)
+
+#define DatumGetAclP(X) ((Acl *) PG_DETOAST_DATUM(X))
+#define DatumGetAclPCopy(X) ((Acl *) PG_DETOAST_DATUM_COPY(X))
+#define PG_GETARG_ACL_P(n) DatumGetAclP(PG_GETARG_DATUM(n))
+#define PG_GETARG_ACL_P_COPY(n) DatumGetAclPCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_ACL_P(x) PG_RETURN_POINTER(x)
+
+/*
+ * ACL modification opcodes for aclupdate
+ */
+#define ACL_MODECHG_ADD 1
+#define ACL_MODECHG_DEL 2
+#define ACL_MODECHG_EQL 3
+
+/*
+ * External representations of the privilege bits --- aclitemin/aclitemout
+ * represent each possible privilege bit with a distinct 1-character code
+ */
+#define ACL_INSERT_CHR 'a' /* formerly known as "append" */
+#define ACL_SELECT_CHR 'r' /* formerly known as "read" */
+#define ACL_UPDATE_CHR 'w' /* formerly known as "write" */
+#define ACL_DELETE_CHR 'd'
+#define ACL_TRUNCATE_CHR 'D' /* super-delete, as it were */
+#define ACL_REFERENCES_CHR 'x'
+#define ACL_TRIGGER_CHR 't'
+#define ACL_EXECUTE_CHR 'X'
+#define ACL_USAGE_CHR 'U'
+#define ACL_CREATE_CHR 'C'
+#define ACL_CREATE_TEMP_CHR 'T'
+#define ACL_CONNECT_CHR 'c'
+#define ACL_SET_CHR 's'
+#define ACL_ALTER_SYSTEM_CHR 'A'
+
+/* string holding all privilege code chars, in order by bitmask position */
+#define ACL_ALL_RIGHTS_STR "arwdDxtXUCTcsA"
+
+/*
+ * Bitmasks defining "all rights" for each supported object type
+ */
+#define ACL_ALL_RIGHTS_COLUMN (ACL_INSERT|ACL_SELECT|ACL_UPDATE|ACL_REFERENCES)
+#define ACL_ALL_RIGHTS_RELATION (ACL_INSERT|ACL_SELECT|ACL_UPDATE|ACL_DELETE|ACL_TRUNCATE|ACL_REFERENCES|ACL_TRIGGER)
+#define ACL_ALL_RIGHTS_SEQUENCE (ACL_USAGE|ACL_SELECT|ACL_UPDATE)
+#define ACL_ALL_RIGHTS_DATABASE (ACL_CREATE|ACL_CREATE_TEMP|ACL_CONNECT)
+#define ACL_ALL_RIGHTS_FDW (ACL_USAGE)
+#define ACL_ALL_RIGHTS_FOREIGN_SERVER (ACL_USAGE)
+#define ACL_ALL_RIGHTS_FUNCTION (ACL_EXECUTE)
+#define ACL_ALL_RIGHTS_LANGUAGE (ACL_USAGE)
+#define ACL_ALL_RIGHTS_LARGEOBJECT (ACL_SELECT|ACL_UPDATE)
+#define ACL_ALL_RIGHTS_PARAMETER_ACL (ACL_SET|ACL_ALTER_SYSTEM)
+#define ACL_ALL_RIGHTS_SCHEMA (ACL_USAGE|ACL_CREATE)
+#define ACL_ALL_RIGHTS_TABLESPACE (ACL_CREATE)
+#define ACL_ALL_RIGHTS_TYPE (ACL_USAGE)
+
+/* operation codes for pg_*_aclmask */
+typedef enum
+{
+ ACLMASK_ALL, /* normal case: compute all bits */
+ ACLMASK_ANY /* return when result is known nonzero */
+} AclMaskHow;
+
+/* result codes for pg_*_aclcheck */
+typedef enum
+{
+ ACLCHECK_OK = 0,
+ ACLCHECK_NO_PRIV,
+ ACLCHECK_NOT_OWNER
+} AclResult;
+
+
+/*
+ * routines used internally
+ */
+extern Acl *acldefault(ObjectType objtype, Oid ownerId);
+extern Acl *get_user_default_acl(ObjectType objtype, Oid ownerId,
+ Oid nsp_oid);
+extern void recordDependencyOnNewAcl(Oid classId, Oid objectId, int32 objsubId,
+ Oid ownerId, Acl *acl);
+
+extern Acl *aclupdate(const Acl *old_acl, const AclItem *mod_aip,
+ int modechg, Oid ownerId, DropBehavior behavior);
+extern Acl *aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId);
+extern Acl *make_empty_acl(void);
+extern Acl *aclcopy(const Acl *orig_acl);
+extern Acl *aclconcat(const Acl *left_acl, const Acl *right_acl);
+extern Acl *aclmerge(const Acl *left_acl, const Acl *right_acl, Oid ownerId);
+extern void aclitemsort(Acl *acl);
+extern bool aclequal(const Acl *left_acl, const Acl *right_acl);
+
+extern AclMode aclmask(const Acl *acl, Oid roleid, Oid ownerId,
+ AclMode mask, AclMaskHow how);
+extern int aclmembers(const Acl *acl, Oid **roleids);
+
+extern bool has_privs_of_role(Oid member, Oid role);
+extern bool member_can_set_role(Oid member, Oid role);
+extern void check_can_set_role(Oid member, Oid role);
+extern bool is_member_of_role(Oid member, Oid role);
+extern bool is_member_of_role_nosuper(Oid member, Oid role);
+extern bool is_admin_of_role(Oid member, Oid role);
+extern Oid select_best_admin(Oid member, Oid role);
+extern Oid get_role_oid(const char *rolname, bool missing_ok);
+extern Oid get_role_oid_or_public(const char *rolname);
+extern Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok);
+extern void check_rolespec_name(const RoleSpec *role, const char *detail_msg);
+extern HeapTuple get_rolespec_tuple(const RoleSpec *role);
+extern char *get_rolespec_name(const RoleSpec *role);
+
+extern void select_best_grantor(Oid roleId, AclMode privileges,
+ const Acl *acl, Oid ownerId,
+ Oid *grantorId, AclMode *grantOptions);
+
+extern void initialize_acl(void);
+
+/*
+ * prototypes for functions in aclchk.c
+ */
+extern void ExecuteGrantStmt(GrantStmt *stmt);
+extern void ExecAlterDefaultPrivilegesStmt(ParseState *pstate, AlterDefaultPrivilegesStmt *stmt);
+
+extern void RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid);
+
+extern AclMode pg_class_aclmask(Oid table_oid, Oid roleid,
+ AclMode mask, AclMaskHow how);
+
+/* generic function */
+extern AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode);
+
+/* special cases */
+extern AclResult pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum,
+ Oid roleid, AclMode mode);
+extern AclResult pg_attribute_aclcheck_ext(Oid table_oid, AttrNumber attnum,
+ Oid roleid, AclMode mode,
+ bool *is_missing);
+extern AclResult pg_attribute_aclcheck_all(Oid table_oid, Oid roleid,
+ AclMode mode, AclMaskHow how);
+extern AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode);
+extern AclResult pg_class_aclcheck_ext(Oid table_oid, Oid roleid,
+ AclMode mode, bool *is_missing);
+extern AclResult pg_parameter_aclcheck(const char *name, Oid roleid,
+ AclMode mode);
+extern AclResult pg_largeobject_aclcheck_snapshot(Oid lobj_oid, Oid roleid,
+ AclMode mode, Snapshot snapshot);
+
+extern void aclcheck_error(AclResult aclerr, ObjectType objtype,
+ const char *objectname);
+
+extern void aclcheck_error_col(AclResult aclerr, ObjectType objtype,
+ const char *objectname, const char *colname);
+
+extern void aclcheck_error_type(AclResult aclerr, Oid typeOid);
+
+extern void recordExtObjInitPriv(Oid objoid, Oid classoid);
+extern void removeExtObjInitPriv(Oid objoid, Oid classoid);
+
+
+/* ownercheck routines just return true (owner) or false (not) */
+extern bool object_ownercheck(Oid classid, Oid objectid, Oid roleid);
+extern bool has_createrole_privilege(Oid roleid);
+extern bool has_bypassrls_privilege(Oid roleid);
+
+#endif /* ACL_H */
diff --git a/pgsql/include/server/utils/aclchk_internal.h b/pgsql/include/server/utils/aclchk_internal.h
new file mode 100644
index 0000000000000000000000000000000000000000..55af624fb34356c9e09e3db9d33885313482aa71
--- /dev/null
+++ b/pgsql/include/server/utils/aclchk_internal.h
@@ -0,0 +1,45 @@
+/*-------------------------------------------------------------------------
+ *
+ * aclchk_internal.h
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/aclchk_internal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ACLCHK_INTERNAL_H
+#define ACLCHK_INTERNAL_H
+
+#include "nodes/parsenodes.h"
+#include "nodes/pg_list.h"
+
+/*
+ * The information about one Grant/Revoke statement, in internal format: object
+ * and grantees names have been turned into Oids, the privilege list is an
+ * AclMode bitmask. If 'privileges' is ACL_NO_RIGHTS (the 0 value) and
+ * all_privs is true, 'privileges' will be internally set to the right kind of
+ * ACL_ALL_RIGHTS_*, depending on the object type (NB - this will modify the
+ * InternalGrant struct!)
+ *
+ * Note: 'all_privs' and 'privileges' represent object-level privileges only.
+ * There might also be column-level privilege specifications, which are
+ * represented in col_privs (this is a list of untransformed AccessPriv nodes).
+ * Column privileges are only valid for objtype OBJECT_TABLE.
+ */
+typedef struct
+{
+ bool is_grant;
+ ObjectType objtype;
+ List *objects;
+ bool all_privs;
+ AclMode privileges;
+ List *col_privs;
+ List *grantees;
+ bool grant_option;
+ DropBehavior behavior;
+} InternalGrant;
+
+
+#endif /* ACLCHK_INTERNAL_H */
diff --git a/pgsql/include/server/utils/array.h b/pgsql/include/server/utils/array.h
new file mode 100644
index 0000000000000000000000000000000000000000..e6c8d88d9f20c5ac7253b52e219fa61ab8fe5e06
--- /dev/null
+++ b/pgsql/include/server/utils/array.h
@@ -0,0 +1,482 @@
+/*-------------------------------------------------------------------------
+ *
+ * array.h
+ * Declarations for Postgres arrays.
+ *
+ * A standard varlena array has the following internal structure:
+ * - standard varlena header word
+ * - number of dimensions of the array
+ * - offset to stored data, or 0 if no nulls bitmap
+ * - element type OID
+ * - length of each array axis (C array of int)
+ * - lower boundary of each dimension (C array of int)
+ * - bitmap showing locations of nulls (OPTIONAL)
+ * - whatever is the stored data
+ *
+ * The and arrays each have ndim elements.
+ *
+ * The may be omitted if the array contains no NULL elements.
+ * If it is absent, the field is zero and the offset to the
+ * stored data must be computed on-the-fly. If the bitmap is present,
+ * is nonzero and is equal to the offset from the array start
+ * to the first data element (including any alignment padding). The bitmap
+ * follows the same conventions as tuple null bitmaps, ie, a 1 indicates
+ * a non-null entry and the LSB of each bitmap byte is used first.
+ *
+ * The actual data starts on a MAXALIGN boundary. Individual items in the
+ * array are aligned as specified by the array element type. They are
+ * stored in row-major order (last subscript varies most rapidly).
+ *
+ * NOTE: it is important that array elements of toastable datatypes NOT be
+ * toasted, since the tupletoaster won't know they are there. (We could
+ * support compressed toasted items; only out-of-line items are dangerous.
+ * However, it seems preferable to store such items uncompressed and allow
+ * the toaster to compress the whole array as one input.)
+ *
+ *
+ * The OIDVECTOR and INT2VECTOR datatypes are storage-compatible with
+ * generic arrays, but they support only one-dimensional arrays with no
+ * nulls (and no null bitmap). They don't support being toasted, either.
+ *
+ * There are also some "fixed-length array" datatypes, such as NAME and
+ * POINT. These are simply a sequence of a fixed number of items each
+ * of a fixed-length datatype, with no overhead; the item size must be
+ * a multiple of its alignment requirement, because we do no padding.
+ * We support subscripting on these types, but array_in() and array_out()
+ * only work with varlena arrays.
+ *
+ * In addition, arrays are a major user of the "expanded object" TOAST
+ * infrastructure. This allows a varlena array to be converted to a
+ * separate representation that may include "deconstructed" Datum/isnull
+ * arrays holding the elements.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/array.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ARRAY_H
+#define ARRAY_H
+
+#include "fmgr.h"
+#include "utils/expandeddatum.h"
+
+/* avoid including execnodes.h here */
+struct ExprState;
+struct ExprContext;
+
+
+/*
+ * Maximum number of array subscripts (arbitrary limit)
+ */
+#define MAXDIM 6
+
+/*
+ * Maximum number of elements in an array. We limit this to at most about a
+ * quarter billion elements, so that it's not necessary to check for overflow
+ * in quite so many places --- for instance when palloc'ing Datum arrays.
+ */
+#define MaxArraySize ((Size) (MaxAllocSize / sizeof(Datum)))
+
+/*
+ * Arrays are varlena objects, so must meet the varlena convention that
+ * the first int32 of the object contains the total object size in bytes.
+ * Be sure to use VARSIZE() and SET_VARSIZE() to access it, though!
+ *
+ * CAUTION: if you change the header for ordinary arrays you will also
+ * need to change the headers for oidvector and int2vector!
+ */
+typedef struct ArrayType
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int ndim; /* # of dimensions */
+ int32 dataoffset; /* offset to data, or 0 if no bitmap */
+ Oid elemtype; /* element type OID */
+} ArrayType;
+
+/*
+ * An expanded array is contained within a private memory context (as
+ * all expanded objects must be) and has a control structure as below.
+ *
+ * The expanded array might contain a regular "flat" array if that was the
+ * original input and we've not modified it significantly. Otherwise, the
+ * contents are represented by Datum/isnull arrays plus dimensionality and
+ * type information. We could also have both forms, if we've deconstructed
+ * the original array for access purposes but not yet changed it. For pass-
+ * by-reference element types, the Datums would point into the flat array in
+ * this situation. Once we start modifying array elements, new pass-by-ref
+ * elements are separately palloc'd within the memory context.
+ */
+#define EA_MAGIC 689375833 /* ID for debugging crosschecks */
+
+typedef struct ExpandedArrayHeader
+{
+ /* Standard header for expanded objects */
+ ExpandedObjectHeader hdr;
+
+ /* Magic value identifying an expanded array (for debugging only) */
+ int ea_magic;
+
+ /* Dimensionality info (always valid) */
+ int ndims; /* # of dimensions */
+ int *dims; /* array dimensions */
+ int *lbound; /* index lower bounds for each dimension */
+
+ /* Element type info (always valid) */
+ Oid element_type; /* element type OID */
+ int16 typlen; /* needed info about element datatype */
+ bool typbyval;
+ char typalign;
+
+ /*
+ * If we have a Datum-array representation of the array, it's kept here;
+ * else dvalues/dnulls are NULL. The dvalues and dnulls arrays are always
+ * palloc'd within the object private context, but may change size from
+ * time to time. For pass-by-ref element types, dvalues entries might
+ * point either into the fstartptr..fendptr area, or to separately
+ * palloc'd chunks. Elements should always be fully detoasted, as they
+ * are in the standard flat representation.
+ *
+ * Even when dvalues is valid, dnulls can be NULL if there are no null
+ * elements.
+ */
+ Datum *dvalues; /* array of Datums */
+ bool *dnulls; /* array of is-null flags for Datums */
+ int dvalueslen; /* allocated length of above arrays */
+ int nelems; /* number of valid entries in above arrays */
+
+ /*
+ * flat_size is the current space requirement for the flat equivalent of
+ * the expanded array, if known; otherwise it's 0. We store this to make
+ * consecutive calls of get_flat_size cheap.
+ */
+ Size flat_size;
+
+ /*
+ * fvalue points to the flat representation if it is valid, else it is
+ * NULL. If we have or ever had a flat representation then
+ * fstartptr/fendptr point to the start and end+1 of its data area; this
+ * is so that we can tell which Datum pointers point into the flat
+ * representation rather than being pointers to separately palloc'd data.
+ */
+ ArrayType *fvalue; /* must be a fully detoasted array */
+ char *fstartptr; /* start of its data area */
+ char *fendptr; /* end+1 of its data area */
+} ExpandedArrayHeader;
+
+/*
+ * Functions that can handle either a "flat" varlena array or an expanded
+ * array use this union to work with their input. Don't refer to "flt";
+ * instead, cast to ArrayType. This struct nominally requires 8-byte
+ * alignment on 64-bit, but it's often used for an ArrayType having 4-byte
+ * alignment. UBSan complains about referencing "flt" in such cases.
+ */
+typedef union AnyArrayType
+{
+ ArrayType flt;
+ ExpandedArrayHeader xpn;
+} AnyArrayType;
+
+/*
+ * working state for accumArrayResult() and friends
+ * note that the input must be scalars (legal array elements)
+ */
+typedef struct ArrayBuildState
+{
+ MemoryContext mcontext; /* where all the temp stuff is kept */
+ Datum *dvalues; /* array of accumulated Datums */
+ bool *dnulls; /* array of is-null flags for Datums */
+ int alen; /* allocated length of above arrays */
+ int nelems; /* number of valid entries in above arrays */
+ Oid element_type; /* data type of the Datums */
+ int16 typlen; /* needed info about datatype */
+ bool typbyval;
+ char typalign;
+ bool private_cxt; /* use private memory context */
+} ArrayBuildState;
+
+/*
+ * working state for accumArrayResultArr() and friends
+ * note that the input must be arrays, and the same array type is returned
+ */
+typedef struct ArrayBuildStateArr
+{
+ MemoryContext mcontext; /* where all the temp stuff is kept */
+ char *data; /* accumulated data */
+ bits8 *nullbitmap; /* bitmap of is-null flags, or NULL if none */
+ int abytes; /* allocated length of "data" */
+ int nbytes; /* number of bytes used so far */
+ int aitems; /* allocated length of bitmap (in elements) */
+ int nitems; /* total number of elements in result */
+ int ndims; /* current dimensions of result */
+ int dims[MAXDIM];
+ int lbs[MAXDIM];
+ Oid array_type; /* data type of the arrays */
+ Oid element_type; /* data type of the array elements */
+ bool private_cxt; /* use private memory context */
+} ArrayBuildStateArr;
+
+/*
+ * working state for accumArrayResultAny() and friends
+ * these functions handle both cases
+ */
+typedef struct ArrayBuildStateAny
+{
+ /* Exactly one of these is not NULL: */
+ ArrayBuildState *scalarstate;
+ ArrayBuildStateArr *arraystate;
+} ArrayBuildStateAny;
+
+/*
+ * structure to cache type metadata needed for array manipulation
+ */
+typedef struct ArrayMetaState
+{
+ Oid element_type;
+ int16 typlen;
+ bool typbyval;
+ char typalign;
+ char typdelim;
+ Oid typioparam;
+ Oid typiofunc;
+ FmgrInfo proc;
+} ArrayMetaState;
+
+/*
+ * private state needed by array_map (here because caller must provide it)
+ */
+typedef struct ArrayMapState
+{
+ ArrayMetaState inp_extra;
+ ArrayMetaState ret_extra;
+} ArrayMapState;
+
+/* ArrayIteratorData is private in arrayfuncs.c */
+typedef struct ArrayIteratorData *ArrayIterator;
+
+/* fmgr macros for regular varlena array objects */
+#define DatumGetArrayTypeP(X) ((ArrayType *) PG_DETOAST_DATUM(X))
+#define DatumGetArrayTypePCopy(X) ((ArrayType *) PG_DETOAST_DATUM_COPY(X))
+#define PG_GETARG_ARRAYTYPE_P(n) DatumGetArrayTypeP(PG_GETARG_DATUM(n))
+#define PG_GETARG_ARRAYTYPE_P_COPY(n) DatumGetArrayTypePCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_ARRAYTYPE_P(x) PG_RETURN_POINTER(x)
+
+/* fmgr macros for expanded array objects */
+#define PG_GETARG_EXPANDED_ARRAY(n) DatumGetExpandedArray(PG_GETARG_DATUM(n))
+#define PG_GETARG_EXPANDED_ARRAYX(n, metacache) \
+ DatumGetExpandedArrayX(PG_GETARG_DATUM(n), metacache)
+#define PG_RETURN_EXPANDED_ARRAY(x) PG_RETURN_DATUM(EOHPGetRWDatum(&(x)->hdr))
+
+/* fmgr macros for AnyArrayType (ie, get either varlena or expanded form) */
+#define PG_GETARG_ANY_ARRAY_P(n) DatumGetAnyArrayP(PG_GETARG_DATUM(n))
+
+/*
+ * Access macros for varlena array header fields.
+ *
+ * ARR_DIMS returns a pointer to an array of array dimensions (number of
+ * elements along the various array axes).
+ *
+ * ARR_LBOUND returns a pointer to an array of array lower bounds.
+ *
+ * That is: if the third axis of an array has elements 5 through 8, then
+ * ARR_DIMS(a)[2] == 4 and ARR_LBOUND(a)[2] == 5.
+ *
+ * Unlike C, the default lower bound is 1.
+ */
+#define ARR_SIZE(a) VARSIZE(a)
+#define ARR_NDIM(a) ((a)->ndim)
+#define ARR_HASNULL(a) ((a)->dataoffset != 0)
+#define ARR_ELEMTYPE(a) ((a)->elemtype)
+
+#define ARR_DIMS(a) \
+ ((int *) (((char *) (a)) + sizeof(ArrayType)))
+#define ARR_LBOUND(a) \
+ ((int *) (((char *) (a)) + sizeof(ArrayType) + \
+ sizeof(int) * ARR_NDIM(a)))
+
+#define ARR_NULLBITMAP(a) \
+ (ARR_HASNULL(a) ? \
+ (bits8 *) (((char *) (a)) + sizeof(ArrayType) + \
+ 2 * sizeof(int) * ARR_NDIM(a)) \
+ : (bits8 *) NULL)
+
+/*
+ * The total array header size (in bytes) for an array with the specified
+ * number of dimensions and total number of items.
+ */
+#define ARR_OVERHEAD_NONULLS(ndims) \
+ MAXALIGN(sizeof(ArrayType) + 2 * sizeof(int) * (ndims))
+#define ARR_OVERHEAD_WITHNULLS(ndims, nitems) \
+ MAXALIGN(sizeof(ArrayType) + 2 * sizeof(int) * (ndims) + \
+ ((nitems) + 7) / 8)
+
+#define ARR_DATA_OFFSET(a) \
+ (ARR_HASNULL(a) ? (a)->dataoffset : ARR_OVERHEAD_NONULLS(ARR_NDIM(a)))
+
+/*
+ * Returns a pointer to the actual array data.
+ */
+#define ARR_DATA_PTR(a) \
+ (((char *) (a)) + ARR_DATA_OFFSET(a))
+
+/*
+ * Macros for working with AnyArrayType inputs. Beware multiple references!
+ */
+#define AARR_NDIM(a) \
+ (VARATT_IS_EXPANDED_HEADER(a) ? \
+ (a)->xpn.ndims : ARR_NDIM((ArrayType *) (a)))
+#define AARR_HASNULL(a) \
+ (VARATT_IS_EXPANDED_HEADER(a) ? \
+ ((a)->xpn.dvalues != NULL ? (a)->xpn.dnulls != NULL : ARR_HASNULL((a)->xpn.fvalue)) : \
+ ARR_HASNULL((ArrayType *) (a)))
+#define AARR_ELEMTYPE(a) \
+ (VARATT_IS_EXPANDED_HEADER(a) ? \
+ (a)->xpn.element_type : ARR_ELEMTYPE((ArrayType *) (a)))
+#define AARR_DIMS(a) \
+ (VARATT_IS_EXPANDED_HEADER(a) ? \
+ (a)->xpn.dims : ARR_DIMS((ArrayType *) (a)))
+#define AARR_LBOUND(a) \
+ (VARATT_IS_EXPANDED_HEADER(a) ? \
+ (a)->xpn.lbound : ARR_LBOUND((ArrayType *) (a)))
+
+
+/*
+ * GUC parameter
+ */
+extern PGDLLIMPORT bool Array_nulls;
+
+/*
+ * prototypes for functions defined in arrayfuncs.c
+ */
+extern void CopyArrayEls(ArrayType *array,
+ Datum *values,
+ bool *nulls,
+ int nitems,
+ int typlen,
+ bool typbyval,
+ char typalign,
+ bool freedata);
+
+extern Datum array_get_element(Datum arraydatum, int nSubscripts, int *indx,
+ int arraytyplen, int elmlen, bool elmbyval, char elmalign,
+ bool *isNull);
+extern Datum array_set_element(Datum arraydatum, int nSubscripts, int *indx,
+ Datum dataValue, bool isNull,
+ int arraytyplen, int elmlen, bool elmbyval, char elmalign);
+extern Datum array_get_slice(Datum arraydatum, int nSubscripts,
+ int *upperIndx, int *lowerIndx,
+ bool *upperProvided, bool *lowerProvided,
+ int arraytyplen, int elmlen, bool elmbyval, char elmalign);
+extern Datum array_set_slice(Datum arraydatum, int nSubscripts,
+ int *upperIndx, int *lowerIndx,
+ bool *upperProvided, bool *lowerProvided,
+ Datum srcArrayDatum, bool isNull,
+ int arraytyplen, int elmlen, bool elmbyval, char elmalign);
+
+extern Datum array_ref(ArrayType *array, int nSubscripts, int *indx,
+ int arraytyplen, int elmlen, bool elmbyval, char elmalign,
+ bool *isNull);
+extern ArrayType *array_set(ArrayType *array, int nSubscripts, int *indx,
+ Datum dataValue, bool isNull,
+ int arraytyplen, int elmlen, bool elmbyval, char elmalign);
+
+extern Datum array_map(Datum arrayd,
+ struct ExprState *exprstate, struct ExprContext *econtext,
+ Oid retType, ArrayMapState *amstate);
+
+extern void array_bitmap_copy(bits8 *destbitmap, int destoffset,
+ const bits8 *srcbitmap, int srcoffset,
+ int nitems);
+
+extern ArrayType *construct_array(Datum *elems, int nelems,
+ Oid elmtype,
+ int elmlen, bool elmbyval, char elmalign);
+extern ArrayType *construct_array_builtin(Datum *elems, int nelems, Oid elmtype);
+extern ArrayType *construct_md_array(Datum *elems,
+ bool *nulls,
+ int ndims,
+ int *dims,
+ int *lbs,
+ Oid elmtype, int elmlen, bool elmbyval, char elmalign);
+extern ArrayType *construct_empty_array(Oid elmtype);
+extern ExpandedArrayHeader *construct_empty_expanded_array(Oid element_type,
+ MemoryContext parentcontext,
+ ArrayMetaState *metacache);
+extern void deconstruct_array(ArrayType *array,
+ Oid elmtype,
+ int elmlen, bool elmbyval, char elmalign,
+ Datum **elemsp, bool **nullsp, int *nelemsp);
+extern void deconstruct_array_builtin(ArrayType *array,
+ Oid elmtype,
+ Datum **elemsp, bool **nullsp, int *nelemsp);
+extern bool array_contains_nulls(ArrayType *array);
+
+extern ArrayBuildState *initArrayResult(Oid element_type,
+ MemoryContext rcontext, bool subcontext);
+extern ArrayBuildState *initArrayResultWithSize(Oid element_type,
+ MemoryContext rcontext,
+ bool subcontext, int initsize);
+extern ArrayBuildState *accumArrayResult(ArrayBuildState *astate,
+ Datum dvalue, bool disnull,
+ Oid element_type,
+ MemoryContext rcontext);
+extern Datum makeArrayResult(ArrayBuildState *astate,
+ MemoryContext rcontext);
+extern Datum makeMdArrayResult(ArrayBuildState *astate, int ndims,
+ int *dims, int *lbs, MemoryContext rcontext, bool release);
+
+extern ArrayBuildStateArr *initArrayResultArr(Oid array_type, Oid element_type,
+ MemoryContext rcontext, bool subcontext);
+extern ArrayBuildStateArr *accumArrayResultArr(ArrayBuildStateArr *astate,
+ Datum dvalue, bool disnull,
+ Oid array_type,
+ MemoryContext rcontext);
+extern Datum makeArrayResultArr(ArrayBuildStateArr *astate,
+ MemoryContext rcontext, bool release);
+
+extern ArrayBuildStateAny *initArrayResultAny(Oid input_type,
+ MemoryContext rcontext, bool subcontext);
+extern ArrayBuildStateAny *accumArrayResultAny(ArrayBuildStateAny *astate,
+ Datum dvalue, bool disnull,
+ Oid input_type,
+ MemoryContext rcontext);
+extern Datum makeArrayResultAny(ArrayBuildStateAny *astate,
+ MemoryContext rcontext, bool release);
+
+extern ArrayIterator array_create_iterator(ArrayType *arr, int slice_ndim, ArrayMetaState *mstate);
+extern bool array_iterate(ArrayIterator iterator, Datum *value, bool *isnull);
+extern void array_free_iterator(ArrayIterator iterator);
+
+/*
+ * prototypes for functions defined in arrayutils.c
+ */
+
+extern int ArrayGetOffset(int n, const int *dim, const int *lb, const int *indx);
+extern int ArrayGetOffset0(int n, const int *tup, const int *scale);
+extern int ArrayGetNItems(int ndim, const int *dims);
+extern int ArrayGetNItemsSafe(int ndim, const int *dims,
+ struct Node *escontext);
+extern void ArrayCheckBounds(int ndim, const int *dims, const int *lb);
+extern bool ArrayCheckBoundsSafe(int ndim, const int *dims, const int *lb,
+ struct Node *escontext);
+extern void mda_get_range(int n, int *span, const int *st, const int *endp);
+extern void mda_get_prod(int n, const int *range, int *prod);
+extern void mda_get_offset_values(int n, int *dist, const int *prod, const int *span);
+extern int mda_next_tuple(int n, int *curr, const int *span);
+extern int32 *ArrayGetIntegerTypmods(ArrayType *arr, int *n);
+
+/*
+ * prototypes for functions defined in array_expanded.c
+ */
+extern Datum expand_array(Datum arraydatum, MemoryContext parentcontext,
+ ArrayMetaState *metacache);
+extern ExpandedArrayHeader *DatumGetExpandedArray(Datum d);
+extern ExpandedArrayHeader *DatumGetExpandedArrayX(Datum d,
+ ArrayMetaState *metacache);
+extern AnyArrayType *DatumGetAnyArrayP(Datum d);
+extern void deconstruct_expanded_array(ExpandedArrayHeader *eah);
+
+#endif /* ARRAY_H */
diff --git a/pgsql/include/server/utils/arrayaccess.h b/pgsql/include/server/utils/arrayaccess.h
new file mode 100644
index 0000000000000000000000000000000000000000..fd267d5480420f621509bdfbfd4a71289f80649e
--- /dev/null
+++ b/pgsql/include/server/utils/arrayaccess.h
@@ -0,0 +1,118 @@
+/*-------------------------------------------------------------------------
+ *
+ * arrayaccess.h
+ * Declarations for element-by-element access to Postgres arrays.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/arrayaccess.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ARRAYACCESS_H
+#define ARRAYACCESS_H
+
+#include "access/tupmacs.h"
+#include "utils/array.h"
+
+
+/*
+ * Functions for iterating through elements of a flat or expanded array.
+ * These require a state struct "array_iter iter".
+ *
+ * Use "array_iter_setup(&iter, arrayptr);" to prepare to iterate, and
+ * "datumvar = array_iter_next(&iter, &isnullvar, index, ...);" to fetch
+ * the next element into datumvar/isnullvar.
+ * "index" must be the zero-origin element number; we make caller provide
+ * this since caller is generally counting the elements anyway. Despite
+ * that, these functions can only fetch elements sequentially.
+ */
+
+typedef struct array_iter
+{
+ /* datumptr being NULL or not tells if we have flat or expanded array */
+
+ /* Fields used when we have an expanded array */
+ Datum *datumptr; /* Pointer to Datum array */
+ bool *isnullptr; /* Pointer to isnull array */
+
+ /* Fields used when we have a flat array */
+ char *dataptr; /* Current spot in the data area */
+ bits8 *bitmapptr; /* Current byte of the nulls bitmap, or NULL */
+ int bitmask; /* mask for current bit in nulls bitmap */
+} array_iter;
+
+
+static inline void
+array_iter_setup(array_iter *it, AnyArrayType *a)
+{
+ if (VARATT_IS_EXPANDED_HEADER(a))
+ {
+ if (a->xpn.dvalues)
+ {
+ it->datumptr = a->xpn.dvalues;
+ it->isnullptr = a->xpn.dnulls;
+ /* we must fill all fields to prevent compiler warnings */
+ it->dataptr = NULL;
+ it->bitmapptr = NULL;
+ }
+ else
+ {
+ /* Work with flat array embedded in the expanded datum */
+ it->datumptr = NULL;
+ it->isnullptr = NULL;
+ it->dataptr = ARR_DATA_PTR(a->xpn.fvalue);
+ it->bitmapptr = ARR_NULLBITMAP(a->xpn.fvalue);
+ }
+ }
+ else
+ {
+ it->datumptr = NULL;
+ it->isnullptr = NULL;
+ it->dataptr = ARR_DATA_PTR((ArrayType *) a);
+ it->bitmapptr = ARR_NULLBITMAP((ArrayType *) a);
+ }
+ it->bitmask = 1;
+}
+
+static inline Datum
+array_iter_next(array_iter *it, bool *isnull, int i,
+ int elmlen, bool elmbyval, char elmalign)
+{
+ Datum ret;
+
+ if (it->datumptr)
+ {
+ ret = it->datumptr[i];
+ *isnull = it->isnullptr ? it->isnullptr[i] : false;
+ }
+ else
+ {
+ if (it->bitmapptr && (*(it->bitmapptr) & it->bitmask) == 0)
+ {
+ *isnull = true;
+ ret = (Datum) 0;
+ }
+ else
+ {
+ *isnull = false;
+ ret = fetch_att(it->dataptr, elmbyval, elmlen);
+ it->dataptr = att_addlength_pointer(it->dataptr, elmlen,
+ it->dataptr);
+ it->dataptr = (char *) att_align_nominal(it->dataptr, elmalign);
+ }
+ it->bitmask <<= 1;
+ if (it->bitmask == 0x100)
+ {
+ if (it->bitmapptr)
+ it->bitmapptr++;
+ it->bitmask = 1;
+ }
+ }
+
+ return ret;
+}
+
+#endif /* ARRAYACCESS_H */
diff --git a/pgsql/include/server/utils/ascii.h b/pgsql/include/server/utils/ascii.h
new file mode 100644
index 0000000000000000000000000000000000000000..7df024dad398d2218c1160c879a07db7f4fcf1f6
--- /dev/null
+++ b/pgsql/include/server/utils/ascii.h
@@ -0,0 +1,84 @@
+/*-----------------------------------------------------------------------
+ * ascii.h
+ *
+ * Portions Copyright (c) 1999-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/ascii.h
+ *
+ *-----------------------------------------------------------------------
+ */
+
+#ifndef _ASCII_H_
+#define _ASCII_H_
+
+#include "port/simd.h"
+
+extern void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz);
+
+/*
+ * Verify a chunk of bytes for valid ASCII.
+ *
+ * Returns false if the input contains any zero bytes or bytes with the
+ * high-bit set. Input len must be a multiple of the chunk size (8 or 16).
+ */
+static inline bool
+is_valid_ascii(const unsigned char *s, int len)
+{
+ const unsigned char *const s_end = s + len;
+ Vector8 chunk;
+ Vector8 highbit_cum = vector8_broadcast(0);
+#ifdef USE_NO_SIMD
+ Vector8 zero_cum = vector8_broadcast(0x80);
+#endif
+
+ Assert(len % sizeof(chunk) == 0);
+
+ while (s < s_end)
+ {
+ vector8_load(&chunk, s);
+
+ /* Capture any zero bytes in this chunk. */
+#ifdef USE_NO_SIMD
+
+ /*
+ * First, add 0x7f to each byte. This sets the high bit in each byte,
+ * unless it was a zero. If any resulting high bits are zero, the
+ * corresponding high bits in the zero accumulator will be cleared.
+ *
+ * If none of the bytes in the chunk had the high bit set, the max
+ * value each byte can have after the addition is 0x7f + 0x7f = 0xfe,
+ * and we don't need to worry about carrying over to the next byte. If
+ * any input bytes did have the high bit set, it doesn't matter
+ * because we check for those separately.
+ */
+ zero_cum &= (chunk + vector8_broadcast(0x7F));
+#else
+
+ /*
+ * Set all bits in each lane of the highbit accumulator where input
+ * bytes are zero.
+ */
+ highbit_cum = vector8_or(highbit_cum,
+ vector8_eq(chunk, vector8_broadcast(0)));
+#endif
+
+ /* Capture all set bits in this chunk. */
+ highbit_cum = vector8_or(highbit_cum, chunk);
+
+ s += sizeof(chunk);
+ }
+
+ /* Check if any high bits in the high bit accumulator got set. */
+ if (vector8_is_highbit_set(highbit_cum))
+ return false;
+
+#ifdef USE_NO_SIMD
+ /* Check if any high bits in the zero accumulator got cleared. */
+ if (zero_cum != vector8_broadcast(0x80))
+ return false;
+#endif
+
+ return true;
+}
+
+#endif /* _ASCII_H_ */
diff --git a/pgsql/include/server/utils/attoptcache.h b/pgsql/include/server/utils/attoptcache.h
new file mode 100644
index 0000000000000000000000000000000000000000..e4119b6aa2899dfd7be038949982ae9cb1503ac2
--- /dev/null
+++ b/pgsql/include/server/utils/attoptcache.h
@@ -0,0 +1,28 @@
+/*-------------------------------------------------------------------------
+ *
+ * attoptcache.h
+ * Attribute options cache.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/attoptcache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ATTOPTCACHE_H
+#define ATTOPTCACHE_H
+
+/*
+ * Attribute options.
+ */
+typedef struct AttributeOpts
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ float8 n_distinct;
+ float8 n_distinct_inherited;
+} AttributeOpts;
+
+extern AttributeOpts *get_attribute_options(Oid attrelid, int attnum);
+
+#endif /* ATTOPTCACHE_H */
diff --git a/pgsql/include/server/utils/backend_progress.h b/pgsql/include/server/utils/backend_progress.h
new file mode 100644
index 0000000000000000000000000000000000000000..a84752ade99a1bb74ad12690926311e09ae1991c
--- /dev/null
+++ b/pgsql/include/server/utils/backend_progress.h
@@ -0,0 +1,45 @@
+/* ----------
+ * backend_progress.h
+ * Command progress reporting definition.
+ *
+ * Note that this file provides the infrastructure for storing a single
+ * backend's command progress counters, without ascribing meaning to the
+ * individual fields. See commands/progress.h and system_views.sql for that.
+ *
+ * Copyright (c) 2001-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/backend_progress.h
+ * ----------
+ */
+#ifndef BACKEND_PROGRESS_H
+#define BACKEND_PROGRESS_H
+
+
+/* ----------
+ * Command type for progress reporting purposes
+ * ----------
+ */
+typedef enum ProgressCommandType
+{
+ PROGRESS_COMMAND_INVALID,
+ PROGRESS_COMMAND_VACUUM,
+ PROGRESS_COMMAND_ANALYZE,
+ PROGRESS_COMMAND_CLUSTER,
+ PROGRESS_COMMAND_CREATE_INDEX,
+ PROGRESS_COMMAND_BASEBACKUP,
+ PROGRESS_COMMAND_COPY
+} ProgressCommandType;
+
+#define PGSTAT_NUM_PROGRESS_PARAM 20
+
+
+extern void pgstat_progress_start_command(ProgressCommandType cmdtype,
+ Oid relid);
+extern void pgstat_progress_update_param(int index, int64 val);
+extern void pgstat_progress_incr_param(int index, int64 incr);
+extern void pgstat_progress_update_multi_param(int nparam, const int *index,
+ const int64 *val);
+extern void pgstat_progress_end_command(void);
+
+
+#endif /* BACKEND_PROGRESS_H */
diff --git a/pgsql/include/server/utils/backend_status.h b/pgsql/include/server/utils/backend_status.h
new file mode 100644
index 0000000000000000000000000000000000000000..d51c840dafbeff3a36bf46b686b0475c8ff9a405
--- /dev/null
+++ b/pgsql/include/server/utils/backend_status.h
@@ -0,0 +1,342 @@
+/* ----------
+ * backend_status.h
+ * Definitions related to backend status reporting
+ *
+ * Copyright (c) 2001-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/backend_status.h
+ * ----------
+ */
+#ifndef BACKEND_STATUS_H
+#define BACKEND_STATUS_H
+
+#include "datatype/timestamp.h"
+#include "libpq/pqcomm.h"
+#include "miscadmin.h" /* for BackendType */
+#include "storage/backendid.h"
+#include "utils/backend_progress.h"
+
+
+/* ----------
+ * Backend states
+ * ----------
+ */
+typedef enum BackendState
+{
+ STATE_UNDEFINED,
+ STATE_IDLE,
+ STATE_RUNNING,
+ STATE_IDLEINTRANSACTION,
+ STATE_FASTPATH,
+ STATE_IDLEINTRANSACTION_ABORTED,
+ STATE_DISABLED
+} BackendState;
+
+
+/* ----------
+ * Shared-memory data structures
+ * ----------
+ */
+
+/*
+ * PgBackendSSLStatus
+ *
+ * For each backend, we keep the SSL status in a separate struct, that
+ * is only filled in if SSL is enabled.
+ *
+ * All char arrays must be null-terminated.
+ */
+typedef struct PgBackendSSLStatus
+{
+ /* Information about SSL connection */
+ int ssl_bits;
+ char ssl_version[NAMEDATALEN];
+ char ssl_cipher[NAMEDATALEN];
+ char ssl_client_dn[NAMEDATALEN];
+
+ /*
+ * serial number is max "20 octets" per RFC 5280, so this size should be
+ * fine
+ */
+ char ssl_client_serial[NAMEDATALEN];
+
+ char ssl_issuer_dn[NAMEDATALEN];
+} PgBackendSSLStatus;
+
+/*
+ * PgBackendGSSStatus
+ *
+ * For each backend, we keep the GSS status in a separate struct, that
+ * is only filled in if GSS is enabled.
+ *
+ * All char arrays must be null-terminated.
+ */
+typedef struct PgBackendGSSStatus
+{
+ /* Information about GSSAPI connection */
+ char gss_princ[NAMEDATALEN]; /* GSSAPI Principal used to auth */
+ bool gss_auth; /* If GSSAPI authentication was used */
+ bool gss_enc; /* If encryption is being used */
+ bool gss_delegation; /* If credentials delegated */
+
+} PgBackendGSSStatus;
+
+
+/* ----------
+ * PgBackendStatus
+ *
+ * Each live backend maintains a PgBackendStatus struct in shared memory
+ * showing its current activity. (The structs are allocated according to
+ * BackendId, but that is not critical.) Note that this is unrelated to the
+ * cumulative stats system (i.e. pgstat.c et al).
+ *
+ * Each auxiliary process also maintains a PgBackendStatus struct in shared
+ * memory.
+ * ----------
+ */
+typedef struct PgBackendStatus
+{
+ /*
+ * To avoid locking overhead, we use the following protocol: a backend
+ * increments st_changecount before modifying its entry, and again after
+ * finishing a modification. A would-be reader should note the value of
+ * st_changecount, copy the entry into private memory, then check
+ * st_changecount again. If the value hasn't changed, and if it's even,
+ * the copy is valid; otherwise start over. This makes updates cheap
+ * while reads are potentially expensive, but that's the tradeoff we want.
+ *
+ * The above protocol needs memory barriers to ensure that the apparent
+ * order of execution is as it desires. Otherwise, for example, the CPU
+ * might rearrange the code so that st_changecount is incremented twice
+ * before the modification on a machine with weak memory ordering. Hence,
+ * use the macros defined below for manipulating st_changecount, rather
+ * than touching it directly.
+ */
+ int st_changecount;
+
+ /* The entry is valid iff st_procpid > 0, unused if st_procpid == 0 */
+ int st_procpid;
+
+ /* Type of backends */
+ BackendType st_backendType;
+
+ /* Times when current backend, transaction, and activity started */
+ TimestampTz st_proc_start_timestamp;
+ TimestampTz st_xact_start_timestamp;
+ TimestampTz st_activity_start_timestamp;
+ TimestampTz st_state_start_timestamp;
+
+ /* Database OID, owning user's OID, connection client address */
+ Oid st_databaseid;
+ Oid st_userid;
+ SockAddr st_clientaddr;
+ char *st_clienthostname; /* MUST be null-terminated */
+
+ /* Information about SSL connection */
+ bool st_ssl;
+ PgBackendSSLStatus *st_sslstatus;
+
+ /* Information about GSSAPI connection */
+ bool st_gss;
+ PgBackendGSSStatus *st_gssstatus;
+
+ /* current state */
+ BackendState st_state;
+
+ /* application name; MUST be null-terminated */
+ char *st_appname;
+
+ /*
+ * Current command string; MUST be null-terminated. Note that this string
+ * possibly is truncated in the middle of a multi-byte character. As
+ * activity strings are stored more frequently than read, that allows to
+ * move the cost of correct truncation to the display side. Use
+ * pgstat_clip_activity() to truncate correctly.
+ */
+ char *st_activity_raw;
+
+ /*
+ * Command progress reporting. Any command which wishes can advertise
+ * that it is running by setting st_progress_command,
+ * st_progress_command_target, and st_progress_param[].
+ * st_progress_command_target should be the OID of the relation which the
+ * command targets (we assume there's just one, as this is meant for
+ * utility commands), but the meaning of each element in the
+ * st_progress_param array is command-specific.
+ */
+ ProgressCommandType st_progress_command;
+ Oid st_progress_command_target;
+ int64 st_progress_param[PGSTAT_NUM_PROGRESS_PARAM];
+
+ /* query identifier, optionally computed using post_parse_analyze_hook */
+ uint64 st_query_id;
+} PgBackendStatus;
+
+
+/*
+ * Macros to load and store st_changecount with appropriate memory barriers.
+ *
+ * Use PGSTAT_BEGIN_WRITE_ACTIVITY() before, and PGSTAT_END_WRITE_ACTIVITY()
+ * after, modifying the current process's PgBackendStatus data. Note that,
+ * since there is no mechanism for cleaning up st_changecount after an error,
+ * THESE MACROS FORM A CRITICAL SECTION. Any error between them will be
+ * promoted to PANIC, causing a database restart to clean up shared memory!
+ * Hence, keep the critical section as short and straight-line as possible.
+ * Aside from being safer, that minimizes the window in which readers will
+ * have to loop.
+ *
+ * Reader logic should follow this sketch:
+ *
+ * for (;;)
+ * {
+ * int before_ct, after_ct;
+ *
+ * pgstat_begin_read_activity(beentry, before_ct);
+ * ... copy beentry data to local memory ...
+ * pgstat_end_read_activity(beentry, after_ct);
+ * if (pgstat_read_activity_complete(before_ct, after_ct))
+ * break;
+ * CHECK_FOR_INTERRUPTS();
+ * }
+ *
+ * For extra safety, we generally use volatile beentry pointers, although
+ * the memory barriers should theoretically be sufficient.
+ */
+#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry) \
+ do { \
+ START_CRIT_SECTION(); \
+ (beentry)->st_changecount++; \
+ pg_write_barrier(); \
+ } while (0)
+
+#define PGSTAT_END_WRITE_ACTIVITY(beentry) \
+ do { \
+ pg_write_barrier(); \
+ (beentry)->st_changecount++; \
+ Assert(((beentry)->st_changecount & 1) == 0); \
+ END_CRIT_SECTION(); \
+ } while (0)
+
+#define pgstat_begin_read_activity(beentry, before_changecount) \
+ do { \
+ (before_changecount) = (beentry)->st_changecount; \
+ pg_read_barrier(); \
+ } while (0)
+
+#define pgstat_end_read_activity(beentry, after_changecount) \
+ do { \
+ pg_read_barrier(); \
+ (after_changecount) = (beentry)->st_changecount; \
+ } while (0)
+
+#define pgstat_read_activity_complete(before_changecount, after_changecount) \
+ ((before_changecount) == (after_changecount) && \
+ ((before_changecount) & 1) == 0)
+
+
+/* ----------
+ * LocalPgBackendStatus
+ *
+ * When we build the backend status array, we use LocalPgBackendStatus to be
+ * able to add new values to the struct when needed without adding new fields
+ * to the shared memory. It contains the backend status as a first member.
+ * ----------
+ */
+typedef struct LocalPgBackendStatus
+{
+ /*
+ * Local version of the backend status entry.
+ */
+ PgBackendStatus backendStatus;
+
+ /*
+ * The backend ID. For auxiliary processes, this will be set to a value
+ * greater than MaxBackends (since auxiliary processes do not have proper
+ * backend IDs).
+ */
+ BackendId backend_id;
+
+ /*
+ * The xid of the current transaction if available, InvalidTransactionId
+ * if not.
+ */
+ TransactionId backend_xid;
+
+ /*
+ * The xmin of the current session if available, InvalidTransactionId if
+ * not.
+ */
+ TransactionId backend_xmin;
+
+ /*
+ * Number of cached subtransactions in the current session.
+ */
+ int backend_subxact_count;
+
+ /*
+ * The number of subtransactions in the current session which exceeded the
+ * cached subtransaction limit.
+ */
+ bool backend_subxact_overflowed;
+} LocalPgBackendStatus;
+
+
+/* ----------
+ * GUC parameters
+ * ----------
+ */
+extern PGDLLIMPORT bool pgstat_track_activities;
+extern PGDLLIMPORT int pgstat_track_activity_query_size;
+
+
+/* ----------
+ * Other global variables
+ * ----------
+ */
+extern PGDLLIMPORT PgBackendStatus *MyBEEntry;
+
+
+/* ----------
+ * Functions called from postmaster
+ * ----------
+ */
+extern Size BackendStatusShmemSize(void);
+extern void CreateSharedBackendStatus(void);
+
+
+/* ----------
+ * Functions called from backends
+ * ----------
+ */
+
+/* Initialization functions */
+extern void pgstat_beinit(void);
+extern void pgstat_bestart(void);
+
+extern void pgstat_clear_backend_activity_snapshot(void);
+
+/* Activity reporting functions */
+extern void pgstat_report_activity(BackendState state, const char *cmd_str);
+extern void pgstat_report_query_id(uint64 query_id, bool force);
+extern void pgstat_report_tempfile(size_t filesize);
+extern void pgstat_report_appname(const char *appname);
+extern void pgstat_report_xact_timestamp(TimestampTz tstamp);
+extern const char *pgstat_get_backend_current_activity(int pid, bool checkUser);
+extern const char *pgstat_get_crashed_backend_activity(int pid, char *buffer,
+ int buflen);
+extern uint64 pgstat_get_my_query_id(void);
+
+
+/* ----------
+ * Support functions for the SQL-callable functions to
+ * generate the pgstat* views.
+ * ----------
+ */
+extern int pgstat_fetch_stat_numbackends(void);
+extern PgBackendStatus *pgstat_get_beentry_by_backend_id(BackendId beid);
+extern LocalPgBackendStatus *pgstat_get_local_beentry_by_backend_id(BackendId beid);
+extern LocalPgBackendStatus *pgstat_get_local_beentry_by_index(int idx);
+extern char *pgstat_clip_activity(const char *raw_activity);
+
+
+#endif /* BACKEND_STATUS_H */
diff --git a/pgsql/include/server/utils/builtins.h b/pgsql/include/server/utils/builtins.h
new file mode 100644
index 0000000000000000000000000000000000000000..2f8b46d6da32e2fdb3fceddd122a37c82d567325
--- /dev/null
+++ b/pgsql/include/server/utils/builtins.h
@@ -0,0 +1,136 @@
+/*-------------------------------------------------------------------------
+ *
+ * builtins.h
+ * Declarations for operations on built-in types.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/builtins.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BUILTINS_H
+#define BUILTINS_H
+
+#include "fmgr.h"
+#include "nodes/nodes.h"
+#include "utils/fmgrprotos.h"
+
+/* Sign + the most decimal digits an 8-byte number could have */
+#define MAXINT8LEN 20
+
+/* bool.c */
+extern bool parse_bool(const char *value, bool *result);
+extern bool parse_bool_with_len(const char *value, size_t len, bool *result);
+
+/* domains.c */
+extern void domain_check(Datum value, bool isnull, Oid domainType,
+ void **extra, MemoryContext mcxt);
+extern int errdatatype(Oid datatypeOid);
+extern int errdomainconstraint(Oid datatypeOid, const char *conname);
+
+/* encode.c */
+extern uint64 hex_encode(const char *src, size_t len, char *dst);
+extern uint64 hex_decode(const char *src, size_t len, char *dst);
+extern uint64 hex_decode_safe(const char *src, size_t len, char *dst,
+ Node *escontext);
+
+/* int.c */
+extern int2vector *buildint2vector(const int16 *int2s, int n);
+
+/* name.c */
+extern void namestrcpy(Name name, const char *str);
+extern int namestrcmp(Name name, const char *str);
+
+/* numutils.c */
+extern int16 pg_strtoint16(const char *s);
+extern int16 pg_strtoint16_safe(const char *s, Node *escontext);
+extern int32 pg_strtoint32(const char *s);
+extern int32 pg_strtoint32_safe(const char *s, Node *escontext);
+extern int64 pg_strtoint64(const char *s);
+extern int64 pg_strtoint64_safe(const char *s, Node *escontext);
+extern uint32 uint32in_subr(const char *s, char **endloc,
+ const char *typname, Node *escontext);
+extern uint64 uint64in_subr(const char *s, char **endloc,
+ const char *typname, Node *escontext);
+extern int pg_itoa(int16 i, char *a);
+extern int pg_ultoa_n(uint32 value, char *a);
+extern int pg_ulltoa_n(uint64 value, char *a);
+extern int pg_ltoa(int32 value, char *a);
+extern int pg_lltoa(int64 value, char *a);
+extern char *pg_ultostr_zeropad(char *str, uint32 value, int32 minwidth);
+extern char *pg_ultostr(char *str, uint32 value);
+
+/* oid.c */
+extern oidvector *buildoidvector(const Oid *oids, int n);
+extern Oid oidparse(Node *node);
+extern int oid_cmp(const void *p1, const void *p2);
+
+/* regexp.c */
+extern char *regexp_fixed_prefix(text *text_re, bool case_insensitive,
+ Oid collation, bool *exact);
+
+/* ruleutils.c */
+extern PGDLLIMPORT bool quote_all_identifiers;
+extern const char *quote_identifier(const char *ident);
+extern char *quote_qualified_identifier(const char *qualifier,
+ const char *ident);
+extern void generate_operator_clause(fmStringInfo buf,
+ const char *leftop, Oid leftoptype,
+ Oid opoid,
+ const char *rightop, Oid rightoptype);
+
+/* varchar.c */
+extern int bpchartruelen(char *s, int len);
+
+/* popular functions from varlena.c */
+extern text *cstring_to_text(const char *s);
+extern text *cstring_to_text_with_len(const char *s, int len);
+extern char *text_to_cstring(const text *t);
+extern void text_to_cstring_buffer(const text *src, char *dst, size_t dst_len);
+
+#define CStringGetTextDatum(s) PointerGetDatum(cstring_to_text(s))
+#define TextDatumGetCString(d) text_to_cstring((text *) DatumGetPointer(d))
+
+/* xid.c */
+extern int xidComparator(const void *arg1, const void *arg2);
+extern int xidLogicalComparator(const void *arg1, const void *arg2);
+
+/* inet_cidr_ntop.c */
+extern char *pg_inet_cidr_ntop(int af, const void *src, int bits,
+ char *dst, size_t size);
+
+/* inet_net_pton.c */
+extern int pg_inet_net_pton(int af, const char *src,
+ void *dst, size_t size);
+
+/* network.c */
+extern double convert_network_to_scalar(Datum value, Oid typid, bool *failure);
+extern Datum network_scan_first(Datum in);
+extern Datum network_scan_last(Datum in);
+extern void clean_ipv6_addr(int addr_family, char *addr);
+
+/* numeric.c */
+extern Datum numeric_float8_no_overflow(PG_FUNCTION_ARGS);
+
+/* format_type.c */
+
+/* Control flags for format_type_extended */
+#define FORMAT_TYPE_TYPEMOD_GIVEN 0x01 /* typemod defined by caller */
+#define FORMAT_TYPE_ALLOW_INVALID 0x02 /* allow invalid types */
+#define FORMAT_TYPE_FORCE_QUALIFY 0x04 /* force qualification of type */
+#define FORMAT_TYPE_INVALID_AS_NULL 0x08 /* NULL if undefined */
+extern char *format_type_extended(Oid type_oid, int32 typemod, bits16 flags);
+
+extern char *format_type_be(Oid type_oid);
+extern char *format_type_be_qualified(Oid type_oid);
+extern char *format_type_with_typemod(Oid type_oid, int32 typemod);
+
+extern int32 type_maximum_size(Oid type_oid, int32 typemod);
+
+/* quote.c */
+extern char *quote_literal_cstr(const char *rawstr);
+
+#endif /* BUILTINS_H */
diff --git a/pgsql/include/server/utils/bytea.h b/pgsql/include/server/utils/bytea.h
new file mode 100644
index 0000000000000000000000000000000000000000..166dd0366e63f93b03fa9f3d76142cd339a7f41e
--- /dev/null
+++ b/pgsql/include/server/utils/bytea.h
@@ -0,0 +1,28 @@
+/*-------------------------------------------------------------------------
+ *
+ * bytea.h
+ * Declarations for BYTEA data type support.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/bytea.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef BYTEA_H
+#define BYTEA_H
+
+
+
+typedef enum
+{
+ BYTEA_OUTPUT_ESCAPE,
+ BYTEA_OUTPUT_HEX
+} ByteaOutputType;
+
+extern PGDLLIMPORT int bytea_output; /* ByteaOutputType, but int for GUC
+ * enum */
+
+#endif /* BYTEA_H */
diff --git a/pgsql/include/server/utils/cash.h b/pgsql/include/server/utils/cash.h
new file mode 100644
index 0000000000000000000000000000000000000000..55d45fadd4815415f8bb5289d82776026df901b4
--- /dev/null
+++ b/pgsql/include/server/utils/cash.h
@@ -0,0 +1,35 @@
+/*
+ * src/include/utils/cash.h
+ *
+ *
+ * cash.h
+ * Written by D'Arcy J.M. Cain
+ *
+ * Functions to allow input and output of money normally but store
+ * and handle it as 64 bit integer.
+ */
+
+#ifndef CASH_H
+#define CASH_H
+
+#include "fmgr.h"
+
+typedef int64 Cash;
+
+/* Cash is pass-by-reference if and only if int64 is */
+static inline Cash
+DatumGetCash(Datum X)
+{
+ return DatumGetInt64(X);
+}
+
+static inline Datum
+CashGetDatum(Cash X)
+{
+ return Int64GetDatum(X);
+}
+
+#define PG_GETARG_CASH(n) DatumGetCash(PG_GETARG_DATUM(n))
+#define PG_RETURN_CASH(x) return CashGetDatum(x)
+
+#endif /* CASH_H */
diff --git a/pgsql/include/server/utils/catcache.h b/pgsql/include/server/utils/catcache.h
new file mode 100644
index 0000000000000000000000000000000000000000..a32d7222a99c56302b17d4126ff6aba994121d5d
--- /dev/null
+++ b/pgsql/include/server/utils/catcache.h
@@ -0,0 +1,236 @@
+/*-------------------------------------------------------------------------
+ *
+ * catcache.h
+ * Low-level catalog cache definitions.
+ *
+ * NOTE: every catalog cache must have a corresponding unique index on
+ * the system table that it caches --- ie, the index must match the keys
+ * used to do lookups in this cache. All cache fetches are done with
+ * indexscans (under normal conditions). The index should be unique to
+ * guarantee that there can only be one matching row for a key combination.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/catcache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef CATCACHE_H
+#define CATCACHE_H
+
+#include "access/htup.h"
+#include "access/skey.h"
+#include "lib/ilist.h"
+#include "utils/relcache.h"
+
+/*
+ * struct catctup: individual tuple in the cache.
+ * struct catclist: list of tuples matching a partial key.
+ * struct catcache: information for managing a cache.
+ * struct catcacheheader: information for managing all the caches.
+ */
+
+#define CATCACHE_MAXKEYS 4
+
+
+/* function computing a datum's hash */
+typedef uint32 (*CCHashFN) (Datum datum);
+
+/* function computing equality of two datums */
+typedef bool (*CCFastEqualFN) (Datum a, Datum b);
+
+typedef struct catcache
+{
+ int id; /* cache identifier --- see syscache.h */
+ int cc_nbuckets; /* # of hash buckets in this cache */
+ TupleDesc cc_tupdesc; /* tuple descriptor (copied from reldesc) */
+ dlist_head *cc_bucket; /* hash buckets */
+ CCHashFN cc_hashfunc[CATCACHE_MAXKEYS]; /* hash function for each key */
+ CCFastEqualFN cc_fastequal[CATCACHE_MAXKEYS]; /* fast equal function for
+ * each key */
+ int cc_keyno[CATCACHE_MAXKEYS]; /* AttrNumber of each key */
+ dlist_head cc_lists; /* list of CatCList structs */
+ int cc_ntup; /* # of tuples currently in this cache */
+ int cc_nkeys; /* # of keys (1..CATCACHE_MAXKEYS) */
+ const char *cc_relname; /* name of relation the tuples come from */
+ Oid cc_reloid; /* OID of relation the tuples come from */
+ Oid cc_indexoid; /* OID of index matching cache keys */
+ bool cc_relisshared; /* is relation shared across databases? */
+ slist_node cc_next; /* list link */
+ ScanKeyData cc_skey[CATCACHE_MAXKEYS]; /* precomputed key info for heap
+ * scans */
+
+ /* These fields are placed here to avoid ABI breakage in v16 */
+ int cc_nlist; /* # of CatCLists currently in this cache */
+ int cc_nlbuckets; /* # of CatCList hash buckets in this cache */
+ dlist_head *cc_lbucket; /* hash buckets for CatCLists */
+
+ /*
+ * Keep these at the end, so that compiling catcache.c with CATCACHE_STATS
+ * doesn't break ABI for other modules
+ */
+#ifdef CATCACHE_STATS
+ long cc_searches; /* total # searches against this cache */
+ long cc_hits; /* # of matches against existing entry */
+ long cc_neg_hits; /* # of matches against negative entry */
+ long cc_newloads; /* # of successful loads of new entry */
+
+ /*
+ * cc_searches - (cc_hits + cc_neg_hits + cc_newloads) is number of failed
+ * searches, each of which will result in loading a negative entry
+ */
+ long cc_invals; /* # of entries invalidated from cache */
+ long cc_lsearches; /* total # list-searches */
+ long cc_lhits; /* # of matches against existing lists */
+#endif
+} CatCache;
+
+
+typedef struct catctup
+{
+ int ct_magic; /* for identifying CatCTup entries */
+#define CT_MAGIC 0x57261502
+
+ uint32 hash_value; /* hash value for this tuple's keys */
+
+ /*
+ * Lookup keys for the entry. By-reference datums point into the tuple for
+ * positive cache entries, and are separately allocated for negative ones.
+ */
+ Datum keys[CATCACHE_MAXKEYS];
+
+ /*
+ * Each tuple in a cache is a member of a dlist that stores the elements
+ * of its hash bucket. We keep each dlist in LRU order to speed repeated
+ * lookups.
+ */
+ dlist_node cache_elem; /* list member of per-bucket list */
+
+ /*
+ * A tuple marked "dead" must not be returned by subsequent searches.
+ * However, it won't be physically deleted from the cache until its
+ * refcount goes to zero. (If it's a member of a CatCList, the list's
+ * refcount must go to zero, too; also, remember to mark the list dead at
+ * the same time the tuple is marked.)
+ *
+ * A negative cache entry is an assertion that there is no tuple matching
+ * a particular key. This is just as useful as a normal entry so far as
+ * avoiding catalog searches is concerned. Management of positive and
+ * negative entries is identical.
+ */
+ int refcount; /* number of active references */
+ bool dead; /* dead but not yet removed? */
+ bool negative; /* negative cache entry? */
+ HeapTupleData tuple; /* tuple management header */
+
+ /*
+ * The tuple may also be a member of at most one CatCList. (If a single
+ * catcache is list-searched with varying numbers of keys, we may have to
+ * make multiple entries for the same tuple because of this restriction.
+ * Currently, that's not expected to be common, so we accept the potential
+ * inefficiency.)
+ */
+ struct catclist *c_list; /* containing CatCList, or NULL if none */
+
+ CatCache *my_cache; /* link to owning catcache */
+ /* properly aligned tuple data follows, unless a negative entry */
+} CatCTup;
+
+
+/*
+ * A CatCList describes the result of a partial search, ie, a search using
+ * only the first K key columns of an N-key cache. We store the keys used
+ * into the keys attribute to represent the stored key set. The CatCList
+ * object contains links to cache entries for all the table rows satisfying
+ * the partial key. (Note: none of these will be negative cache entries.)
+ *
+ * A CatCList is only a member of a per-cache list; we do not currently
+ * divide them into hash buckets.
+ *
+ * A list marked "dead" must not be returned by subsequent searches.
+ * However, it won't be physically deleted from the cache until its
+ * refcount goes to zero. (A list should be marked dead if any of its
+ * member entries are dead.)
+ *
+ * If "ordered" is true then the member tuples appear in the order of the
+ * cache's underlying index. This will be true in normal operation, but
+ * might not be true during bootstrap or recovery operations. (namespace.c
+ * is able to save some cycles when it is true.)
+ */
+typedef struct catclist
+{
+ int cl_magic; /* for identifying CatCList entries */
+#define CL_MAGIC 0x52765103
+
+ uint32 hash_value; /* hash value for lookup keys */
+
+ dlist_node cache_elem; /* list member of per-catcache list */
+
+ /*
+ * Lookup keys for the entry, with the first nkeys elements being valid.
+ * All by-reference are separately allocated.
+ */
+ Datum keys[CATCACHE_MAXKEYS];
+
+ int refcount; /* number of active references */
+ bool dead; /* dead but not yet removed? */
+ bool ordered; /* members listed in index order? */
+ short nkeys; /* number of lookup keys specified */
+ int n_members; /* number of member tuples */
+ CatCache *my_cache; /* link to owning catcache */
+ CatCTup *members[FLEXIBLE_ARRAY_MEMBER]; /* members */
+} CatCList;
+
+
+typedef struct catcacheheader
+{
+ slist_head ch_caches; /* head of list of CatCache structs */
+ int ch_ntup; /* # of tuples in all caches */
+} CatCacheHeader;
+
+
+/* this extern duplicates utils/memutils.h... */
+extern PGDLLIMPORT MemoryContext CacheMemoryContext;
+
+extern void CreateCacheMemoryContext(void);
+
+extern CatCache *InitCatCache(int id, Oid reloid, Oid indexoid,
+ int nkeys, const int *key,
+ int nbuckets);
+extern void InitCatCachePhase2(CatCache *cache, bool touch_index);
+
+extern HeapTuple SearchCatCache(CatCache *cache,
+ Datum v1, Datum v2, Datum v3, Datum v4);
+extern HeapTuple SearchCatCache1(CatCache *cache,
+ Datum v1);
+extern HeapTuple SearchCatCache2(CatCache *cache,
+ Datum v1, Datum v2);
+extern HeapTuple SearchCatCache3(CatCache *cache,
+ Datum v1, Datum v2, Datum v3);
+extern HeapTuple SearchCatCache4(CatCache *cache,
+ Datum v1, Datum v2, Datum v3, Datum v4);
+extern void ReleaseCatCache(HeapTuple tuple);
+
+extern uint32 GetCatCacheHashValue(CatCache *cache,
+ Datum v1, Datum v2,
+ Datum v3, Datum v4);
+
+extern CatCList *SearchCatCacheList(CatCache *cache, int nkeys,
+ Datum v1, Datum v2,
+ Datum v3);
+extern void ReleaseCatCacheList(CatCList *list);
+
+extern void ResetCatalogCaches(void);
+extern void CatalogCacheFlushCatalog(Oid catId);
+extern void CatCacheInvalidate(CatCache *cache, uint32 hashValue);
+extern void PrepareToInvalidateCacheTuple(Relation relation,
+ HeapTuple tuple,
+ HeapTuple newtuple,
+ void (*function) (int, uint32, Oid));
+
+extern void PrintCatCacheLeakWarning(HeapTuple tuple);
+extern void PrintCatCacheListLeakWarning(CatCList *list);
+
+#endif /* CATCACHE_H */
diff --git a/pgsql/include/server/utils/combocid.h b/pgsql/include/server/utils/combocid.h
new file mode 100644
index 0000000000000000000000000000000000000000..2b496ee6346229c1e5dd0cd62553c43231d8396d
--- /dev/null
+++ b/pgsql/include/server/utils/combocid.h
@@ -0,0 +1,28 @@
+/*-------------------------------------------------------------------------
+ *
+ * combocid.h
+ * Combo command ID support routines
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/combocid.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef COMBOCID_H
+#define COMBOCID_H
+
+/*
+ * HeapTupleHeaderGetCmin and HeapTupleHeaderGetCmax function prototypes
+ * are in access/htup.h, because that's where the macro definitions that
+ * those functions replaced used to be.
+ */
+
+extern void AtEOXact_ComboCid(void);
+extern void RestoreComboCIDState(char *comboCIDstate);
+extern void SerializeComboCIDState(Size maxsize, char *start_address);
+extern Size EstimateComboCIDStateSpace(void);
+
+#endif /* COMBOCID_H */
diff --git a/pgsql/include/server/utils/conffiles.h b/pgsql/include/server/utils/conffiles.h
new file mode 100644
index 0000000000000000000000000000000000000000..e3868fbc23df8aa3bb8f0d81b90de957fd946582
--- /dev/null
+++ b/pgsql/include/server/utils/conffiles.h
@@ -0,0 +1,27 @@
+/*--------------------------------------------------------------------
+ * conffiles.h
+ *
+ * Utilities related to configuration files.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/conffiles.h
+ *
+ *--------------------------------------------------------------------
+ */
+#ifndef CONFFILES_H
+#define CONFFILES_H
+
+/* recursion nesting depth for configuration files */
+#define CONF_FILE_START_DEPTH 0
+#define CONF_FILE_MAX_DEPTH 10
+
+extern char *AbsoluteConfigLocation(const char *location,
+ const char *calling_file);
+extern char **GetConfFilesInDir(const char *includedir,
+ const char *calling_file,
+ int elevel, int *num_filenames,
+ char **err_msg);
+
+#endif /* CONFFILES_H */
diff --git a/pgsql/include/server/utils/date.h b/pgsql/include/server/utils/date.h
new file mode 100644
index 0000000000000000000000000000000000000000..97e1a0212172e817337561aeee344c2b131edffd
--- /dev/null
+++ b/pgsql/include/server/utils/date.h
@@ -0,0 +1,118 @@
+/*-------------------------------------------------------------------------
+ *
+ * date.h
+ * Definitions for the SQL "date" and "time" types.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/date.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DATE_H
+#define DATE_H
+
+#include
+
+#include "datatype/timestamp.h"
+#include "fmgr.h"
+#include "pgtime.h"
+
+typedef int32 DateADT;
+
+typedef int64 TimeADT;
+
+typedef struct
+{
+ TimeADT time; /* all time units other than months and years */
+ int32 zone; /* numeric time zone, in seconds */
+} TimeTzADT;
+
+/*
+ * Infinity and minus infinity must be the max and min values of DateADT.
+ */
+#define DATEVAL_NOBEGIN ((DateADT) PG_INT32_MIN)
+#define DATEVAL_NOEND ((DateADT) PG_INT32_MAX)
+
+#define DATE_NOBEGIN(j) ((j) = DATEVAL_NOBEGIN)
+#define DATE_IS_NOBEGIN(j) ((j) == DATEVAL_NOBEGIN)
+#define DATE_NOEND(j) ((j) = DATEVAL_NOEND)
+#define DATE_IS_NOEND(j) ((j) == DATEVAL_NOEND)
+#define DATE_NOT_FINITE(j) (DATE_IS_NOBEGIN(j) || DATE_IS_NOEND(j))
+
+#define MAX_TIME_PRECISION 6
+
+/*
+ * Functions for fmgr-callable functions.
+ *
+ * For TimeADT, we make use of the same support routines as for int64.
+ * Therefore TimeADT is pass-by-reference if and only if int64 is!
+ */
+static inline DateADT
+DatumGetDateADT(Datum X)
+{
+ return (DateADT) DatumGetInt32(X);
+}
+
+static inline TimeADT
+DatumGetTimeADT(Datum X)
+{
+ return (TimeADT) DatumGetInt64(X);
+}
+
+static inline TimeTzADT *
+DatumGetTimeTzADTP(Datum X)
+{
+ return (TimeTzADT *) DatumGetPointer(X);
+}
+
+static inline Datum
+DateADTGetDatum(DateADT X)
+{
+ return Int32GetDatum(X);
+}
+
+static inline Datum
+TimeADTGetDatum(TimeADT X)
+{
+ return Int64GetDatum(X);
+}
+
+static inline Datum
+TimeTzADTPGetDatum(const TimeTzADT *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_DATEADT(n) DatumGetDateADT(PG_GETARG_DATUM(n))
+#define PG_GETARG_TIMEADT(n) DatumGetTimeADT(PG_GETARG_DATUM(n))
+#define PG_GETARG_TIMETZADT_P(n) DatumGetTimeTzADTP(PG_GETARG_DATUM(n))
+
+#define PG_RETURN_DATEADT(x) return DateADTGetDatum(x)
+#define PG_RETURN_TIMEADT(x) return TimeADTGetDatum(x)
+#define PG_RETURN_TIMETZADT_P(x) return TimeTzADTPGetDatum(x)
+
+
+/* date.c */
+extern int32 anytime_typmod_check(bool istz, int32 typmod);
+extern double date2timestamp_no_overflow(DateADT dateVal);
+extern Timestamp date2timestamp_opt_overflow(DateADT dateVal, int *overflow);
+extern TimestampTz date2timestamptz_opt_overflow(DateADT dateVal, int *overflow);
+extern int32 date_cmp_timestamp_internal(DateADT dateVal, Timestamp dt2);
+extern int32 date_cmp_timestamptz_internal(DateADT dateVal, TimestampTz dt2);
+
+extern void EncodeSpecialDate(DateADT dt, char *str);
+extern DateADT GetSQLCurrentDate(void);
+extern TimeTzADT *GetSQLCurrentTime(int32 typmod);
+extern TimeADT GetSQLLocalTime(int32 typmod);
+extern int time2tm(TimeADT time, struct pg_tm *tm, fsec_t *fsec);
+extern int timetz2tm(TimeTzADT *time, struct pg_tm *tm, fsec_t *fsec, int *tzp);
+extern int tm2time(struct pg_tm *tm, fsec_t fsec, TimeADT *result);
+extern int tm2timetz(struct pg_tm *tm, fsec_t fsec, int tz, TimeTzADT *result);
+extern bool time_overflows(int hour, int min, int sec, fsec_t fsec);
+extern bool float_time_overflows(int hour, int min, double sec);
+extern void AdjustTimeForTypmod(TimeADT *time, int32 typmod);
+
+#endif /* DATE_H */
diff --git a/pgsql/include/server/utils/datetime.h b/pgsql/include/server/utils/datetime.h
new file mode 100644
index 0000000000000000000000000000000000000000..a871e3223de661bab3557ac5725d43c69a6370a9
--- /dev/null
+++ b/pgsql/include/server/utils/datetime.h
@@ -0,0 +1,364 @@
+/*-------------------------------------------------------------------------
+ *
+ * datetime.h
+ * Definitions for date/time support code.
+ * The support code is shared with other date data types,
+ * including date, and time.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/datetime.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DATETIME_H
+#define DATETIME_H
+
+#include "utils/timestamp.h"
+
+/* this struct is declared in utils/tzparser.h: */
+struct tzEntry;
+
+
+/* ----------------------------------------------------------------
+ * time types + support macros
+ *
+ * String definitions for standard time quantities.
+ *
+ * These strings are the defaults used to form output time strings.
+ * Other alternative forms are hardcoded into token tables in datetime.c.
+ * ----------------------------------------------------------------
+ */
+
+#define DAGO "ago"
+#define DCURRENT "current"
+#define EPOCH "epoch"
+#define INVALID "invalid"
+#define EARLY "-infinity"
+#define LATE "infinity"
+#define NOW "now"
+#define TODAY "today"
+#define TOMORROW "tomorrow"
+#define YESTERDAY "yesterday"
+#define ZULU "zulu"
+
+#define DMICROSEC "usecond"
+#define DMILLISEC "msecond"
+#define DSECOND "second"
+#define DMINUTE "minute"
+#define DHOUR "hour"
+#define DDAY "day"
+#define DWEEK "week"
+#define DMONTH "month"
+#define DQUARTER "quarter"
+#define DYEAR "year"
+#define DDECADE "decade"
+#define DCENTURY "century"
+#define DMILLENNIUM "millennium"
+#define DA_D "ad"
+#define DB_C "bc"
+#define DTIMEZONE "timezone"
+
+/*
+ * Fundamental time field definitions for parsing.
+ *
+ * Meridian: am, pm, or 24-hour style.
+ * Millennium: ad, bc
+ */
+
+#define AM 0
+#define PM 1
+#define HR24 2
+
+#define AD 0
+#define BC 1
+
+/*
+ * Field types for time decoding.
+ *
+ * Can't have more of these than there are bits in an unsigned int
+ * since these are turned into bit masks during parsing and decoding.
+ *
+ * Furthermore, the values for YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
+ * must be in the range 0..14 so that the associated bitmasks can fit
+ * into the left half of an INTERVAL's typmod value. Since those bits
+ * are stored in typmods, you can't change them without initdb!
+ */
+
+#define RESERV 0
+#define MONTH 1
+#define YEAR 2
+#define DAY 3
+#define JULIAN 4
+#define TZ 5 /* fixed-offset timezone abbreviation */
+#define DTZ 6 /* fixed-offset timezone abbrev, DST */
+#define DYNTZ 7 /* dynamic timezone abbreviation */
+#define IGNORE_DTF 8
+#define AMPM 9
+#define HOUR 10
+#define MINUTE 11
+#define SECOND 12
+#define MILLISECOND 13
+#define MICROSECOND 14
+#define DOY 15
+#define DOW 16
+#define UNITS 17
+#define ADBC 18
+/* these are only for relative dates */
+#define AGO 19
+#define ABS_BEFORE 20
+#define ABS_AFTER 21
+/* generic fields to help with parsing */
+#define ISODATE 22
+#define ISOTIME 23
+/* these are only for parsing intervals */
+#define WEEK 24
+#define DECADE 25
+#define CENTURY 26
+#define MILLENNIUM 27
+/* hack for parsing two-word timezone specs "MET DST" etc */
+#define DTZMOD 28 /* "DST" as a separate word */
+/* reserved for unrecognized string values */
+#define UNKNOWN_FIELD 31
+
+/*
+ * Token field definitions for time parsing and decoding.
+ *
+ * Some field type codes (see above) use these as the "value" in datetktbl[].
+ * These are also used for bit masks in DecodeDateTime and friends
+ * so actually restrict them to within [0,31] for now.
+ * - thomas 97/06/19
+ * Not all of these fields are used for masks in DecodeDateTime
+ * so allow some larger than 31. - thomas 1997-11-17
+ *
+ * Caution: there are undocumented assumptions in the code that most of these
+ * values are not equal to IGNORE_DTF nor RESERV. Be very careful when
+ * renumbering values in either of these apparently-independent lists :-(
+ */
+
+#define DTK_NUMBER 0
+#define DTK_STRING 1
+
+#define DTK_DATE 2
+#define DTK_TIME 3
+#define DTK_TZ 4
+#define DTK_AGO 5
+
+#define DTK_SPECIAL 6
+#define DTK_EARLY 9
+#define DTK_LATE 10
+#define DTK_EPOCH 11
+#define DTK_NOW 12
+#define DTK_YESTERDAY 13
+#define DTK_TODAY 14
+#define DTK_TOMORROW 15
+#define DTK_ZULU 16
+
+#define DTK_DELTA 17
+#define DTK_SECOND 18
+#define DTK_MINUTE 19
+#define DTK_HOUR 20
+#define DTK_DAY 21
+#define DTK_WEEK 22
+#define DTK_MONTH 23
+#define DTK_QUARTER 24
+#define DTK_YEAR 25
+#define DTK_DECADE 26
+#define DTK_CENTURY 27
+#define DTK_MILLENNIUM 28
+#define DTK_MILLISEC 29
+#define DTK_MICROSEC 30
+#define DTK_JULIAN 31
+
+#define DTK_DOW 32
+#define DTK_DOY 33
+#define DTK_TZ_HOUR 34
+#define DTK_TZ_MINUTE 35
+#define DTK_ISOYEAR 36
+#define DTK_ISODOW 37
+
+
+/*
+ * Bit mask definitions for time parsing.
+ */
+
+#define DTK_M(t) (0x01 << (t))
+
+/* Convenience: a second, plus any fractional component */
+#define DTK_ALL_SECS_M (DTK_M(SECOND) | DTK_M(MILLISECOND) | DTK_M(MICROSECOND))
+#define DTK_DATE_M (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY))
+#define DTK_TIME_M (DTK_M(HOUR) | DTK_M(MINUTE) | DTK_ALL_SECS_M)
+
+/*
+ * Working buffer size for input and output of interval, timestamp, etc.
+ * Inputs that need more working space will be rejected early. Longer outputs
+ * will overrun buffers, so this must suffice for all possible output. As of
+ * this writing, interval_out() needs the most space at ~90 bytes.
+ */
+#define MAXDATELEN 128
+/* maximum possible number of fields in a date string */
+#define MAXDATEFIELDS 25
+/* only this many chars are stored in datetktbl */
+#define TOKMAXLEN 10
+
+/* keep this struct small; it gets used a lot */
+typedef struct
+{
+ char token[TOKMAXLEN + 1]; /* always NUL-terminated */
+ char type; /* see field type codes above */
+ int32 value; /* meaning depends on type */
+} datetkn;
+
+/* one of its uses is in tables of time zone abbreviations */
+typedef struct TimeZoneAbbrevTable
+{
+ Size tblsize; /* size in bytes of TimeZoneAbbrevTable */
+ int numabbrevs; /* number of entries in abbrevs[] array */
+ datetkn abbrevs[FLEXIBLE_ARRAY_MEMBER];
+ /* DynamicZoneAbbrev(s) may follow the abbrevs[] array */
+} TimeZoneAbbrevTable;
+
+/* auxiliary data for a dynamic time zone abbreviation (non-fixed-offset) */
+typedef struct DynamicZoneAbbrev
+{
+ pg_tz *tz; /* NULL if not yet looked up */
+ char zone[FLEXIBLE_ARRAY_MEMBER]; /* NUL-terminated zone name */
+} DynamicZoneAbbrev;
+
+
+/* FMODULO()
+ * Macro to replace modf(), which is broken on some platforms.
+ * t = input and remainder
+ * q = integer part
+ * u = divisor
+ */
+#define FMODULO(t,q,u) \
+do { \
+ (q) = (((t) < 0) ? ceil((t) / (u)) : floor((t) / (u))); \
+ if ((q) != 0) (t) -= rint((q) * (u)); \
+} while(0)
+
+/* TMODULO()
+ * Like FMODULO(), but work on the timestamp datatype (now always int64).
+ * We assume that int64 follows the C99 semantics for division (negative
+ * quotients truncate towards zero).
+ */
+#define TMODULO(t,q,u) \
+do { \
+ (q) = ((t) / (u)); \
+ if ((q) != 0) (t) -= ((q) * (u)); \
+} while(0)
+
+/*
+ * Date/time validation
+ * Include check for leap year.
+ */
+
+extern PGDLLIMPORT const char *const months[]; /* months (3-char
+ * abbreviations) */
+extern PGDLLIMPORT const char *const days[]; /* days (full names) */
+extern PGDLLIMPORT const int day_tab[2][13];
+
+/*
+ * These are the rules for the Gregorian calendar, which was adopted in 1582.
+ * However, we use this calculation for all prior years as well because the
+ * SQL standard specifies use of the Gregorian calendar. This prevents the
+ * date 1500-02-29 from being stored, even though it is valid in the Julian
+ * calendar.
+ */
+#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
+
+
+/*
+ * Datetime input parsing routines (ParseDateTime, DecodeDateTime, etc)
+ * return zero or a positive value on success. On failure, they return
+ * one of these negative code values. DateTimeParseError may be used to
+ * produce a suitable error report. For some of these codes,
+ * DateTimeParseError requires additional information, which is carried
+ * in struct DateTimeErrorExtra.
+ */
+#define DTERR_BAD_FORMAT (-1)
+#define DTERR_FIELD_OVERFLOW (-2)
+#define DTERR_MD_FIELD_OVERFLOW (-3) /* triggers hint about DateStyle */
+#define DTERR_INTERVAL_OVERFLOW (-4)
+#define DTERR_TZDISP_OVERFLOW (-5)
+#define DTERR_BAD_TIMEZONE (-6)
+#define DTERR_BAD_ZONE_ABBREV (-7)
+
+typedef struct DateTimeErrorExtra
+{
+ /* Needed for DTERR_BAD_TIMEZONE and DTERR_BAD_ZONE_ABBREV: */
+ const char *dtee_timezone; /* incorrect time zone name */
+ /* Needed for DTERR_BAD_ZONE_ABBREV: */
+ const char *dtee_abbrev; /* relevant time zone abbreviation */
+} DateTimeErrorExtra;
+
+/* Result codes for DecodeTimezoneName() */
+#define TZNAME_FIXED_OFFSET 0
+#define TZNAME_DYNTZ 1
+#define TZNAME_ZONE 2
+
+
+extern void GetCurrentDateTime(struct pg_tm *tm);
+extern void GetCurrentTimeUsec(struct pg_tm *tm, fsec_t *fsec, int *tzp);
+extern void j2date(int jd, int *year, int *month, int *day);
+extern int date2j(int year, int month, int day);
+
+extern int ParseDateTime(const char *timestr, char *workbuf, size_t buflen,
+ char **field, int *ftype,
+ int maxfields, int *numfields);
+extern int DecodeDateTime(char **field, int *ftype, int nf,
+ int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp,
+ DateTimeErrorExtra *extra);
+extern int DecodeTimezone(const char *str, int *tzp);
+extern int DecodeTimeOnly(char **field, int *ftype, int nf,
+ int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp,
+ DateTimeErrorExtra *extra);
+extern int DecodeInterval(char **field, int *ftype, int nf, int range,
+ int *dtype, struct pg_itm_in *itm_in);
+extern int DecodeISO8601Interval(char *str,
+ int *dtype, struct pg_itm_in *itm_in);
+
+extern void DateTimeParseError(int dterr, DateTimeErrorExtra *extra,
+ const char *str, const char *datatype,
+ struct Node *escontext);
+
+extern int DetermineTimeZoneOffset(struct pg_tm *tm, pg_tz *tzp);
+extern int DetermineTimeZoneAbbrevOffset(struct pg_tm *tm, const char *abbr, pg_tz *tzp);
+extern int DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr,
+ pg_tz *tzp, int *isdst);
+
+extern void EncodeDateOnly(struct pg_tm *tm, int style, char *str);
+extern void EncodeTimeOnly(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str);
+extern void EncodeDateTime(struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str);
+extern void EncodeInterval(struct pg_itm *itm, int style, char *str);
+extern void EncodeSpecialTimestamp(Timestamp dt, char *str);
+
+extern int ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc,
+ struct pg_tm *tm);
+
+extern int DecodeTimezoneAbbrev(int field, const char *lowtoken,
+ int *ftype, int *offset, pg_tz **tz,
+ DateTimeErrorExtra *extra);
+extern int DecodeSpecial(int field, const char *lowtoken, int *val);
+extern int DecodeUnits(int field, const char *lowtoken, int *val);
+
+extern int DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz);
+extern pg_tz *DecodeTimezoneNameToTz(const char *tzname);
+
+extern int j2day(int date);
+
+extern struct Node *TemporalSimplify(int32 max_precis, struct Node *node);
+
+extern bool CheckDateTokenTables(void);
+
+extern TimeZoneAbbrevTable *ConvertTimeZoneAbbrevs(struct tzEntry *abbrevs,
+ int n);
+extern void InstallTimeZoneAbbrevs(TimeZoneAbbrevTable *tbl);
+
+extern bool AdjustTimestampForTypmod(Timestamp *time, int32 typmod,
+ struct Node *escontext);
+
+#endif /* DATETIME_H */
diff --git a/pgsql/include/server/utils/datum.h b/pgsql/include/server/utils/datum.h
new file mode 100644
index 0000000000000000000000000000000000000000..70a47f33c18ed5898a8f69acfa2f7f090c93ca73
--- /dev/null
+++ b/pgsql/include/server/utils/datum.h
@@ -0,0 +1,76 @@
+/*-------------------------------------------------------------------------
+ *
+ * datum.h
+ * POSTGRES Datum (abstract data type) manipulation routines.
+ *
+ * These routines are driven by the 'typbyval' and 'typlen' information,
+ * which must previously have been obtained by the caller for the datatype
+ * of the Datum. (We do it this way because in most situations the caller
+ * can look up the info just once and use it for many per-datum operations.)
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/datum.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DATUM_H
+#define DATUM_H
+
+/*
+ * datumGetSize - find the "real" length of a datum
+ */
+extern Size datumGetSize(Datum value, bool typByVal, int typLen);
+
+/*
+ * datumCopy - make a copy of a non-NULL datum.
+ *
+ * If the datatype is pass-by-reference, memory is obtained with palloc().
+ */
+extern Datum datumCopy(Datum value, bool typByVal, int typLen);
+
+/*
+ * datumTransfer - transfer a non-NULL datum into the current memory context.
+ *
+ * Differs from datumCopy() in its handling of read-write expanded objects.
+ */
+extern Datum datumTransfer(Datum value, bool typByVal, int typLen);
+
+/*
+ * datumIsEqual
+ * return true if two datums of the same type are equal, false otherwise.
+ *
+ * XXX : See comments in the code for restrictions!
+ */
+extern bool datumIsEqual(Datum value1, Datum value2,
+ bool typByVal, int typLen);
+
+/*
+ * datum_image_eq
+ *
+ * Compares two datums for identical contents, based on byte images. Return
+ * true if the two datums are equal, false otherwise.
+ */
+extern bool datum_image_eq(Datum value1, Datum value2,
+ bool typByVal, int typLen);
+
+/*
+ * datum_image_hash
+ *
+ * Generates hash value for 'value' based on its bits rather than logical
+ * value.
+ */
+extern uint32 datum_image_hash(Datum value, bool typByVal, int typLen);
+
+/*
+ * Serialize and restore datums so that we can transfer them to parallel
+ * workers.
+ */
+extern Size datumEstimateSpace(Datum value, bool isnull, bool typByVal,
+ int typLen);
+extern void datumSerialize(Datum value, bool isnull, bool typByVal,
+ int typLen, char **start_address);
+extern Datum datumRestore(char **start_address, bool *isnull);
+
+#endif /* DATUM_H */
diff --git a/pgsql/include/server/utils/dsa.h b/pgsql/include/server/utils/dsa.h
new file mode 100644
index 0000000000000000000000000000000000000000..3ce4ee300a567870d34dc9eabb56c1f561c5133b
--- /dev/null
+++ b/pgsql/include/server/utils/dsa.h
@@ -0,0 +1,127 @@
+/*-------------------------------------------------------------------------
+ *
+ * dsa.h
+ * Dynamic shared memory areas.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/utils/dsa.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DSA_H
+#define DSA_H
+
+#include "port/atomics.h"
+#include "storage/dsm.h"
+
+/* The opaque type used for an area. */
+struct dsa_area;
+typedef struct dsa_area dsa_area;
+
+/*
+ * If this system only uses a 32-bit value for size_t, then use the 32-bit
+ * implementation of DSA. This limits the amount of DSA that can be created
+ * to something significantly less than the entire 4GB address space because
+ * the DSA pointer must encode both a segment identifier and an offset, but
+ * that shouldn't be a significant limitation in practice.
+ *
+ * If this system doesn't support atomic operations on 64-bit values, then
+ * we fall back to 32-bit dsa_pointer for lack of other options.
+ *
+ * For testing purposes, USE_SMALL_DSA_POINTER can be defined to force the use
+ * of 32-bit dsa_pointer even on systems capable of supporting a 64-bit
+ * dsa_pointer.
+ */
+#if SIZEOF_SIZE_T == 4 || !defined(PG_HAVE_ATOMIC_U64_SUPPORT) || \
+ defined(USE_SMALL_DSA_POINTER)
+#define SIZEOF_DSA_POINTER 4
+#else
+#define SIZEOF_DSA_POINTER 8
+#endif
+
+/*
+ * The type of 'relative pointers' to memory allocated by a dynamic shared
+ * area. dsa_pointer values can be shared with other processes, but must be
+ * converted to backend-local pointers before they can be dereferenced. See
+ * dsa_get_address. Also, an atomic version and appropriately sized atomic
+ * operations.
+ */
+#if SIZEOF_DSA_POINTER == 4
+typedef uint32 dsa_pointer;
+typedef pg_atomic_uint32 dsa_pointer_atomic;
+#define dsa_pointer_atomic_init pg_atomic_init_u32
+#define dsa_pointer_atomic_read pg_atomic_read_u32
+#define dsa_pointer_atomic_write pg_atomic_write_u32
+#define dsa_pointer_atomic_fetch_add pg_atomic_fetch_add_u32
+#define dsa_pointer_atomic_compare_exchange pg_atomic_compare_exchange_u32
+#define DSA_POINTER_FORMAT "%08x"
+#else
+typedef uint64 dsa_pointer;
+typedef pg_atomic_uint64 dsa_pointer_atomic;
+#define dsa_pointer_atomic_init pg_atomic_init_u64
+#define dsa_pointer_atomic_read pg_atomic_read_u64
+#define dsa_pointer_atomic_write pg_atomic_write_u64
+#define dsa_pointer_atomic_fetch_add pg_atomic_fetch_add_u64
+#define dsa_pointer_atomic_compare_exchange pg_atomic_compare_exchange_u64
+#define DSA_POINTER_FORMAT "%016" INT64_MODIFIER "x"
+#endif
+
+/* Flags for dsa_allocate_extended. */
+#define DSA_ALLOC_HUGE 0x01 /* allow huge allocation (> 1 GB) */
+#define DSA_ALLOC_NO_OOM 0x02 /* no failure if out-of-memory */
+#define DSA_ALLOC_ZERO 0x04 /* zero allocated memory */
+
+/* A sentinel value for dsa_pointer used to indicate failure to allocate. */
+#define InvalidDsaPointer ((dsa_pointer) 0)
+
+/* Check if a dsa_pointer value is valid. */
+#define DsaPointerIsValid(x) ((x) != InvalidDsaPointer)
+
+/* Allocate uninitialized memory with error on out-of-memory. */
+#define dsa_allocate(area, size) \
+ dsa_allocate_extended(area, size, 0)
+
+/* Allocate zero-initialized memory with error on out-of-memory. */
+#define dsa_allocate0(area, size) \
+ dsa_allocate_extended(area, size, DSA_ALLOC_ZERO)
+
+/*
+ * The type used for dsa_area handles. dsa_handle values can be shared with
+ * other processes, so that they can attach to them. This provides a way to
+ * share allocated storage with other processes.
+ *
+ * The handle for a dsa_area is currently implemented as the dsm_handle
+ * for the first DSM segment backing this dynamic storage area, but client
+ * code shouldn't assume that is true.
+ */
+typedef dsm_handle dsa_handle;
+
+/* Sentinel value to use for invalid dsa_handles. */
+#define DSA_HANDLE_INVALID ((dsa_handle) DSM_HANDLE_INVALID)
+
+
+extern dsa_area *dsa_create(int tranche_id);
+extern dsa_area *dsa_create_in_place(void *place, size_t size,
+ int tranche_id, dsm_segment *segment);
+extern dsa_area *dsa_attach(dsa_handle handle);
+extern dsa_area *dsa_attach_in_place(void *place, dsm_segment *segment);
+extern void dsa_release_in_place(void *place);
+extern void dsa_on_dsm_detach_release_in_place(dsm_segment *, Datum);
+extern void dsa_on_shmem_exit_release_in_place(int, Datum);
+extern void dsa_pin_mapping(dsa_area *area);
+extern void dsa_detach(dsa_area *area);
+extern void dsa_pin(dsa_area *area);
+extern void dsa_unpin(dsa_area *area);
+extern void dsa_set_size_limit(dsa_area *area, size_t limit);
+extern size_t dsa_minimum_size(void);
+extern dsa_handle dsa_get_handle(dsa_area *area);
+extern dsa_pointer dsa_allocate_extended(dsa_area *area, size_t size, int flags);
+extern void dsa_free(dsa_area *area, dsa_pointer dp);
+extern void *dsa_get_address(dsa_area *area, dsa_pointer dp);
+extern void dsa_trim(dsa_area *area);
+extern void dsa_dump(dsa_area *area);
+
+#endif /* DSA_H */
diff --git a/pgsql/include/server/utils/dynahash.h b/pgsql/include/server/utils/dynahash.h
new file mode 100644
index 0000000000000000000000000000000000000000..866677abd863bff018d867320c1c94d3686fb6bd
--- /dev/null
+++ b/pgsql/include/server/utils/dynahash.h
@@ -0,0 +1,20 @@
+/*-------------------------------------------------------------------------
+ *
+ * dynahash.h
+ * POSTGRES dynahash.h file definitions
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/utils/dynahash.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef DYNAHASH_H
+#define DYNAHASH_H
+
+extern int my_log2(long num);
+
+#endif /* DYNAHASH_H */
diff --git a/pgsql/include/server/utils/elog.h b/pgsql/include/server/utils/elog.h
new file mode 100644
index 0000000000000000000000000000000000000000..0292e88b4f293affcb9e7d69520a5e141bea8898
--- /dev/null
+++ b/pgsql/include/server/utils/elog.h
@@ -0,0 +1,545 @@
+/*-------------------------------------------------------------------------
+ *
+ * elog.h
+ * POSTGRES error reporting/logging definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/elog.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef ELOG_H
+#define ELOG_H
+
+#include
+
+#include "lib/stringinfo.h"
+
+/* We cannot include nodes.h yet, so forward-declare struct Node */
+struct Node;
+
+
+/* Error level codes */
+#define DEBUG5 10 /* Debugging messages, in categories of
+ * decreasing detail. */
+#define DEBUG4 11
+#define DEBUG3 12
+#define DEBUG2 13
+#define DEBUG1 14 /* used by GUC debug_* variables */
+#define LOG 15 /* Server operational messages; sent only to
+ * server log by default. */
+#define LOG_SERVER_ONLY 16 /* Same as LOG for server reporting, but never
+ * sent to client. */
+#define COMMERROR LOG_SERVER_ONLY /* Client communication problems; same as
+ * LOG for server reporting, but never
+ * sent to client. */
+#define INFO 17 /* Messages specifically requested by user (eg
+ * VACUUM VERBOSE output); always sent to
+ * client regardless of client_min_messages,
+ * but by default not sent to server log. */
+#define NOTICE 18 /* Helpful messages to users about query
+ * operation; sent to client and not to server
+ * log by default. */
+#define WARNING 19 /* Warnings. NOTICE is for expected messages
+ * like implicit sequence creation by SERIAL.
+ * WARNING is for unexpected messages. */
+#define PGWARNING 19 /* Must equal WARNING; see NOTE below. */
+#define WARNING_CLIENT_ONLY 20 /* Warnings to be sent to client as usual, but
+ * never to the server log. */
+#define ERROR 21 /* user error - abort transaction; return to
+ * known state */
+#define PGERROR 21 /* Must equal ERROR; see NOTE below. */
+#define FATAL 22 /* fatal error - abort process */
+#define PANIC 23 /* take down the other backends with me */
+
+/*
+ * NOTE: the alternate names PGWARNING and PGERROR are useful for dealing
+ * with third-party headers that make other definitions of WARNING and/or
+ * ERROR. One can, for example, re-define ERROR as PGERROR after including
+ * such a header.
+ */
+
+
+/* macros for representing SQLSTATE strings compactly */
+#define PGSIXBIT(ch) (((ch) - '0') & 0x3F)
+#define PGUNSIXBIT(val) (((val) & 0x3F) + '0')
+
+#define MAKE_SQLSTATE(ch1,ch2,ch3,ch4,ch5) \
+ (PGSIXBIT(ch1) + (PGSIXBIT(ch2) << 6) + (PGSIXBIT(ch3) << 12) + \
+ (PGSIXBIT(ch4) << 18) + (PGSIXBIT(ch5) << 24))
+
+/* These macros depend on the fact that '0' becomes a zero in PGSIXBIT */
+#define ERRCODE_TO_CATEGORY(ec) ((ec) & ((1 << 12) - 1))
+#define ERRCODE_IS_CATEGORY(ec) (((ec) & ~((1 << 12) - 1)) == 0)
+
+/* SQLSTATE codes for errors are defined in a separate file */
+#include "utils/errcodes.h"
+
+/*
+ * Provide a way to prevent "errno" from being accidentally used inside an
+ * elog() or ereport() invocation. Since we know that some operating systems
+ * define errno as something involving a function call, we'll put a local
+ * variable of the same name as that function in the local scope to force a
+ * compile error. On platforms that don't define errno in that way, nothing
+ * happens, so we get no warning ... but we can live with that as long as it
+ * happens on some popular platforms.
+ */
+#if defined(errno) && defined(__linux__)
+#define pg_prevent_errno_in_scope() int __errno_location pg_attribute_unused()
+#elif defined(errno) && (defined(__darwin__) || defined(__FreeBSD__))
+#define pg_prevent_errno_in_scope() int __error pg_attribute_unused()
+#else
+#define pg_prevent_errno_in_scope()
+#endif
+
+
+/*----------
+ * New-style error reporting API: to be used in this way:
+ * ereport(ERROR,
+ * errcode(ERRCODE_UNDEFINED_CURSOR),
+ * errmsg("portal \"%s\" not found", stmt->portalname),
+ * ... other errxxx() fields as needed ...);
+ *
+ * The error level is required, and so is a primary error message (errmsg
+ * or errmsg_internal). All else is optional. errcode() defaults to
+ * ERRCODE_INTERNAL_ERROR if elevel is ERROR or more, ERRCODE_WARNING
+ * if elevel is WARNING, or ERRCODE_SUCCESSFUL_COMPLETION if elevel is
+ * NOTICE or below.
+ *
+ * Before Postgres v12, extra parentheses were required around the
+ * list of auxiliary function calls; that's now optional.
+ *
+ * ereport_domain() allows a message domain to be specified, for modules that
+ * wish to use a different message catalog from the backend's. To avoid having
+ * one copy of the default text domain per .o file, we define it as NULL here
+ * and have errstart insert the default text domain. Modules can either use
+ * ereport_domain() directly, or preferably they can override the TEXTDOMAIN
+ * macro.
+ *
+ * When __builtin_constant_p is available and elevel >= ERROR we make a call
+ * to errstart_cold() instead of errstart(). This version of the function is
+ * marked with pg_attribute_cold which will coax supporting compilers into
+ * generating code which is more optimized towards non-ERROR cases. Because
+ * we use __builtin_constant_p() in the condition, when elevel is not a
+ * compile-time constant, or if it is, but it's < ERROR, the compiler has no
+ * need to generate any code for this branch. It can simply call errstart()
+ * unconditionally.
+ *
+ * If elevel >= ERROR, the call will not return; we try to inform the compiler
+ * of that via pg_unreachable(). However, no useful optimization effect is
+ * obtained unless the compiler sees elevel as a compile-time constant, else
+ * we're just adding code bloat. So, if __builtin_constant_p is available,
+ * use that to cause the second if() to vanish completely for non-constant
+ * cases. We avoid using a local variable because it's not necessary and
+ * prevents gcc from making the unreachability deduction at optlevel -O0.
+ *----------
+ */
+#ifdef HAVE__BUILTIN_CONSTANT_P
+#define ereport_domain(elevel, domain, ...) \
+ do { \
+ pg_prevent_errno_in_scope(); \
+ if (__builtin_constant_p(elevel) && (elevel) >= ERROR ? \
+ errstart_cold(elevel, domain) : \
+ errstart(elevel, domain)) \
+ __VA_ARGS__, errfinish(__FILE__, __LINE__, __func__); \
+ if (__builtin_constant_p(elevel) && (elevel) >= ERROR) \
+ pg_unreachable(); \
+ } while(0)
+#else /* !HAVE__BUILTIN_CONSTANT_P */
+#define ereport_domain(elevel, domain, ...) \
+ do { \
+ const int elevel_ = (elevel); \
+ pg_prevent_errno_in_scope(); \
+ if (errstart(elevel_, domain)) \
+ __VA_ARGS__, errfinish(__FILE__, __LINE__, __func__); \
+ if (elevel_ >= ERROR) \
+ pg_unreachable(); \
+ } while(0)
+#endif /* HAVE__BUILTIN_CONSTANT_P */
+
+#define ereport(elevel, ...) \
+ ereport_domain(elevel, TEXTDOMAIN, __VA_ARGS__)
+
+#define TEXTDOMAIN NULL
+
+extern bool message_level_is_interesting(int elevel);
+
+extern bool errstart(int elevel, const char *domain);
+extern pg_attribute_cold bool errstart_cold(int elevel, const char *domain);
+extern void errfinish(const char *filename, int lineno, const char *funcname);
+
+extern int errcode(int sqlerrcode);
+
+extern int errcode_for_file_access(void);
+extern int errcode_for_socket_access(void);
+
+extern int errmsg(const char *fmt,...) pg_attribute_printf(1, 2);
+extern int errmsg_internal(const char *fmt,...) pg_attribute_printf(1, 2);
+
+extern int errmsg_plural(const char *fmt_singular, const char *fmt_plural,
+ unsigned long n,...) pg_attribute_printf(1, 4) pg_attribute_printf(2, 4);
+
+extern int errdetail(const char *fmt,...) pg_attribute_printf(1, 2);
+extern int errdetail_internal(const char *fmt,...) pg_attribute_printf(1, 2);
+
+extern int errdetail_log(const char *fmt,...) pg_attribute_printf(1, 2);
+
+extern int errdetail_log_plural(const char *fmt_singular,
+ const char *fmt_plural,
+ unsigned long n,...) pg_attribute_printf(1, 4) pg_attribute_printf(2, 4);
+
+extern int errdetail_plural(const char *fmt_singular, const char *fmt_plural,
+ unsigned long n,...) pg_attribute_printf(1, 4) pg_attribute_printf(2, 4);
+
+extern int errhint(const char *fmt,...) pg_attribute_printf(1, 2);
+
+extern int errhint_plural(const char *fmt_singular, const char *fmt_plural,
+ unsigned long n,...) pg_attribute_printf(1, 4) pg_attribute_printf(2, 4);
+
+/*
+ * errcontext() is typically called in error context callback functions, not
+ * within an ereport() invocation. The callback function can be in a different
+ * module than the ereport() call, so the message domain passed in errstart()
+ * is not usually the correct domain for translating the context message.
+ * set_errcontext_domain() first sets the domain to be used, and
+ * errcontext_msg() passes the actual message.
+ */
+#define errcontext set_errcontext_domain(TEXTDOMAIN), errcontext_msg
+
+extern int set_errcontext_domain(const char *domain);
+
+extern int errcontext_msg(const char *fmt,...) pg_attribute_printf(1, 2);
+
+extern int errhidestmt(bool hide_stmt);
+extern int errhidecontext(bool hide_ctx);
+
+extern int errbacktrace(void);
+
+extern int errposition(int cursorpos);
+
+extern int internalerrposition(int cursorpos);
+extern int internalerrquery(const char *query);
+
+extern int err_generic_string(int field, const char *str);
+
+extern int geterrcode(void);
+extern int geterrposition(void);
+extern int getinternalerrposition(void);
+
+
+/*----------
+ * Old-style error reporting API: to be used in this way:
+ * elog(ERROR, "portal \"%s\" not found", stmt->portalname);
+ *----------
+ */
+#define elog(elevel, ...) \
+ ereport(elevel, errmsg_internal(__VA_ARGS__))
+
+
+/*----------
+ * Support for reporting "soft" errors that don't require a full transaction
+ * abort to clean up. This is to be used in this way:
+ * errsave(context,
+ * errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ * errmsg("invalid input syntax for type %s: \"%s\"",
+ * "boolean", in_str),
+ * ... other errxxx() fields as needed ...);
+ *
+ * "context" is a node pointer or NULL, and the remaining auxiliary calls
+ * provide the same error details as in ereport(). If context is not a
+ * pointer to an ErrorSaveContext node, then errsave(context, ...)
+ * behaves identically to ereport(ERROR, ...). If context is a pointer
+ * to an ErrorSaveContext node, then the information provided by the
+ * auxiliary calls is stored in the context node and control returns
+ * normally. The caller of errsave() must then do any required cleanup
+ * and return control back to its caller. That caller must check the
+ * ErrorSaveContext node to see whether an error occurred before
+ * it can trust the function's result to be meaningful.
+ *
+ * errsave_domain() allows a message domain to be specified; it is
+ * precisely analogous to ereport_domain().
+ *----------
+ */
+#define errsave_domain(context, domain, ...) \
+ do { \
+ struct Node *context_ = (context); \
+ pg_prevent_errno_in_scope(); \
+ if (errsave_start(context_, domain)) \
+ __VA_ARGS__, errsave_finish(context_, __FILE__, __LINE__, __func__); \
+ } while(0)
+
+#define errsave(context, ...) \
+ errsave_domain(context, TEXTDOMAIN, __VA_ARGS__)
+
+/*
+ * "ereturn(context, dummy_value, ...);" is exactly the same as
+ * "errsave(context, ...); return dummy_value;". This saves a bit
+ * of typing in the common case where a function has no cleanup
+ * actions to take after reporting a soft error. "dummy_value"
+ * can be empty if the function returns void.
+ */
+#define ereturn_domain(context, dummy_value, domain, ...) \
+ do { \
+ errsave_domain(context, domain, __VA_ARGS__); \
+ return dummy_value; \
+ } while(0)
+
+#define ereturn(context, dummy_value, ...) \
+ ereturn_domain(context, dummy_value, TEXTDOMAIN, __VA_ARGS__)
+
+extern bool errsave_start(struct Node *context, const char *domain);
+extern void errsave_finish(struct Node *context,
+ const char *filename, int lineno,
+ const char *funcname);
+
+
+/* Support for constructing error strings separately from ereport() calls */
+
+extern void pre_format_elog_string(int errnumber, const char *domain);
+extern char *format_elog_string(const char *fmt,...) pg_attribute_printf(1, 2);
+
+
+/* Support for attaching context information to error reports */
+
+typedef struct ErrorContextCallback
+{
+ struct ErrorContextCallback *previous;
+ void (*callback) (void *arg);
+ void *arg;
+} ErrorContextCallback;
+
+extern PGDLLIMPORT ErrorContextCallback *error_context_stack;
+
+
+/*----------
+ * API for catching ereport(ERROR) exits. Use these macros like so:
+ *
+ * PG_TRY();
+ * {
+ * ... code that might throw ereport(ERROR) ...
+ * }
+ * PG_CATCH();
+ * {
+ * ... error recovery code ...
+ * }
+ * PG_END_TRY();
+ *
+ * (The braces are not actually necessary, but are recommended so that
+ * pgindent will indent the construct nicely.) The error recovery code
+ * can either do PG_RE_THROW to propagate the error outwards, or do a
+ * (sub)transaction abort. Failure to do so may leave the system in an
+ * inconsistent state for further processing.
+ *
+ * For the common case that the error recovery code and the cleanup in the
+ * normal code path are identical, the following can be used instead:
+ *
+ * PG_TRY();
+ * {
+ * ... code that might throw ereport(ERROR) ...
+ * }
+ * PG_FINALLY();
+ * {
+ * ... cleanup code ...
+ * }
+ * PG_END_TRY();
+ *
+ * The cleanup code will be run in either case, and any error will be rethrown
+ * afterwards.
+ *
+ * You cannot use both PG_CATCH() and PG_FINALLY() in the same
+ * PG_TRY()/PG_END_TRY() block.
+ *
+ * Note: while the system will correctly propagate any new ereport(ERROR)
+ * occurring in the recovery section, there is a small limit on the number
+ * of levels this will work for. It's best to keep the error recovery
+ * section simple enough that it can't generate any new errors, at least
+ * not before popping the error stack.
+ *
+ * Note: an ereport(FATAL) will not be caught by this construct; control will
+ * exit straight through proc_exit(). Therefore, do NOT put any cleanup
+ * of non-process-local resources into the error recovery section, at least
+ * not without taking thought for what will happen during ereport(FATAL).
+ * The PG_ENSURE_ERROR_CLEANUP macros provided by storage/ipc.h may be
+ * helpful in such cases.
+ *
+ * Note: if a local variable of the function containing PG_TRY is modified
+ * in the PG_TRY section and used in the PG_CATCH section, that variable
+ * must be declared "volatile" for POSIX compliance. This is not mere
+ * pedantry; we have seen bugs from compilers improperly optimizing code
+ * away when such a variable was not marked. Beware that gcc's -Wclobbered
+ * warnings are just about entirely useless for catching such oversights.
+ *
+ * Each of these macros accepts an optional argument which can be specified
+ * to apply a suffix to the variables declared within the macros. This suffix
+ * can be used to avoid the compiler emitting warnings about shadowed
+ * variables when compiling with -Wshadow in situations where nested PG_TRY()
+ * statements are required. The optional suffix may contain any character
+ * that's allowed in a variable name. The suffix, if specified, must be the
+ * same within each component macro of the given PG_TRY() statement.
+ *----------
+ */
+#define PG_TRY(...) \
+ do { \
+ sigjmp_buf *_save_exception_stack##__VA_ARGS__ = PG_exception_stack; \
+ ErrorContextCallback *_save_context_stack##__VA_ARGS__ = error_context_stack; \
+ sigjmp_buf _local_sigjmp_buf##__VA_ARGS__; \
+ bool _do_rethrow##__VA_ARGS__ = false; \
+ if (sigsetjmp(_local_sigjmp_buf##__VA_ARGS__, 0) == 0) \
+ { \
+ PG_exception_stack = &_local_sigjmp_buf##__VA_ARGS__
+
+#define PG_CATCH(...) \
+ } \
+ else \
+ { \
+ PG_exception_stack = _save_exception_stack##__VA_ARGS__; \
+ error_context_stack = _save_context_stack##__VA_ARGS__
+
+#define PG_FINALLY(...) \
+ } \
+ else \
+ _do_rethrow##__VA_ARGS__ = true; \
+ { \
+ PG_exception_stack = _save_exception_stack##__VA_ARGS__; \
+ error_context_stack = _save_context_stack##__VA_ARGS__
+
+#define PG_END_TRY(...) \
+ } \
+ if (_do_rethrow##__VA_ARGS__) \
+ PG_RE_THROW(); \
+ PG_exception_stack = _save_exception_stack##__VA_ARGS__; \
+ error_context_stack = _save_context_stack##__VA_ARGS__; \
+ } while (0)
+
+/*
+ * Some compilers understand pg_attribute_noreturn(); for other compilers,
+ * insert pg_unreachable() so that the compiler gets the point.
+ */
+#ifdef HAVE_PG_ATTRIBUTE_NORETURN
+#define PG_RE_THROW() \
+ pg_re_throw()
+#else
+#define PG_RE_THROW() \
+ (pg_re_throw(), pg_unreachable())
+#endif
+
+extern PGDLLIMPORT sigjmp_buf *PG_exception_stack;
+
+
+/* Stuff that error handlers might want to use */
+
+/*
+ * ErrorData holds the data accumulated during any one ereport() cycle.
+ * Any non-NULL pointers must point to palloc'd data.
+ * (The const pointers are an exception; we assume they point at non-freeable
+ * constant strings.)
+ */
+typedef struct ErrorData
+{
+ int elevel; /* error level */
+ bool output_to_server; /* will report to server log? */
+ bool output_to_client; /* will report to client? */
+ bool hide_stmt; /* true to prevent STATEMENT: inclusion */
+ bool hide_ctx; /* true to prevent CONTEXT: inclusion */
+ const char *filename; /* __FILE__ of ereport() call */
+ int lineno; /* __LINE__ of ereport() call */
+ const char *funcname; /* __func__ of ereport() call */
+ const char *domain; /* message domain */
+ const char *context_domain; /* message domain for context message */
+ int sqlerrcode; /* encoded ERRSTATE */
+ char *message; /* primary error message (translated) */
+ char *detail; /* detail error message */
+ char *detail_log; /* detail error message for server log only */
+ char *hint; /* hint message */
+ char *context; /* context message */
+ char *backtrace; /* backtrace */
+ const char *message_id; /* primary message's id (original string) */
+ char *schema_name; /* name of schema */
+ char *table_name; /* name of table */
+ char *column_name; /* name of column */
+ char *datatype_name; /* name of datatype */
+ char *constraint_name; /* name of constraint */
+ int cursorpos; /* cursor index into query string */
+ int internalpos; /* cursor index into internalquery */
+ char *internalquery; /* text of internally-generated query */
+ int saved_errno; /* errno at entry */
+
+ /* context containing associated non-constant strings */
+ struct MemoryContextData *assoc_context;
+} ErrorData;
+
+extern void EmitErrorReport(void);
+extern ErrorData *CopyErrorData(void);
+extern void FreeErrorData(ErrorData *edata);
+extern void FlushErrorState(void);
+extern void ReThrowError(ErrorData *edata) pg_attribute_noreturn();
+extern void ThrowErrorData(ErrorData *edata);
+extern void pg_re_throw(void) pg_attribute_noreturn();
+
+extern char *GetErrorContextStack(void);
+
+/* Hook for intercepting messages before they are sent to the server log */
+typedef void (*emit_log_hook_type) (ErrorData *edata);
+extern PGDLLIMPORT emit_log_hook_type emit_log_hook;
+
+
+/* GUC-configurable parameters */
+
+typedef enum
+{
+ PGERROR_TERSE, /* single-line error messages */
+ PGERROR_DEFAULT, /* recommended style */
+ PGERROR_VERBOSE /* all the facts, ma'am */
+} PGErrorVerbosity;
+
+extern PGDLLIMPORT int Log_error_verbosity;
+extern PGDLLIMPORT char *Log_line_prefix;
+extern PGDLLIMPORT int Log_destination;
+extern PGDLLIMPORT char *Log_destination_string;
+extern PGDLLIMPORT bool syslog_sequence_numbers;
+extern PGDLLIMPORT bool syslog_split_messages;
+
+/* Log destination bitmap */
+#define LOG_DESTINATION_STDERR 1
+#define LOG_DESTINATION_SYSLOG 2
+#define LOG_DESTINATION_EVENTLOG 4
+#define LOG_DESTINATION_CSVLOG 8
+#define LOG_DESTINATION_JSONLOG 16
+
+/* Other exported functions */
+extern void log_status_format(StringInfo buf, const char *format,
+ ErrorData *edata);
+extern void DebugFileOpen(void);
+extern char *unpack_sql_state(int sql_state);
+extern bool in_error_recursion_trouble(void);
+
+/* Common functions shared across destinations */
+extern void reset_formatted_start_time(void);
+extern char *get_formatted_start_time(void);
+extern char *get_formatted_log_time(void);
+extern const char *get_backend_type_for_log(void);
+extern bool check_log_of_query(ErrorData *edata);
+extern const char *error_severity(int elevel);
+extern void write_pipe_chunks(char *data, int len, int dest);
+
+/* Destination-specific functions */
+extern void write_csvlog(ErrorData *edata);
+extern void write_jsonlog(ErrorData *edata);
+
+/*
+ * Write errors to stderr (or by equal means when stderr is
+ * not available). Used before ereport/elog can be used
+ * safely (memory context, GUC load etc)
+ */
+extern void write_stderr(const char *fmt,...) pg_attribute_printf(1, 2);
+
+/*
+ * Write a message to STDERR using only async-signal-safe functions. This can
+ * be used to safely emit a message from a signal handler.
+ */
+extern void write_stderr_signal_safe(const char *fmt);
+
+#endif /* ELOG_H */
diff --git a/pgsql/include/server/utils/errcodes.h b/pgsql/include/server/utils/errcodes.h
new file mode 100644
index 0000000000000000000000000000000000000000..ea243abf44906a0dd636f5163ce462a7b7d574f2
--- /dev/null
+++ b/pgsql/include/server/utils/errcodes.h
@@ -0,0 +1,354 @@
+/* autogenerated from src/backend/utils/errcodes.txt, do not edit */
+/* there is deliberately not an #ifndef ERRCODES_H here */
+
+/* Class 00 - Successful Completion */
+#define ERRCODE_SUCCESSFUL_COMPLETION MAKE_SQLSTATE('0','0','0','0','0')
+
+/* Class 01 - Warning */
+#define ERRCODE_WARNING MAKE_SQLSTATE('0','1','0','0','0')
+#define ERRCODE_WARNING_DYNAMIC_RESULT_SETS_RETURNED MAKE_SQLSTATE('0','1','0','0','C')
+#define ERRCODE_WARNING_IMPLICIT_ZERO_BIT_PADDING MAKE_SQLSTATE('0','1','0','0','8')
+#define ERRCODE_WARNING_NULL_VALUE_ELIMINATED_IN_SET_FUNCTION MAKE_SQLSTATE('0','1','0','0','3')
+#define ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED MAKE_SQLSTATE('0','1','0','0','7')
+#define ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED MAKE_SQLSTATE('0','1','0','0','6')
+#define ERRCODE_WARNING_STRING_DATA_RIGHT_TRUNCATION MAKE_SQLSTATE('0','1','0','0','4')
+#define ERRCODE_WARNING_DEPRECATED_FEATURE MAKE_SQLSTATE('0','1','P','0','1')
+
+/* Class 02 - No Data (this is also a warning class per the SQL standard) */
+#define ERRCODE_NO_DATA MAKE_SQLSTATE('0','2','0','0','0')
+#define ERRCODE_NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED MAKE_SQLSTATE('0','2','0','0','1')
+
+/* Class 03 - SQL Statement Not Yet Complete */
+#define ERRCODE_SQL_STATEMENT_NOT_YET_COMPLETE MAKE_SQLSTATE('0','3','0','0','0')
+
+/* Class 08 - Connection Exception */
+#define ERRCODE_CONNECTION_EXCEPTION MAKE_SQLSTATE('0','8','0','0','0')
+#define ERRCODE_CONNECTION_DOES_NOT_EXIST MAKE_SQLSTATE('0','8','0','0','3')
+#define ERRCODE_CONNECTION_FAILURE MAKE_SQLSTATE('0','8','0','0','6')
+#define ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION MAKE_SQLSTATE('0','8','0','0','1')
+#define ERRCODE_SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION MAKE_SQLSTATE('0','8','0','0','4')
+#define ERRCODE_TRANSACTION_RESOLUTION_UNKNOWN MAKE_SQLSTATE('0','8','0','0','7')
+#define ERRCODE_PROTOCOL_VIOLATION MAKE_SQLSTATE('0','8','P','0','1')
+
+/* Class 09 - Triggered Action Exception */
+#define ERRCODE_TRIGGERED_ACTION_EXCEPTION MAKE_SQLSTATE('0','9','0','0','0')
+
+/* Class 0A - Feature Not Supported */
+#define ERRCODE_FEATURE_NOT_SUPPORTED MAKE_SQLSTATE('0','A','0','0','0')
+
+/* Class 0B - Invalid Transaction Initiation */
+#define ERRCODE_INVALID_TRANSACTION_INITIATION MAKE_SQLSTATE('0','B','0','0','0')
+
+/* Class 0F - Locator Exception */
+#define ERRCODE_LOCATOR_EXCEPTION MAKE_SQLSTATE('0','F','0','0','0')
+#define ERRCODE_L_E_INVALID_SPECIFICATION MAKE_SQLSTATE('0','F','0','0','1')
+
+/* Class 0L - Invalid Grantor */
+#define ERRCODE_INVALID_GRANTOR MAKE_SQLSTATE('0','L','0','0','0')
+#define ERRCODE_INVALID_GRANT_OPERATION MAKE_SQLSTATE('0','L','P','0','1')
+
+/* Class 0P - Invalid Role Specification */
+#define ERRCODE_INVALID_ROLE_SPECIFICATION MAKE_SQLSTATE('0','P','0','0','0')
+
+/* Class 0Z - Diagnostics Exception */
+#define ERRCODE_DIAGNOSTICS_EXCEPTION MAKE_SQLSTATE('0','Z','0','0','0')
+#define ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER MAKE_SQLSTATE('0','Z','0','0','2')
+
+/* Class 20 - Case Not Found */
+#define ERRCODE_CASE_NOT_FOUND MAKE_SQLSTATE('2','0','0','0','0')
+
+/* Class 21 - Cardinality Violation */
+#define ERRCODE_CARDINALITY_VIOLATION MAKE_SQLSTATE('2','1','0','0','0')
+
+/* Class 22 - Data Exception */
+#define ERRCODE_DATA_EXCEPTION MAKE_SQLSTATE('2','2','0','0','0')
+#define ERRCODE_ARRAY_ELEMENT_ERROR MAKE_SQLSTATE('2','2','0','2','E')
+#define ERRCODE_ARRAY_SUBSCRIPT_ERROR MAKE_SQLSTATE('2','2','0','2','E')
+#define ERRCODE_CHARACTER_NOT_IN_REPERTOIRE MAKE_SQLSTATE('2','2','0','2','1')
+#define ERRCODE_DATETIME_FIELD_OVERFLOW MAKE_SQLSTATE('2','2','0','0','8')
+#define ERRCODE_DATETIME_VALUE_OUT_OF_RANGE MAKE_SQLSTATE('2','2','0','0','8')
+#define ERRCODE_DIVISION_BY_ZERO MAKE_SQLSTATE('2','2','0','1','2')
+#define ERRCODE_ERROR_IN_ASSIGNMENT MAKE_SQLSTATE('2','2','0','0','5')
+#define ERRCODE_ESCAPE_CHARACTER_CONFLICT MAKE_SQLSTATE('2','2','0','0','B')
+#define ERRCODE_INDICATOR_OVERFLOW MAKE_SQLSTATE('2','2','0','2','2')
+#define ERRCODE_INTERVAL_FIELD_OVERFLOW MAKE_SQLSTATE('2','2','0','1','5')
+#define ERRCODE_INVALID_ARGUMENT_FOR_LOG MAKE_SQLSTATE('2','2','0','1','E')
+#define ERRCODE_INVALID_ARGUMENT_FOR_NTILE MAKE_SQLSTATE('2','2','0','1','4')
+#define ERRCODE_INVALID_ARGUMENT_FOR_NTH_VALUE MAKE_SQLSTATE('2','2','0','1','6')
+#define ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION MAKE_SQLSTATE('2','2','0','1','F')
+#define ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION MAKE_SQLSTATE('2','2','0','1','G')
+#define ERRCODE_INVALID_CHARACTER_VALUE_FOR_CAST MAKE_SQLSTATE('2','2','0','1','8')
+#define ERRCODE_INVALID_DATETIME_FORMAT MAKE_SQLSTATE('2','2','0','0','7')
+#define ERRCODE_INVALID_ESCAPE_CHARACTER MAKE_SQLSTATE('2','2','0','1','9')
+#define ERRCODE_INVALID_ESCAPE_OCTET MAKE_SQLSTATE('2','2','0','0','D')
+#define ERRCODE_INVALID_ESCAPE_SEQUENCE MAKE_SQLSTATE('2','2','0','2','5')
+#define ERRCODE_NONSTANDARD_USE_OF_ESCAPE_CHARACTER MAKE_SQLSTATE('2','2','P','0','6')
+#define ERRCODE_INVALID_INDICATOR_PARAMETER_VALUE MAKE_SQLSTATE('2','2','0','1','0')
+#define ERRCODE_INVALID_PARAMETER_VALUE MAKE_SQLSTATE('2','2','0','2','3')
+#define ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE MAKE_SQLSTATE('2','2','0','1','3')
+#define ERRCODE_INVALID_REGULAR_EXPRESSION MAKE_SQLSTATE('2','2','0','1','B')
+#define ERRCODE_INVALID_ROW_COUNT_IN_LIMIT_CLAUSE MAKE_SQLSTATE('2','2','0','1','W')
+#define ERRCODE_INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE MAKE_SQLSTATE('2','2','0','1','X')
+#define ERRCODE_INVALID_TABLESAMPLE_ARGUMENT MAKE_SQLSTATE('2','2','0','2','H')
+#define ERRCODE_INVALID_TABLESAMPLE_REPEAT MAKE_SQLSTATE('2','2','0','2','G')
+#define ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE MAKE_SQLSTATE('2','2','0','0','9')
+#define ERRCODE_INVALID_USE_OF_ESCAPE_CHARACTER MAKE_SQLSTATE('2','2','0','0','C')
+#define ERRCODE_MOST_SPECIFIC_TYPE_MISMATCH MAKE_SQLSTATE('2','2','0','0','G')
+#define ERRCODE_NULL_VALUE_NOT_ALLOWED MAKE_SQLSTATE('2','2','0','0','4')
+#define ERRCODE_NULL_VALUE_NO_INDICATOR_PARAMETER MAKE_SQLSTATE('2','2','0','0','2')
+#define ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE MAKE_SQLSTATE('2','2','0','0','3')
+#define ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED MAKE_SQLSTATE('2','2','0','0','H')
+#define ERRCODE_STRING_DATA_LENGTH_MISMATCH MAKE_SQLSTATE('2','2','0','2','6')
+#define ERRCODE_STRING_DATA_RIGHT_TRUNCATION MAKE_SQLSTATE('2','2','0','0','1')
+#define ERRCODE_SUBSTRING_ERROR MAKE_SQLSTATE('2','2','0','1','1')
+#define ERRCODE_TRIM_ERROR MAKE_SQLSTATE('2','2','0','2','7')
+#define ERRCODE_UNTERMINATED_C_STRING MAKE_SQLSTATE('2','2','0','2','4')
+#define ERRCODE_ZERO_LENGTH_CHARACTER_STRING MAKE_SQLSTATE('2','2','0','0','F')
+#define ERRCODE_FLOATING_POINT_EXCEPTION MAKE_SQLSTATE('2','2','P','0','1')
+#define ERRCODE_INVALID_TEXT_REPRESENTATION MAKE_SQLSTATE('2','2','P','0','2')
+#define ERRCODE_INVALID_BINARY_REPRESENTATION MAKE_SQLSTATE('2','2','P','0','3')
+#define ERRCODE_BAD_COPY_FILE_FORMAT MAKE_SQLSTATE('2','2','P','0','4')
+#define ERRCODE_UNTRANSLATABLE_CHARACTER MAKE_SQLSTATE('2','2','P','0','5')
+#define ERRCODE_NOT_AN_XML_DOCUMENT MAKE_SQLSTATE('2','2','0','0','L')
+#define ERRCODE_INVALID_XML_DOCUMENT MAKE_SQLSTATE('2','2','0','0','M')
+#define ERRCODE_INVALID_XML_CONTENT MAKE_SQLSTATE('2','2','0','0','N')
+#define ERRCODE_INVALID_XML_COMMENT MAKE_SQLSTATE('2','2','0','0','S')
+#define ERRCODE_INVALID_XML_PROCESSING_INSTRUCTION MAKE_SQLSTATE('2','2','0','0','T')
+#define ERRCODE_DUPLICATE_JSON_OBJECT_KEY_VALUE MAKE_SQLSTATE('2','2','0','3','0')
+#define ERRCODE_INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION MAKE_SQLSTATE('2','2','0','3','1')
+#define ERRCODE_INVALID_JSON_TEXT MAKE_SQLSTATE('2','2','0','3','2')
+#define ERRCODE_INVALID_SQL_JSON_SUBSCRIPT MAKE_SQLSTATE('2','2','0','3','3')
+#define ERRCODE_MORE_THAN_ONE_SQL_JSON_ITEM MAKE_SQLSTATE('2','2','0','3','4')
+#define ERRCODE_NO_SQL_JSON_ITEM MAKE_SQLSTATE('2','2','0','3','5')
+#define ERRCODE_NON_NUMERIC_SQL_JSON_ITEM MAKE_SQLSTATE('2','2','0','3','6')
+#define ERRCODE_NON_UNIQUE_KEYS_IN_A_JSON_OBJECT MAKE_SQLSTATE('2','2','0','3','7')
+#define ERRCODE_SINGLETON_SQL_JSON_ITEM_REQUIRED MAKE_SQLSTATE('2','2','0','3','8')
+#define ERRCODE_SQL_JSON_ARRAY_NOT_FOUND MAKE_SQLSTATE('2','2','0','3','9')
+#define ERRCODE_SQL_JSON_MEMBER_NOT_FOUND MAKE_SQLSTATE('2','2','0','3','A')
+#define ERRCODE_SQL_JSON_NUMBER_NOT_FOUND MAKE_SQLSTATE('2','2','0','3','B')
+#define ERRCODE_SQL_JSON_OBJECT_NOT_FOUND MAKE_SQLSTATE('2','2','0','3','C')
+#define ERRCODE_TOO_MANY_JSON_ARRAY_ELEMENTS MAKE_SQLSTATE('2','2','0','3','D')
+#define ERRCODE_TOO_MANY_JSON_OBJECT_MEMBERS MAKE_SQLSTATE('2','2','0','3','E')
+#define ERRCODE_SQL_JSON_SCALAR_REQUIRED MAKE_SQLSTATE('2','2','0','3','F')
+#define ERRCODE_SQL_JSON_ITEM_CANNOT_BE_CAST_TO_TARGET_TYPE MAKE_SQLSTATE('2','2','0','3','G')
+
+/* Class 23 - Integrity Constraint Violation */
+#define ERRCODE_INTEGRITY_CONSTRAINT_VIOLATION MAKE_SQLSTATE('2','3','0','0','0')
+#define ERRCODE_RESTRICT_VIOLATION MAKE_SQLSTATE('2','3','0','0','1')
+#define ERRCODE_NOT_NULL_VIOLATION MAKE_SQLSTATE('2','3','5','0','2')
+#define ERRCODE_FOREIGN_KEY_VIOLATION MAKE_SQLSTATE('2','3','5','0','3')
+#define ERRCODE_UNIQUE_VIOLATION MAKE_SQLSTATE('2','3','5','0','5')
+#define ERRCODE_CHECK_VIOLATION MAKE_SQLSTATE('2','3','5','1','4')
+#define ERRCODE_EXCLUSION_VIOLATION MAKE_SQLSTATE('2','3','P','0','1')
+
+/* Class 24 - Invalid Cursor State */
+#define ERRCODE_INVALID_CURSOR_STATE MAKE_SQLSTATE('2','4','0','0','0')
+
+/* Class 25 - Invalid Transaction State */
+#define ERRCODE_INVALID_TRANSACTION_STATE MAKE_SQLSTATE('2','5','0','0','0')
+#define ERRCODE_ACTIVE_SQL_TRANSACTION MAKE_SQLSTATE('2','5','0','0','1')
+#define ERRCODE_BRANCH_TRANSACTION_ALREADY_ACTIVE MAKE_SQLSTATE('2','5','0','0','2')
+#define ERRCODE_HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL MAKE_SQLSTATE('2','5','0','0','8')
+#define ERRCODE_INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION MAKE_SQLSTATE('2','5','0','0','3')
+#define ERRCODE_INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION MAKE_SQLSTATE('2','5','0','0','4')
+#define ERRCODE_NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION MAKE_SQLSTATE('2','5','0','0','5')
+#define ERRCODE_READ_ONLY_SQL_TRANSACTION MAKE_SQLSTATE('2','5','0','0','6')
+#define ERRCODE_SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED MAKE_SQLSTATE('2','5','0','0','7')
+#define ERRCODE_NO_ACTIVE_SQL_TRANSACTION MAKE_SQLSTATE('2','5','P','0','1')
+#define ERRCODE_IN_FAILED_SQL_TRANSACTION MAKE_SQLSTATE('2','5','P','0','2')
+#define ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT MAKE_SQLSTATE('2','5','P','0','3')
+
+/* Class 26 - Invalid SQL Statement Name */
+#define ERRCODE_INVALID_SQL_STATEMENT_NAME MAKE_SQLSTATE('2','6','0','0','0')
+
+/* Class 27 - Triggered Data Change Violation */
+#define ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION MAKE_SQLSTATE('2','7','0','0','0')
+
+/* Class 28 - Invalid Authorization Specification */
+#define ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION MAKE_SQLSTATE('2','8','0','0','0')
+#define ERRCODE_INVALID_PASSWORD MAKE_SQLSTATE('2','8','P','0','1')
+
+/* Class 2B - Dependent Privilege Descriptors Still Exist */
+#define ERRCODE_DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST MAKE_SQLSTATE('2','B','0','0','0')
+#define ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST MAKE_SQLSTATE('2','B','P','0','1')
+
+/* Class 2D - Invalid Transaction Termination */
+#define ERRCODE_INVALID_TRANSACTION_TERMINATION MAKE_SQLSTATE('2','D','0','0','0')
+
+/* Class 2F - SQL Routine Exception */
+#define ERRCODE_SQL_ROUTINE_EXCEPTION MAKE_SQLSTATE('2','F','0','0','0')
+#define ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT MAKE_SQLSTATE('2','F','0','0','5')
+#define ERRCODE_S_R_E_MODIFYING_SQL_DATA_NOT_PERMITTED MAKE_SQLSTATE('2','F','0','0','2')
+#define ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED MAKE_SQLSTATE('2','F','0','0','3')
+#define ERRCODE_S_R_E_READING_SQL_DATA_NOT_PERMITTED MAKE_SQLSTATE('2','F','0','0','4')
+
+/* Class 34 - Invalid Cursor Name */
+#define ERRCODE_INVALID_CURSOR_NAME MAKE_SQLSTATE('3','4','0','0','0')
+
+/* Class 38 - External Routine Exception */
+#define ERRCODE_EXTERNAL_ROUTINE_EXCEPTION MAKE_SQLSTATE('3','8','0','0','0')
+#define ERRCODE_E_R_E_CONTAINING_SQL_NOT_PERMITTED MAKE_SQLSTATE('3','8','0','0','1')
+#define ERRCODE_E_R_E_MODIFYING_SQL_DATA_NOT_PERMITTED MAKE_SQLSTATE('3','8','0','0','2')
+#define ERRCODE_E_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED MAKE_SQLSTATE('3','8','0','0','3')
+#define ERRCODE_E_R_E_READING_SQL_DATA_NOT_PERMITTED MAKE_SQLSTATE('3','8','0','0','4')
+
+/* Class 39 - External Routine Invocation Exception */
+#define ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION MAKE_SQLSTATE('3','9','0','0','0')
+#define ERRCODE_E_R_I_E_INVALID_SQLSTATE_RETURNED MAKE_SQLSTATE('3','9','0','0','1')
+#define ERRCODE_E_R_I_E_NULL_VALUE_NOT_ALLOWED MAKE_SQLSTATE('3','9','0','0','4')
+#define ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED MAKE_SQLSTATE('3','9','P','0','1')
+#define ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED MAKE_SQLSTATE('3','9','P','0','2')
+#define ERRCODE_E_R_I_E_EVENT_TRIGGER_PROTOCOL_VIOLATED MAKE_SQLSTATE('3','9','P','0','3')
+
+/* Class 3B - Savepoint Exception */
+#define ERRCODE_SAVEPOINT_EXCEPTION MAKE_SQLSTATE('3','B','0','0','0')
+#define ERRCODE_S_E_INVALID_SPECIFICATION MAKE_SQLSTATE('3','B','0','0','1')
+
+/* Class 3D - Invalid Catalog Name */
+#define ERRCODE_INVALID_CATALOG_NAME MAKE_SQLSTATE('3','D','0','0','0')
+
+/* Class 3F - Invalid Schema Name */
+#define ERRCODE_INVALID_SCHEMA_NAME MAKE_SQLSTATE('3','F','0','0','0')
+
+/* Class 40 - Transaction Rollback */
+#define ERRCODE_TRANSACTION_ROLLBACK MAKE_SQLSTATE('4','0','0','0','0')
+#define ERRCODE_T_R_INTEGRITY_CONSTRAINT_VIOLATION MAKE_SQLSTATE('4','0','0','0','2')
+#define ERRCODE_T_R_SERIALIZATION_FAILURE MAKE_SQLSTATE('4','0','0','0','1')
+#define ERRCODE_T_R_STATEMENT_COMPLETION_UNKNOWN MAKE_SQLSTATE('4','0','0','0','3')
+#define ERRCODE_T_R_DEADLOCK_DETECTED MAKE_SQLSTATE('4','0','P','0','1')
+
+/* Class 42 - Syntax Error or Access Rule Violation */
+#define ERRCODE_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION MAKE_SQLSTATE('4','2','0','0','0')
+#define ERRCODE_SYNTAX_ERROR MAKE_SQLSTATE('4','2','6','0','1')
+#define ERRCODE_INSUFFICIENT_PRIVILEGE MAKE_SQLSTATE('4','2','5','0','1')
+#define ERRCODE_CANNOT_COERCE MAKE_SQLSTATE('4','2','8','4','6')
+#define ERRCODE_GROUPING_ERROR MAKE_SQLSTATE('4','2','8','0','3')
+#define ERRCODE_WINDOWING_ERROR MAKE_SQLSTATE('4','2','P','2','0')
+#define ERRCODE_INVALID_RECURSION MAKE_SQLSTATE('4','2','P','1','9')
+#define ERRCODE_INVALID_FOREIGN_KEY MAKE_SQLSTATE('4','2','8','3','0')
+#define ERRCODE_INVALID_NAME MAKE_SQLSTATE('4','2','6','0','2')
+#define ERRCODE_NAME_TOO_LONG MAKE_SQLSTATE('4','2','6','2','2')
+#define ERRCODE_RESERVED_NAME MAKE_SQLSTATE('4','2','9','3','9')
+#define ERRCODE_DATATYPE_MISMATCH MAKE_SQLSTATE('4','2','8','0','4')
+#define ERRCODE_INDETERMINATE_DATATYPE MAKE_SQLSTATE('4','2','P','1','8')
+#define ERRCODE_COLLATION_MISMATCH MAKE_SQLSTATE('4','2','P','2','1')
+#define ERRCODE_INDETERMINATE_COLLATION MAKE_SQLSTATE('4','2','P','2','2')
+#define ERRCODE_WRONG_OBJECT_TYPE MAKE_SQLSTATE('4','2','8','0','9')
+#define ERRCODE_GENERATED_ALWAYS MAKE_SQLSTATE('4','2','8','C','9')
+#define ERRCODE_UNDEFINED_COLUMN MAKE_SQLSTATE('4','2','7','0','3')
+#define ERRCODE_UNDEFINED_CURSOR MAKE_SQLSTATE('3','4','0','0','0')
+#define ERRCODE_UNDEFINED_DATABASE MAKE_SQLSTATE('3','D','0','0','0')
+#define ERRCODE_UNDEFINED_FUNCTION MAKE_SQLSTATE('4','2','8','8','3')
+#define ERRCODE_UNDEFINED_PSTATEMENT MAKE_SQLSTATE('2','6','0','0','0')
+#define ERRCODE_UNDEFINED_SCHEMA MAKE_SQLSTATE('3','F','0','0','0')
+#define ERRCODE_UNDEFINED_TABLE MAKE_SQLSTATE('4','2','P','0','1')
+#define ERRCODE_UNDEFINED_PARAMETER MAKE_SQLSTATE('4','2','P','0','2')
+#define ERRCODE_UNDEFINED_OBJECT MAKE_SQLSTATE('4','2','7','0','4')
+#define ERRCODE_DUPLICATE_COLUMN MAKE_SQLSTATE('4','2','7','0','1')
+#define ERRCODE_DUPLICATE_CURSOR MAKE_SQLSTATE('4','2','P','0','3')
+#define ERRCODE_DUPLICATE_DATABASE MAKE_SQLSTATE('4','2','P','0','4')
+#define ERRCODE_DUPLICATE_FUNCTION MAKE_SQLSTATE('4','2','7','2','3')
+#define ERRCODE_DUPLICATE_PSTATEMENT MAKE_SQLSTATE('4','2','P','0','5')
+#define ERRCODE_DUPLICATE_SCHEMA MAKE_SQLSTATE('4','2','P','0','6')
+#define ERRCODE_DUPLICATE_TABLE MAKE_SQLSTATE('4','2','P','0','7')
+#define ERRCODE_DUPLICATE_ALIAS MAKE_SQLSTATE('4','2','7','1','2')
+#define ERRCODE_DUPLICATE_OBJECT MAKE_SQLSTATE('4','2','7','1','0')
+#define ERRCODE_AMBIGUOUS_COLUMN MAKE_SQLSTATE('4','2','7','0','2')
+#define ERRCODE_AMBIGUOUS_FUNCTION MAKE_SQLSTATE('4','2','7','2','5')
+#define ERRCODE_AMBIGUOUS_PARAMETER MAKE_SQLSTATE('4','2','P','0','8')
+#define ERRCODE_AMBIGUOUS_ALIAS MAKE_SQLSTATE('4','2','P','0','9')
+#define ERRCODE_INVALID_COLUMN_REFERENCE MAKE_SQLSTATE('4','2','P','1','0')
+#define ERRCODE_INVALID_COLUMN_DEFINITION MAKE_SQLSTATE('4','2','6','1','1')
+#define ERRCODE_INVALID_CURSOR_DEFINITION MAKE_SQLSTATE('4','2','P','1','1')
+#define ERRCODE_INVALID_DATABASE_DEFINITION MAKE_SQLSTATE('4','2','P','1','2')
+#define ERRCODE_INVALID_FUNCTION_DEFINITION MAKE_SQLSTATE('4','2','P','1','3')
+#define ERRCODE_INVALID_PSTATEMENT_DEFINITION MAKE_SQLSTATE('4','2','P','1','4')
+#define ERRCODE_INVALID_SCHEMA_DEFINITION MAKE_SQLSTATE('4','2','P','1','5')
+#define ERRCODE_INVALID_TABLE_DEFINITION MAKE_SQLSTATE('4','2','P','1','6')
+#define ERRCODE_INVALID_OBJECT_DEFINITION MAKE_SQLSTATE('4','2','P','1','7')
+
+/* Class 44 - WITH CHECK OPTION Violation */
+#define ERRCODE_WITH_CHECK_OPTION_VIOLATION MAKE_SQLSTATE('4','4','0','0','0')
+
+/* Class 53 - Insufficient Resources */
+#define ERRCODE_INSUFFICIENT_RESOURCES MAKE_SQLSTATE('5','3','0','0','0')
+#define ERRCODE_DISK_FULL MAKE_SQLSTATE('5','3','1','0','0')
+#define ERRCODE_OUT_OF_MEMORY MAKE_SQLSTATE('5','3','2','0','0')
+#define ERRCODE_TOO_MANY_CONNECTIONS MAKE_SQLSTATE('5','3','3','0','0')
+#define ERRCODE_CONFIGURATION_LIMIT_EXCEEDED MAKE_SQLSTATE('5','3','4','0','0')
+
+/* Class 54 - Program Limit Exceeded */
+#define ERRCODE_PROGRAM_LIMIT_EXCEEDED MAKE_SQLSTATE('5','4','0','0','0')
+#define ERRCODE_STATEMENT_TOO_COMPLEX MAKE_SQLSTATE('5','4','0','0','1')
+#define ERRCODE_TOO_MANY_COLUMNS MAKE_SQLSTATE('5','4','0','1','1')
+#define ERRCODE_TOO_MANY_ARGUMENTS MAKE_SQLSTATE('5','4','0','2','3')
+
+/* Class 55 - Object Not In Prerequisite State */
+#define ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE MAKE_SQLSTATE('5','5','0','0','0')
+#define ERRCODE_OBJECT_IN_USE MAKE_SQLSTATE('5','5','0','0','6')
+#define ERRCODE_CANT_CHANGE_RUNTIME_PARAM MAKE_SQLSTATE('5','5','P','0','2')
+#define ERRCODE_LOCK_NOT_AVAILABLE MAKE_SQLSTATE('5','5','P','0','3')
+#define ERRCODE_UNSAFE_NEW_ENUM_VALUE_USAGE MAKE_SQLSTATE('5','5','P','0','4')
+
+/* Class 57 - Operator Intervention */
+#define ERRCODE_OPERATOR_INTERVENTION MAKE_SQLSTATE('5','7','0','0','0')
+#define ERRCODE_QUERY_CANCELED MAKE_SQLSTATE('5','7','0','1','4')
+#define ERRCODE_ADMIN_SHUTDOWN MAKE_SQLSTATE('5','7','P','0','1')
+#define ERRCODE_CRASH_SHUTDOWN MAKE_SQLSTATE('5','7','P','0','2')
+#define ERRCODE_CANNOT_CONNECT_NOW MAKE_SQLSTATE('5','7','P','0','3')
+#define ERRCODE_DATABASE_DROPPED MAKE_SQLSTATE('5','7','P','0','4')
+#define ERRCODE_IDLE_SESSION_TIMEOUT MAKE_SQLSTATE('5','7','P','0','5')
+
+/* Class 58 - System Error (errors external to PostgreSQL itself) */
+#define ERRCODE_SYSTEM_ERROR MAKE_SQLSTATE('5','8','0','0','0')
+#define ERRCODE_IO_ERROR MAKE_SQLSTATE('5','8','0','3','0')
+#define ERRCODE_UNDEFINED_FILE MAKE_SQLSTATE('5','8','P','0','1')
+#define ERRCODE_DUPLICATE_FILE MAKE_SQLSTATE('5','8','P','0','2')
+
+/* Class 72 - Snapshot Failure */
+#define ERRCODE_SNAPSHOT_TOO_OLD MAKE_SQLSTATE('7','2','0','0','0')
+
+/* Class F0 - Configuration File Error */
+#define ERRCODE_CONFIG_FILE_ERROR MAKE_SQLSTATE('F','0','0','0','0')
+#define ERRCODE_LOCK_FILE_EXISTS MAKE_SQLSTATE('F','0','0','0','1')
+
+/* Class HV - Foreign Data Wrapper Error (SQL/MED) */
+#define ERRCODE_FDW_ERROR MAKE_SQLSTATE('H','V','0','0','0')
+#define ERRCODE_FDW_COLUMN_NAME_NOT_FOUND MAKE_SQLSTATE('H','V','0','0','5')
+#define ERRCODE_FDW_DYNAMIC_PARAMETER_VALUE_NEEDED MAKE_SQLSTATE('H','V','0','0','2')
+#define ERRCODE_FDW_FUNCTION_SEQUENCE_ERROR MAKE_SQLSTATE('H','V','0','1','0')
+#define ERRCODE_FDW_INCONSISTENT_DESCRIPTOR_INFORMATION MAKE_SQLSTATE('H','V','0','2','1')
+#define ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE MAKE_SQLSTATE('H','V','0','2','4')
+#define ERRCODE_FDW_INVALID_COLUMN_NAME MAKE_SQLSTATE('H','V','0','0','7')
+#define ERRCODE_FDW_INVALID_COLUMN_NUMBER MAKE_SQLSTATE('H','V','0','0','8')
+#define ERRCODE_FDW_INVALID_DATA_TYPE MAKE_SQLSTATE('H','V','0','0','4')
+#define ERRCODE_FDW_INVALID_DATA_TYPE_DESCRIPTORS MAKE_SQLSTATE('H','V','0','0','6')
+#define ERRCODE_FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER MAKE_SQLSTATE('H','V','0','9','1')
+#define ERRCODE_FDW_INVALID_HANDLE MAKE_SQLSTATE('H','V','0','0','B')
+#define ERRCODE_FDW_INVALID_OPTION_INDEX MAKE_SQLSTATE('H','V','0','0','C')
+#define ERRCODE_FDW_INVALID_OPTION_NAME MAKE_SQLSTATE('H','V','0','0','D')
+#define ERRCODE_FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH MAKE_SQLSTATE('H','V','0','9','0')
+#define ERRCODE_FDW_INVALID_STRING_FORMAT MAKE_SQLSTATE('H','V','0','0','A')
+#define ERRCODE_FDW_INVALID_USE_OF_NULL_POINTER MAKE_SQLSTATE('H','V','0','0','9')
+#define ERRCODE_FDW_TOO_MANY_HANDLES MAKE_SQLSTATE('H','V','0','1','4')
+#define ERRCODE_FDW_OUT_OF_MEMORY MAKE_SQLSTATE('H','V','0','0','1')
+#define ERRCODE_FDW_NO_SCHEMAS MAKE_SQLSTATE('H','V','0','0','P')
+#define ERRCODE_FDW_OPTION_NAME_NOT_FOUND MAKE_SQLSTATE('H','V','0','0','J')
+#define ERRCODE_FDW_REPLY_HANDLE MAKE_SQLSTATE('H','V','0','0','K')
+#define ERRCODE_FDW_SCHEMA_NOT_FOUND MAKE_SQLSTATE('H','V','0','0','Q')
+#define ERRCODE_FDW_TABLE_NOT_FOUND MAKE_SQLSTATE('H','V','0','0','R')
+#define ERRCODE_FDW_UNABLE_TO_CREATE_EXECUTION MAKE_SQLSTATE('H','V','0','0','L')
+#define ERRCODE_FDW_UNABLE_TO_CREATE_REPLY MAKE_SQLSTATE('H','V','0','0','M')
+#define ERRCODE_FDW_UNABLE_TO_ESTABLISH_CONNECTION MAKE_SQLSTATE('H','V','0','0','N')
+
+/* Class P0 - PL/pgSQL Error */
+#define ERRCODE_PLPGSQL_ERROR MAKE_SQLSTATE('P','0','0','0','0')
+#define ERRCODE_RAISE_EXCEPTION MAKE_SQLSTATE('P','0','0','0','1')
+#define ERRCODE_NO_DATA_FOUND MAKE_SQLSTATE('P','0','0','0','2')
+#define ERRCODE_TOO_MANY_ROWS MAKE_SQLSTATE('P','0','0','0','3')
+#define ERRCODE_ASSERT_FAILURE MAKE_SQLSTATE('P','0','0','0','4')
+
+/* Class XX - Internal Error */
+#define ERRCODE_INTERNAL_ERROR MAKE_SQLSTATE('X','X','0','0','0')
+#define ERRCODE_DATA_CORRUPTED MAKE_SQLSTATE('X','X','0','0','1')
+#define ERRCODE_INDEX_CORRUPTED MAKE_SQLSTATE('X','X','0','0','2')
diff --git a/pgsql/include/server/utils/evtcache.h b/pgsql/include/server/utils/evtcache.h
new file mode 100644
index 0000000000000000000000000000000000000000..d340026518ae9a3d7ac5953f57958927f7e5fd0a
--- /dev/null
+++ b/pgsql/include/server/utils/evtcache.h
@@ -0,0 +1,37 @@
+/*-------------------------------------------------------------------------
+ *
+ * evtcache.h
+ * Special-purpose cache for event trigger data.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/utils/evtcache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef EVTCACHE_H
+#define EVTCACHE_H
+
+#include "nodes/bitmapset.h"
+#include "nodes/pg_list.h"
+
+typedef enum
+{
+ EVT_DDLCommandStart,
+ EVT_DDLCommandEnd,
+ EVT_SQLDrop,
+ EVT_TableRewrite
+} EventTriggerEvent;
+
+typedef struct
+{
+ Oid fnoid; /* function to be called */
+ char enabled; /* as SESSION_REPLICATION_ROLE_* */
+ Bitmapset *tagset; /* command tags, or NULL if empty */
+} EventTriggerCacheItem;
+
+extern List *EventCacheLookup(EventTriggerEvent event);
+
+#endif /* EVTCACHE_H */
diff --git a/pgsql/include/server/utils/expandeddatum.h b/pgsql/include/server/utils/expandeddatum.h
new file mode 100644
index 0000000000000000000000000000000000000000..a77bb7e7e9ae3817333194ae1ac67f9475ad1cf4
--- /dev/null
+++ b/pgsql/include/server/utils/expandeddatum.h
@@ -0,0 +1,170 @@
+/*-------------------------------------------------------------------------
+ *
+ * expandeddatum.h
+ * Declarations for access to "expanded" value representations.
+ *
+ * Complex data types, particularly container types such as arrays and
+ * records, usually have on-disk representations that are compact but not
+ * especially convenient to modify. What's more, when we do modify them,
+ * having to recopy all the rest of the value can be extremely inefficient.
+ * Therefore, we provide a notion of an "expanded" representation that is used
+ * only in memory and is optimized more for computation than storage.
+ * The format appearing on disk is called the data type's "flattened"
+ * representation, since it is required to be a contiguous blob of bytes --
+ * but the type can have an expanded representation that is not. Data types
+ * must provide means to translate an expanded representation back to
+ * flattened form.
+ *
+ * An expanded object is meant to survive across multiple operations, but
+ * not to be enormously long-lived; for example it might be a local variable
+ * in a PL/pgSQL procedure. So its extra bulk compared to the on-disk format
+ * is a worthwhile trade-off.
+ *
+ * References to expanded objects are a type of TOAST pointer.
+ * Because of longstanding conventions in Postgres, this means that the
+ * flattened form of such an object must always be a varlena object.
+ * Fortunately that's no restriction in practice.
+ *
+ * There are actually two kinds of TOAST pointers for expanded objects:
+ * read-only and read-write pointers. Possession of one of the latter
+ * authorizes a function to modify the value in-place rather than copying it
+ * as would normally be required. Functions should always return a read-write
+ * pointer to any new expanded object they create. Functions that modify an
+ * argument value in-place must take care that they do not corrupt the old
+ * value if they fail partway through.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/expandeddatum.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef EXPANDEDDATUM_H
+#define EXPANDEDDATUM_H
+
+#include "varatt.h"
+
+/* Size of an EXTERNAL datum that contains a pointer to an expanded object */
+#define EXPANDED_POINTER_SIZE (VARHDRSZ_EXTERNAL + sizeof(varatt_expanded))
+
+/*
+ * "Methods" that must be provided for any expanded object.
+ *
+ * get_flat_size: compute space needed for flattened representation (total,
+ * including header).
+ *
+ * flatten_into: construct flattened representation in the caller-allocated
+ * space at *result, of size allocated_size (which will always be the result
+ * of a preceding get_flat_size call; it's passed for cross-checking).
+ *
+ * The flattened representation must be a valid in-line, non-compressed,
+ * 4-byte-header varlena object.
+ *
+ * Note: construction of a heap tuple from an expanded datum calls
+ * get_flat_size twice, so it's worthwhile to make sure that that doesn't
+ * incur too much overhead.
+ */
+typedef Size (*EOM_get_flat_size_method) (ExpandedObjectHeader *eohptr);
+typedef void (*EOM_flatten_into_method) (ExpandedObjectHeader *eohptr,
+ void *result, Size allocated_size);
+
+/* Struct of function pointers for an expanded object's methods */
+typedef struct ExpandedObjectMethods
+{
+ EOM_get_flat_size_method get_flat_size;
+ EOM_flatten_into_method flatten_into;
+} ExpandedObjectMethods;
+
+/*
+ * Every expanded object must contain this header; typically the header
+ * is embedded in some larger struct that adds type-specific fields.
+ *
+ * It is presumed that the header object and all subsidiary data are stored
+ * in eoh_context, so that the object can be freed by deleting that context,
+ * or its storage lifespan can be altered by reparenting the context.
+ * (In principle the object could own additional resources, such as malloc'd
+ * storage, and use a memory context reset callback to free them upon reset or
+ * deletion of eoh_context.)
+ *
+ * We set up two TOAST pointers within the standard header, one read-write
+ * and one read-only. This allows functions to return either kind of pointer
+ * without making an additional allocation, and in particular without worrying
+ * whether a separately palloc'd object would have sufficient lifespan.
+ * But note that these pointers are just a convenience; a pointer object
+ * appearing somewhere else would still be legal.
+ *
+ * The typedef declaration for this appears in postgres.h.
+ */
+struct ExpandedObjectHeader
+{
+ /* Phony varlena header */
+ int32 vl_len_; /* always EOH_HEADER_MAGIC, see below */
+
+ /* Pointer to methods required for object type */
+ const ExpandedObjectMethods *eoh_methods;
+
+ /* Memory context containing this header and subsidiary data */
+ MemoryContext eoh_context;
+
+ /* Standard R/W TOAST pointer for this object is kept here */
+ char eoh_rw_ptr[EXPANDED_POINTER_SIZE];
+
+ /* Standard R/O TOAST pointer for this object is kept here */
+ char eoh_ro_ptr[EXPANDED_POINTER_SIZE];
+};
+
+/*
+ * Particularly for read-only functions, it is handy to be able to work with
+ * either regular "flat" varlena inputs or expanded inputs of the same data
+ * type. To allow determining which case an argument-fetching function has
+ * returned, the first int32 of an ExpandedObjectHeader always contains -1
+ * (EOH_HEADER_MAGIC to the code). This works since no 4-byte-header varlena
+ * could have that as its first 4 bytes. Caution: we could not reliably tell
+ * the difference between an ExpandedObjectHeader and a short-header object
+ * with this trick. However, it works fine if the argument fetching code
+ * always returns either a 4-byte-header flat object or an expanded object.
+ */
+#define EOH_HEADER_MAGIC (-1)
+#define VARATT_IS_EXPANDED_HEADER(PTR) \
+ (((varattrib_4b *) (PTR))->va_4byte.va_header == (uint32) EOH_HEADER_MAGIC)
+
+/*
+ * Generic support functions for expanded objects.
+ * (More of these might be worth inlining later.)
+ */
+
+static inline Datum
+EOHPGetRWDatum(const struct ExpandedObjectHeader *eohptr)
+{
+ return PointerGetDatum(eohptr->eoh_rw_ptr);
+}
+
+static inline Datum
+EOHPGetRODatum(const struct ExpandedObjectHeader *eohptr)
+{
+ return PointerGetDatum(eohptr->eoh_ro_ptr);
+}
+
+/* Does the Datum represent a writable expanded object? */
+#define DatumIsReadWriteExpandedObject(d, isnull, typlen) \
+ (((isnull) || (typlen) != -1) ? false : \
+ VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(d)))
+
+#define MakeExpandedObjectReadOnly(d, isnull, typlen) \
+ (((isnull) || (typlen) != -1) ? (d) : \
+ MakeExpandedObjectReadOnlyInternal(d))
+
+extern ExpandedObjectHeader *DatumGetEOHP(Datum d);
+extern void EOH_init_header(ExpandedObjectHeader *eohptr,
+ const ExpandedObjectMethods *methods,
+ MemoryContext obj_context);
+extern Size EOH_get_flat_size(ExpandedObjectHeader *eohptr);
+extern void EOH_flatten_into(ExpandedObjectHeader *eohptr,
+ void *result, Size allocated_size);
+extern Datum MakeExpandedObjectReadOnlyInternal(Datum d);
+extern Datum TransferExpandedObject(Datum d, MemoryContext new_parent);
+extern void DeleteExpandedObject(Datum d);
+
+#endif /* EXPANDEDDATUM_H */
diff --git a/pgsql/include/server/utils/expandedrecord.h b/pgsql/include/server/utils/expandedrecord.h
new file mode 100644
index 0000000000000000000000000000000000000000..7e7c114b829a2acfb335a7fb52b20ed18a55edfb
--- /dev/null
+++ b/pgsql/include/server/utils/expandedrecord.h
@@ -0,0 +1,241 @@
+/*-------------------------------------------------------------------------
+ *
+ * expandedrecord.h
+ * Declarations for composite expanded objects.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/expandedrecord.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef EXPANDEDRECORD_H
+#define EXPANDEDRECORD_H
+
+#include "access/htup.h"
+#include "access/tupdesc.h"
+#include "fmgr.h"
+#include "utils/expandeddatum.h"
+
+
+/*
+ * An expanded record is contained within a private memory context (as
+ * all expanded objects must be) and has a control structure as below.
+ *
+ * The expanded record might contain a regular "flat" tuple if that was the
+ * original input and we've not modified it. Otherwise, the contents are
+ * represented by Datum/isnull arrays plus type information. We could also
+ * have both forms, if we've deconstructed the original tuple for access
+ * purposes but not yet changed it. For pass-by-reference field types, the
+ * Datums would point into the flat tuple in this situation. Once we start
+ * modifying tuple fields, new pass-by-ref fields are separately palloc'd
+ * within the memory context.
+ *
+ * It's possible to build an expanded record that references a "flat" tuple
+ * stored externally, if the caller can guarantee that that tuple will not
+ * change for the lifetime of the expanded record. (This frammish is mainly
+ * meant to avoid unnecessary data copying in trigger functions.)
+ */
+#define ER_MAGIC 1384727874 /* ID for debugging crosschecks */
+
+typedef struct ExpandedRecordHeader
+{
+ /* Standard header for expanded objects */
+ ExpandedObjectHeader hdr;
+
+ /* Magic value identifying an expanded record (for debugging only) */
+ int er_magic;
+
+ /* Assorted flag bits */
+ int flags;
+#define ER_FLAG_FVALUE_VALID 0x0001 /* fvalue is up to date? */
+#define ER_FLAG_FVALUE_ALLOCED 0x0002 /* fvalue is local storage? */
+#define ER_FLAG_DVALUES_VALID 0x0004 /* dvalues/dnulls are up to date? */
+#define ER_FLAG_DVALUES_ALLOCED 0x0008 /* any field values local storage? */
+#define ER_FLAG_HAVE_EXTERNAL 0x0010 /* any field values are external? */
+#define ER_FLAG_TUPDESC_ALLOCED 0x0020 /* tupdesc is local storage? */
+#define ER_FLAG_IS_DOMAIN 0x0040 /* er_decltypeid is domain? */
+#define ER_FLAG_IS_DUMMY 0x0080 /* this header is dummy (see below) */
+/* flag bits that are not to be cleared when replacing tuple data: */
+#define ER_FLAGS_NON_DATA \
+ (ER_FLAG_TUPDESC_ALLOCED | ER_FLAG_IS_DOMAIN | ER_FLAG_IS_DUMMY)
+
+ /* Declared type of the record variable (could be a domain type) */
+ Oid er_decltypeid;
+
+ /*
+ * Actual composite type/typmod; never a domain (if ER_FLAG_IS_DOMAIN,
+ * these identify the composite base type). These will match
+ * er_tupdesc->tdtypeid/tdtypmod, as well as the header fields of
+ * composite datums made from or stored in this expanded record.
+ */
+ Oid er_typeid; /* type OID of the composite type */
+ int32 er_typmod; /* typmod of the composite type */
+
+ /*
+ * Tuple descriptor, if we have one, else NULL. This may point to a
+ * reference-counted tupdesc originally belonging to the typcache, in
+ * which case we use a memory context reset callback to release the
+ * refcount. It can also be locally allocated in this object's private
+ * context (in which case ER_FLAG_TUPDESC_ALLOCED is set).
+ */
+ TupleDesc er_tupdesc;
+
+ /*
+ * Unique-within-process identifier for the tupdesc (see typcache.h). This
+ * field will never be equal to INVALID_TUPLEDESC_IDENTIFIER.
+ */
+ uint64 er_tupdesc_id;
+
+ /*
+ * If we have a Datum-array representation of the record, it's kept here;
+ * else ER_FLAG_DVALUES_VALID is not set, and dvalues/dnulls may be NULL
+ * if they've not yet been allocated. If allocated, the dvalues and
+ * dnulls arrays are palloc'd within the object private context, and are
+ * of length matching er_tupdesc->natts. For pass-by-ref field types,
+ * dvalues entries might point either into the fstartptr..fendptr area, or
+ * to separately palloc'd chunks.
+ */
+ Datum *dvalues; /* array of Datums */
+ bool *dnulls; /* array of is-null flags for Datums */
+ int nfields; /* length of above arrays */
+
+ /*
+ * flat_size is the current space requirement for the flat equivalent of
+ * the expanded record, if known; otherwise it's 0. We store this to make
+ * consecutive calls of get_flat_size cheap. If flat_size is not 0, the
+ * component values data_len, hoff, and hasnull must be valid too.
+ */
+ Size flat_size;
+
+ Size data_len; /* data len within flat_size */
+ int hoff; /* header offset */
+ bool hasnull; /* null bitmap needed? */
+
+ /*
+ * fvalue points to the flat representation if we have one, else it is
+ * NULL. If the flat representation is valid (up to date) then
+ * ER_FLAG_FVALUE_VALID is set. Even if we've outdated the flat
+ * representation due to changes of user fields, it can still be used to
+ * fetch system column values. If we have a flat representation then
+ * fstartptr/fendptr point to the start and end+1 of its data area; this
+ * is so that we can tell which Datum pointers point into the flat
+ * representation rather than being pointers to separately palloc'd data.
+ */
+ HeapTuple fvalue; /* might or might not be private storage */
+ char *fstartptr; /* start of its data area */
+ char *fendptr; /* end+1 of its data area */
+
+ /* Some operations on the expanded record need a short-lived context */
+ MemoryContext er_short_term_cxt; /* short-term memory context */
+
+ /* Working state for domain checking, used if ER_FLAG_IS_DOMAIN is set */
+ struct ExpandedRecordHeader *er_dummy_header; /* dummy record header */
+ void *er_domaininfo; /* cache space for domain_check() */
+
+ /* Callback info (it's active if er_mcb.arg is not NULL) */
+ MemoryContextCallback er_mcb;
+} ExpandedRecordHeader;
+
+/* fmgr functions and macros for expanded record objects */
+static inline Datum
+ExpandedRecordGetDatum(const ExpandedRecordHeader *erh)
+{
+ return EOHPGetRWDatum(&erh->hdr);
+}
+
+static inline Datum
+ExpandedRecordGetRODatum(const ExpandedRecordHeader *erh)
+{
+ return EOHPGetRODatum(&erh->hdr);
+}
+
+#define PG_GETARG_EXPANDED_RECORD(n) DatumGetExpandedRecord(PG_GETARG_DATUM(n))
+#define PG_RETURN_EXPANDED_RECORD(x) PG_RETURN_DATUM(ExpandedRecordGetDatum(x))
+
+/* assorted other macros */
+#define ExpandedRecordIsEmpty(erh) \
+ (((erh)->flags & (ER_FLAG_DVALUES_VALID | ER_FLAG_FVALUE_VALID)) == 0)
+#define ExpandedRecordIsDomain(erh) \
+ (((erh)->flags & ER_FLAG_IS_DOMAIN) != 0)
+
+/* this can substitute for TransferExpandedObject() when we already have erh */
+#define TransferExpandedRecord(erh, cxt) \
+ MemoryContextSetParent((erh)->hdr.eoh_context, cxt)
+
+/* information returned by expanded_record_lookup_field() */
+typedef struct ExpandedRecordFieldInfo
+{
+ int fnumber; /* field's attr number in record */
+ Oid ftypeid; /* field's type/typmod info */
+ int32 ftypmod;
+ Oid fcollation; /* field's collation if any */
+} ExpandedRecordFieldInfo;
+
+/*
+ * prototypes for functions defined in expandedrecord.c
+ */
+extern ExpandedRecordHeader *make_expanded_record_from_typeid(Oid type_id, int32 typmod,
+ MemoryContext parentcontext);
+extern ExpandedRecordHeader *make_expanded_record_from_tupdesc(TupleDesc tupdesc,
+ MemoryContext parentcontext);
+extern ExpandedRecordHeader *make_expanded_record_from_exprecord(ExpandedRecordHeader *olderh,
+ MemoryContext parentcontext);
+extern void expanded_record_set_tuple(ExpandedRecordHeader *erh,
+ HeapTuple tuple, bool copy, bool expand_external);
+extern Datum make_expanded_record_from_datum(Datum recorddatum,
+ MemoryContext parentcontext);
+extern TupleDesc expanded_record_fetch_tupdesc(ExpandedRecordHeader *erh);
+extern HeapTuple expanded_record_get_tuple(ExpandedRecordHeader *erh);
+extern ExpandedRecordHeader *DatumGetExpandedRecord(Datum d);
+extern void deconstruct_expanded_record(ExpandedRecordHeader *erh);
+extern bool expanded_record_lookup_field(ExpandedRecordHeader *erh,
+ const char *fieldname,
+ ExpandedRecordFieldInfo *finfo);
+extern Datum expanded_record_fetch_field(ExpandedRecordHeader *erh, int fnumber,
+ bool *isnull);
+extern void expanded_record_set_field_internal(ExpandedRecordHeader *erh,
+ int fnumber,
+ Datum newValue, bool isnull,
+ bool expand_external,
+ bool check_constraints);
+extern void expanded_record_set_fields(ExpandedRecordHeader *erh,
+ const Datum *newValues, const bool *isnulls,
+ bool expand_external);
+
+/* outside code should never call expanded_record_set_field_internal as such */
+#define expanded_record_set_field(erh, fnumber, newValue, isnull, expand_external) \
+ expanded_record_set_field_internal(erh, fnumber, newValue, isnull, expand_external, true)
+
+/*
+ * Inline-able fast cases. The expanded_record_fetch_xxx functions above
+ * handle the general cases.
+ */
+
+/* Get the tupdesc for the expanded record's actual type */
+static inline TupleDesc
+expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
+{
+ if (likely(erh->er_tupdesc != NULL))
+ return erh->er_tupdesc;
+ else
+ return expanded_record_fetch_tupdesc(erh);
+}
+
+/* Get value of record field */
+static inline Datum
+expanded_record_get_field(ExpandedRecordHeader *erh, int fnumber,
+ bool *isnull)
+{
+ if ((erh->flags & ER_FLAG_DVALUES_VALID) &&
+ likely(fnumber > 0 && fnumber <= erh->nfields))
+ {
+ *isnull = erh->dnulls[fnumber - 1];
+ return erh->dvalues[fnumber - 1];
+ }
+ else
+ return expanded_record_fetch_field(erh, fnumber, isnull);
+}
+
+#endif /* EXPANDEDRECORD_H */
diff --git a/pgsql/include/server/utils/float.h b/pgsql/include/server/utils/float.h
new file mode 100644
index 0000000000000000000000000000000000000000..7529899d63c65dc6aa18d656d4af63d8c1727b89
--- /dev/null
+++ b/pgsql/include/server/utils/float.h
@@ -0,0 +1,357 @@
+/*-------------------------------------------------------------------------
+ *
+ * float.h
+ * Definitions for the built-in floating-point types
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ *
+ * IDENTIFICATION
+ * src/include/utils/float.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FLOAT_H
+#define FLOAT_H
+
+#include
+
+/* X/Open (XSI) requires to provide M_PI, but core POSIX does not */
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+/* Radians per degree, a.k.a. PI / 180 */
+#define RADIANS_PER_DEGREE 0.0174532925199432957692
+
+/* Visual C++ etc lacks NAN, and won't accept 0.0/0.0. */
+#if defined(WIN32) && !defined(NAN)
+static const uint32 nan[2] = {0xffffffff, 0x7fffffff};
+
+#define NAN (*(const float8 *) nan)
+#endif
+
+extern PGDLLIMPORT int extra_float_digits;
+
+/*
+ * Utility functions in float.c
+ */
+extern void float_overflow_error(void) pg_attribute_noreturn();
+extern void float_underflow_error(void) pg_attribute_noreturn();
+extern void float_zero_divide_error(void) pg_attribute_noreturn();
+extern int is_infinite(float8 val);
+extern float8 float8in_internal(char *num, char **endptr_p,
+ const char *type_name, const char *orig_string,
+ struct Node *escontext);
+extern float4 float4in_internal(char *num, char **endptr_p,
+ const char *type_name, const char *orig_string,
+ struct Node *escontext);
+extern char *float8out_internal(float8 num);
+extern int float4_cmp_internal(float4 a, float4 b);
+extern int float8_cmp_internal(float8 a, float8 b);
+
+/*
+ * Routines to provide reasonably platform-independent handling of
+ * infinity and NaN
+ *
+ * We assume that isinf() and isnan() are available and work per spec.
+ * (On some platforms, we have to supply our own; see src/port.) However,
+ * generating an Infinity or NaN in the first place is less well standardized;
+ * pre-C99 systems tend not to have C99's INFINITY and NaN macros. We
+ * centralize our workarounds for this here.
+ */
+
+/*
+ * The funny placements of the two #pragmas is necessary because of a
+ * long lived bug in the Microsoft compilers.
+ * See http://support.microsoft.com/kb/120968/en-us for details
+ */
+#ifdef _MSC_VER
+#pragma warning(disable:4756)
+#endif
+static inline float4
+get_float4_infinity(void)
+{
+#ifdef INFINITY
+ /* C99 standard way */
+ return (float4) INFINITY;
+#else
+#ifdef _MSC_VER
+#pragma warning(default:4756)
+#endif
+
+ /*
+ * On some platforms, HUGE_VAL is an infinity, elsewhere it's just the
+ * largest normal float8. We assume forcing an overflow will get us a
+ * true infinity.
+ */
+ return (float4) (HUGE_VAL * HUGE_VAL);
+#endif
+}
+
+static inline float8
+get_float8_infinity(void)
+{
+#ifdef INFINITY
+ /* C99 standard way */
+ return (float8) INFINITY;
+#else
+
+ /*
+ * On some platforms, HUGE_VAL is an infinity, elsewhere it's just the
+ * largest normal float8. We assume forcing an overflow will get us a
+ * true infinity.
+ */
+ return (float8) (HUGE_VAL * HUGE_VAL);
+#endif
+}
+
+static inline float4
+get_float4_nan(void)
+{
+#ifdef NAN
+ /* C99 standard way */
+ return (float4) NAN;
+#else
+ /* Assume we can get a NAN via zero divide */
+ return (float4) (0.0 / 0.0);
+#endif
+}
+
+static inline float8
+get_float8_nan(void)
+{
+ /* (float8) NAN doesn't work on some NetBSD/MIPS releases */
+#if defined(NAN) && !(defined(__NetBSD__) && defined(__mips__))
+ /* C99 standard way */
+ return (float8) NAN;
+#else
+ /* Assume we can get a NaN via zero divide */
+ return (float8) (0.0 / 0.0);
+#endif
+}
+
+/*
+ * Floating-point arithmetic with overflow/underflow reported as errors
+ *
+ * There isn't any way to check for underflow of addition/subtraction
+ * because numbers near the underflow value have already been rounded to
+ * the point where we can't detect that the two values were originally
+ * different, e.g. on x86, '1e-45'::float4 == '2e-45'::float4 ==
+ * 1.4013e-45.
+ */
+
+static inline float4
+float4_pl(const float4 val1, const float4 val2)
+{
+ float4 result;
+
+ result = val1 + val2;
+ if (unlikely(isinf(result)) && !isinf(val1) && !isinf(val2))
+ float_overflow_error();
+
+ return result;
+}
+
+static inline float8
+float8_pl(const float8 val1, const float8 val2)
+{
+ float8 result;
+
+ result = val1 + val2;
+ if (unlikely(isinf(result)) && !isinf(val1) && !isinf(val2))
+ float_overflow_error();
+
+ return result;
+}
+
+static inline float4
+float4_mi(const float4 val1, const float4 val2)
+{
+ float4 result;
+
+ result = val1 - val2;
+ if (unlikely(isinf(result)) && !isinf(val1) && !isinf(val2))
+ float_overflow_error();
+
+ return result;
+}
+
+static inline float8
+float8_mi(const float8 val1, const float8 val2)
+{
+ float8 result;
+
+ result = val1 - val2;
+ if (unlikely(isinf(result)) && !isinf(val1) && !isinf(val2))
+ float_overflow_error();
+
+ return result;
+}
+
+static inline float4
+float4_mul(const float4 val1, const float4 val2)
+{
+ float4 result;
+
+ result = val1 * val2;
+ if (unlikely(isinf(result)) && !isinf(val1) && !isinf(val2))
+ float_overflow_error();
+ if (unlikely(result == 0.0f) && val1 != 0.0f && val2 != 0.0f)
+ float_underflow_error();
+
+ return result;
+}
+
+static inline float8
+float8_mul(const float8 val1, const float8 val2)
+{
+ float8 result;
+
+ result = val1 * val2;
+ if (unlikely(isinf(result)) && !isinf(val1) && !isinf(val2))
+ float_overflow_error();
+ if (unlikely(result == 0.0) && val1 != 0.0 && val2 != 0.0)
+ float_underflow_error();
+
+ return result;
+}
+
+static inline float4
+float4_div(const float4 val1, const float4 val2)
+{
+ float4 result;
+
+ if (unlikely(val2 == 0.0f) && !isnan(val1))
+ float_zero_divide_error();
+ result = val1 / val2;
+ if (unlikely(isinf(result)) && !isinf(val1))
+ float_overflow_error();
+ if (unlikely(result == 0.0f) && val1 != 0.0f && !isinf(val2))
+ float_underflow_error();
+
+ return result;
+}
+
+static inline float8
+float8_div(const float8 val1, const float8 val2)
+{
+ float8 result;
+
+ if (unlikely(val2 == 0.0) && !isnan(val1))
+ float_zero_divide_error();
+ result = val1 / val2;
+ if (unlikely(isinf(result)) && !isinf(val1))
+ float_overflow_error();
+ if (unlikely(result == 0.0) && val1 != 0.0 && !isinf(val2))
+ float_underflow_error();
+
+ return result;
+}
+
+/*
+ * Routines for NaN-aware comparisons
+ *
+ * We consider all NaNs to be equal and larger than any non-NaN. This is
+ * somewhat arbitrary; the important thing is to have a consistent sort
+ * order.
+ */
+
+static inline bool
+float4_eq(const float4 val1, const float4 val2)
+{
+ return isnan(val1) ? isnan(val2) : !isnan(val2) && val1 == val2;
+}
+
+static inline bool
+float8_eq(const float8 val1, const float8 val2)
+{
+ return isnan(val1) ? isnan(val2) : !isnan(val2) && val1 == val2;
+}
+
+static inline bool
+float4_ne(const float4 val1, const float4 val2)
+{
+ return isnan(val1) ? !isnan(val2) : isnan(val2) || val1 != val2;
+}
+
+static inline bool
+float8_ne(const float8 val1, const float8 val2)
+{
+ return isnan(val1) ? !isnan(val2) : isnan(val2) || val1 != val2;
+}
+
+static inline bool
+float4_lt(const float4 val1, const float4 val2)
+{
+ return !isnan(val1) && (isnan(val2) || val1 < val2);
+}
+
+static inline bool
+float8_lt(const float8 val1, const float8 val2)
+{
+ return !isnan(val1) && (isnan(val2) || val1 < val2);
+}
+
+static inline bool
+float4_le(const float4 val1, const float4 val2)
+{
+ return isnan(val2) || (!isnan(val1) && val1 <= val2);
+}
+
+static inline bool
+float8_le(const float8 val1, const float8 val2)
+{
+ return isnan(val2) || (!isnan(val1) && val1 <= val2);
+}
+
+static inline bool
+float4_gt(const float4 val1, const float4 val2)
+{
+ return !isnan(val2) && (isnan(val1) || val1 > val2);
+}
+
+static inline bool
+float8_gt(const float8 val1, const float8 val2)
+{
+ return !isnan(val2) && (isnan(val1) || val1 > val2);
+}
+
+static inline bool
+float4_ge(const float4 val1, const float4 val2)
+{
+ return isnan(val1) || (!isnan(val2) && val1 >= val2);
+}
+
+static inline bool
+float8_ge(const float8 val1, const float8 val2)
+{
+ return isnan(val1) || (!isnan(val2) && val1 >= val2);
+}
+
+static inline float4
+float4_min(const float4 val1, const float4 val2)
+{
+ return float4_lt(val1, val2) ? val1 : val2;
+}
+
+static inline float8
+float8_min(const float8 val1, const float8 val2)
+{
+ return float8_lt(val1, val2) ? val1 : val2;
+}
+
+static inline float4
+float4_max(const float4 val1, const float4 val2)
+{
+ return float4_gt(val1, val2) ? val1 : val2;
+}
+
+static inline float8
+float8_max(const float8 val1, const float8 val2)
+{
+ return float8_gt(val1, val2) ? val1 : val2;
+}
+
+#endif /* FLOAT_H */
diff --git a/pgsql/include/server/utils/fmgroids.h b/pgsql/include/server/utils/fmgroids.h
new file mode 100644
index 0000000000000000000000000000000000000000..75a112dea422dbf73e4ea830a526ddb5f54e1e64
--- /dev/null
+++ b/pgsql/include/server/utils/fmgroids.h
@@ -0,0 +1,3314 @@
+/*-------------------------------------------------------------------------
+ *
+ * fmgroids.h
+ * Macros that define the OIDs of built-in functions.
+ *
+ * These macros can be used to avoid a catalog lookup when a specific
+ * fmgr-callable function needs to be referenced.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES
+ * ******************************
+ * *** DO NOT EDIT THIS FILE! ***
+ * ******************************
+ *
+ * It has been GENERATED by src/backend/utils/Gen_fmgrtab.pl
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FMGROIDS_H
+#define FMGROIDS_H
+
+/*
+ * Constant macros for the OIDs of entries in pg_proc.
+ *
+ * F_XXX macros are named after the proname field; if that is not unique,
+ * we append the proargtypes field, replacing spaces with underscores.
+ * For example, we have F_OIDEQ because that proname is unique, but
+ * F_POW_FLOAT8_FLOAT8 (among others) because that proname is not.
+ */
+#define F_HEAP_TABLEAM_HANDLER 3
+#define F_BYTEAOUT 31
+#define F_CHAROUT 33
+#define F_NAMEIN 34
+#define F_NAMEOUT 35
+#define F_INT2IN 38
+#define F_INT2OUT 39
+#define F_INT2VECTORIN 40
+#define F_INT2VECTOROUT 41
+#define F_INT4IN 42
+#define F_INT4OUT 43
+#define F_REGPROCIN 44
+#define F_REGPROCOUT 45
+#define F_TEXTIN 46
+#define F_TEXTOUT 47
+#define F_TIDIN 48
+#define F_TIDOUT 49
+#define F_XIDIN 50
+#define F_XIDOUT 51
+#define F_CIDIN 52
+#define F_CIDOUT 53
+#define F_OIDVECTORIN 54
+#define F_OIDVECTOROUT 55
+#define F_BOOLLT 56
+#define F_BOOLGT 57
+#define F_BOOLEQ 60
+#define F_CHAREQ 61
+#define F_NAMEEQ 62
+#define F_INT2EQ 63
+#define F_INT2LT 64
+#define F_INT4EQ 65
+#define F_INT4LT 66
+#define F_TEXTEQ 67
+#define F_XIDEQ 68
+#define F_CIDEQ 69
+#define F_CHARNE 70
+#define F_CHARLE 72
+#define F_CHARGT 73
+#define F_CHARGE 74
+#define F_INT4_CHAR 77
+#define F_CHAR_INT4 78
+#define F_NAMEREGEXEQ 79
+#define F_BOOLNE 84
+#define F_PG_DDL_COMMAND_IN 86
+#define F_PG_DDL_COMMAND_OUT 87
+#define F_PG_DDL_COMMAND_RECV 88
+#define F_VERSION 89
+#define F_PG_DDL_COMMAND_SEND 90
+#define F_EQSEL 101
+#define F_NEQSEL 102
+#define F_SCALARLTSEL 103
+#define F_SCALARGTSEL 104
+#define F_EQJOINSEL 105
+#define F_NEQJOINSEL 106
+#define F_SCALARLTJOINSEL 107
+#define F_SCALARGTJOINSEL 108
+#define F_UNKNOWNIN 109
+#define F_UNKNOWNOUT 110
+#define F_BOX_ABOVE_EQ 115
+#define F_BOX_BELOW_EQ 116
+#define F_POINT_IN 117
+#define F_POINT_OUT 118
+#define F_LSEG_IN 119
+#define F_LSEG_OUT 120
+#define F_PATH_IN 121
+#define F_PATH_OUT 122
+#define F_BOX_IN 123
+#define F_BOX_OUT 124
+#define F_BOX_OVERLAP 125
+#define F_BOX_GE 126
+#define F_BOX_GT 127
+#define F_BOX_EQ 128
+#define F_BOX_LT 129
+#define F_BOX_LE 130
+#define F_POINT_ABOVE 131
+#define F_POINT_LEFT 132
+#define F_POINT_RIGHT 133
+#define F_POINT_BELOW 134
+#define F_POINT_EQ 135
+#define F_ON_PB 136
+#define F_ON_PPATH 137
+#define F_BOX_CENTER 138
+#define F_AREASEL 139
+#define F_AREAJOINSEL 140
+#define F_INT4MUL 141
+#define F_INT4NE 144
+#define F_INT2NE 145
+#define F_INT2GT 146
+#define F_INT4GT 147
+#define F_INT2LE 148
+#define F_INT4LE 149
+#define F_INT4GE 150
+#define F_INT2GE 151
+#define F_INT2MUL 152
+#define F_INT2DIV 153
+#define F_INT4DIV 154
+#define F_INT2MOD 155
+#define F_INT4MOD 156
+#define F_TEXTNE 157
+#define F_INT24EQ 158
+#define F_INT42EQ 159
+#define F_INT24LT 160
+#define F_INT42LT 161
+#define F_INT24GT 162
+#define F_INT42GT 163
+#define F_INT24NE 164
+#define F_INT42NE 165
+#define F_INT24LE 166
+#define F_INT42LE 167
+#define F_INT24GE 168
+#define F_INT42GE 169
+#define F_INT24MUL 170
+#define F_INT42MUL 171
+#define F_INT24DIV 172
+#define F_INT42DIV 173
+#define F_INT2PL 176
+#define F_INT4PL 177
+#define F_INT24PL 178
+#define F_INT42PL 179
+#define F_INT2MI 180
+#define F_INT4MI 181
+#define F_INT24MI 182
+#define F_INT42MI 183
+#define F_OIDEQ 184
+#define F_OIDNE 185
+#define F_BOX_SAME 186
+#define F_BOX_CONTAIN 187
+#define F_BOX_LEFT 188
+#define F_BOX_OVERLEFT 189
+#define F_BOX_OVERRIGHT 190
+#define F_BOX_RIGHT 191
+#define F_BOX_CONTAINED 192
+#define F_BOX_CONTAIN_PT 193
+#define F_PG_NODE_TREE_IN 195
+#define F_PG_NODE_TREE_OUT 196
+#define F_PG_NODE_TREE_RECV 197
+#define F_PG_NODE_TREE_SEND 198
+#define F_FLOAT4IN 200
+#define F_FLOAT4OUT 201
+#define F_FLOAT4MUL 202
+#define F_FLOAT4DIV 203
+#define F_FLOAT4PL 204
+#define F_FLOAT4MI 205
+#define F_FLOAT4UM 206
+#define F_FLOAT4ABS 207
+#define F_FLOAT4_ACCUM 208
+#define F_FLOAT4LARGER 209
+#define F_FLOAT4SMALLER 211
+#define F_INT4UM 212
+#define F_INT2UM 213
+#define F_FLOAT8IN 214
+#define F_FLOAT8OUT 215
+#define F_FLOAT8MUL 216
+#define F_FLOAT8DIV 217
+#define F_FLOAT8PL 218
+#define F_FLOAT8MI 219
+#define F_FLOAT8UM 220
+#define F_FLOAT8ABS 221
+#define F_FLOAT8_ACCUM 222
+#define F_FLOAT8LARGER 223
+#define F_FLOAT8SMALLER 224
+#define F_LSEG_CENTER 225
+#define F_POLY_CENTER 227
+#define F_DROUND 228
+#define F_DTRUNC 229
+#define F_DSQRT 230
+#define F_DCBRT 231
+#define F_DPOW 232
+#define F_DEXP 233
+#define F_DLOG1 234
+#define F_FLOAT8_INT2 235
+#define F_FLOAT4_INT2 236
+#define F_INT2_FLOAT8 237
+#define F_INT2_FLOAT4 238
+#define F_LINE_DISTANCE 239
+#define F_NAMEEQTEXT 240
+#define F_NAMELTTEXT 241
+#define F_NAMELETEXT 242
+#define F_NAMEGETEXT 243
+#define F_NAMEGTTEXT 244
+#define F_NAMENETEXT 245
+#define F_BTNAMETEXTCMP 246
+#define F_TEXTEQNAME 247
+#define F_TEXTLTNAME 248
+#define F_TEXTLENAME 249
+#define F_TEXTGENAME 250
+#define F_TEXTGTNAME 251
+#define F_TEXTNENAME 252
+#define F_BTTEXTNAMECMP 253
+#define F_NAMECONCATOID 266
+#define F_TABLE_AM_HANDLER_IN 267
+#define F_TABLE_AM_HANDLER_OUT 268
+#define F_TIMEOFDAY 274
+#define F_PG_NEXTOID 275
+#define F_FLOAT8_COMBINE 276
+#define F_INTER_SL 277
+#define F_INTER_LB 278
+#define F_FLOAT48MUL 279
+#define F_FLOAT48DIV 280
+#define F_FLOAT48PL 281
+#define F_FLOAT48MI 282
+#define F_FLOAT84MUL 283
+#define F_FLOAT84DIV 284
+#define F_FLOAT84PL 285
+#define F_FLOAT84MI 286
+#define F_FLOAT4EQ 287
+#define F_FLOAT4NE 288
+#define F_FLOAT4LT 289
+#define F_FLOAT4LE 290
+#define F_FLOAT4GT 291
+#define F_FLOAT4GE 292
+#define F_FLOAT8EQ 293
+#define F_FLOAT8NE 294
+#define F_FLOAT8LT 295
+#define F_FLOAT8LE 296
+#define F_FLOAT8GT 297
+#define F_FLOAT8GE 298
+#define F_FLOAT48EQ 299
+#define F_FLOAT48NE 300
+#define F_FLOAT48LT 301
+#define F_FLOAT48LE 302
+#define F_FLOAT48GT 303
+#define F_FLOAT48GE 304
+#define F_FLOAT84EQ 305
+#define F_FLOAT84NE 306
+#define F_FLOAT84LT 307
+#define F_FLOAT84LE 308
+#define F_FLOAT84GT 309
+#define F_FLOAT84GE 310
+#define F_FLOAT8_FLOAT4 311
+#define F_FLOAT4_FLOAT8 312
+#define F_INT4_INT2 313
+#define F_INT2_INT4 314
+#define F_PG_JIT_AVAILABLE 315
+#define F_FLOAT8_INT4 316
+#define F_INT4_FLOAT8 317
+#define F_FLOAT4_INT4 318
+#define F_INT4_FLOAT4 319
+#define F_WIDTH_BUCKET_FLOAT8_FLOAT8_FLOAT8_INT4 320
+#define F_JSON_IN 321
+#define F_JSON_OUT 322
+#define F_JSON_RECV 323
+#define F_JSON_SEND 324
+#define F_INDEX_AM_HANDLER_IN 326
+#define F_INDEX_AM_HANDLER_OUT 327
+#define F_HASHMACADDR8 328
+#define F_HASH_ACLITEM 329
+#define F_BTHANDLER 330
+#define F_HASHHANDLER 331
+#define F_GISTHANDLER 332
+#define F_GINHANDLER 333
+#define F_SPGHANDLER 334
+#define F_BRINHANDLER 335
+#define F_SCALARLESEL 336
+#define F_SCALARGESEL 337
+#define F_AMVALIDATE 338
+#define F_POLY_SAME 339
+#define F_POLY_CONTAIN 340
+#define F_POLY_LEFT 341
+#define F_POLY_OVERLEFT 342
+#define F_POLY_OVERRIGHT 343
+#define F_POLY_RIGHT 344
+#define F_POLY_CONTAINED 345
+#define F_POLY_OVERLAP 346
+#define F_POLY_IN 347
+#define F_POLY_OUT 348
+#define F_BTINT2CMP 350
+#define F_BTINT4CMP 351
+#define F_BTFLOAT4CMP 354
+#define F_BTFLOAT8CMP 355
+#define F_BTOIDCMP 356
+#define F_DIST_BP 357
+#define F_BTCHARCMP 358
+#define F_BTNAMECMP 359
+#define F_BTTEXTCMP 360
+#define F_LSEG_DISTANCE 361
+#define F_LSEG_INTERPT 362
+#define F_DIST_PS 363
+#define F_DIST_PB 364
+#define F_DIST_SB 365
+#define F_CLOSE_PS 366
+#define F_CLOSE_PB 367
+#define F_CLOSE_SB 368
+#define F_ON_PS 369
+#define F_PATH_DISTANCE 370
+#define F_DIST_PPATH 371
+#define F_ON_SB 372
+#define F_INTER_SB 373
+#define F_STRING_TO_ARRAY_TEXT_TEXT_TEXT 376
+#define F_CASH_CMP 377
+#define F_ARRAY_APPEND 378
+#define F_ARRAY_PREPEND 379
+#define F_DIST_SP 380
+#define F_DIST_BS 381
+#define F_BTARRAYCMP 382
+#define F_ARRAY_CAT 383
+#define F_ARRAY_TO_STRING_ANYARRAY_TEXT_TEXT 384
+#define F_SCALARLEJOINSEL 386
+#define F_ARRAY_NE 390
+#define F_ARRAY_LT 391
+#define F_ARRAY_GT 392
+#define F_ARRAY_LE 393
+#define F_STRING_TO_ARRAY_TEXT_TEXT 394
+#define F_ARRAY_TO_STRING_ANYARRAY_TEXT 395
+#define F_ARRAY_GE 396
+#define F_SCALARGEJOINSEL 398
+#define F_HASHMACADDR 399
+#define F_HASHTEXT 400
+#define F_TEXT_BPCHAR 401
+#define F_BTOIDVECTORCMP 404
+#define F_TEXT_NAME 406
+#define F_NAME_TEXT 407
+#define F_BPCHAR_NAME 408
+#define F_NAME_BPCHAR 409
+#define F_DIST_PATHP 421
+#define F_HASHINET 422
+#define F_HASHINT4EXTENDED 425
+#define F_HASH_NUMERIC 432
+#define F_MACADDR_IN 436
+#define F_MACADDR_OUT 437
+#define F_NUM_NULLS 438
+#define F_NUM_NONNULLS 440
+#define F_HASHINT2EXTENDED 441
+#define F_HASHINT8EXTENDED 442
+#define F_HASHFLOAT4EXTENDED 443
+#define F_HASHFLOAT8EXTENDED 444
+#define F_HASHOIDEXTENDED 445
+#define F_HASHCHAREXTENDED 446
+#define F_HASHNAMEEXTENDED 447
+#define F_HASHTEXTEXTENDED 448
+#define F_HASHINT2 449
+#define F_HASHINT4 450
+#define F_HASHFLOAT4 451
+#define F_HASHFLOAT8 452
+#define F_HASHOID 453
+#define F_HASHCHAR 454
+#define F_HASHNAME 455
+#define F_HASHVARLENA 456
+#define F_HASHOIDVECTOR 457
+#define F_TEXT_LARGER 458
+#define F_TEXT_SMALLER 459
+#define F_INT8IN 460
+#define F_INT8OUT 461
+#define F_INT8UM 462
+#define F_INT8PL 463
+#define F_INT8MI 464
+#define F_INT8MUL 465
+#define F_INT8DIV 466
+#define F_INT8EQ 467
+#define F_INT8NE 468
+#define F_INT8LT 469
+#define F_INT8GT 470
+#define F_INT8LE 471
+#define F_INT8GE 472
+#define F_INT84EQ 474
+#define F_INT84NE 475
+#define F_INT84LT 476
+#define F_INT84GT 477
+#define F_INT84LE 478
+#define F_INT84GE 479
+#define F_INT4_INT8 480
+#define F_INT8_INT4 481
+#define F_FLOAT8_INT8 482
+#define F_INT8_FLOAT8 483
+#define F_ARRAY_LARGER 515
+#define F_ARRAY_SMALLER 516
+#define F_ABBREV_INET 598
+#define F_ABBREV_CIDR 599
+#define F_SET_MASKLEN_INET_INT4 605
+#define F_OIDVECTORNE 619
+#define F_HASH_ARRAY 626
+#define F_SET_MASKLEN_CIDR_INT4 635
+#define F_PG_INDEXAM_HAS_PROPERTY 636
+#define F_PG_INDEX_HAS_PROPERTY 637
+#define F_PG_INDEX_COLUMN_HAS_PROPERTY 638
+#define F_FLOAT4_INT8 652
+#define F_INT8_FLOAT4 653
+#define F_NAMELT 655
+#define F_NAMELE 656
+#define F_NAMEGT 657
+#define F_NAMEGE 658
+#define F_NAMENE 659
+#define F_BPCHAR_BPCHAR_INT4_BOOL 668
+#define F_VARCHAR_VARCHAR_INT4_BOOL 669
+#define F_PG_INDEXAM_PROGRESS_PHASENAME 676
+#define F_OIDVECTORLT 677
+#define F_OIDVECTORLE 678
+#define F_OIDVECTOREQ 679
+#define F_OIDVECTORGE 680
+#define F_OIDVECTORGT 681
+#define F_NETWORK 683
+#define F_NETMASK 696
+#define F_MASKLEN 697
+#define F_BROADCAST 698
+#define F_HOST 699
+#define F_DIST_LP 702
+#define F_DIST_LS 704
+#define F_GETPGUSERNAME 710
+#define F_FAMILY 711
+#define F_INT2_INT8 714
+#define F_LO_CREATE 715
+#define F_OIDLT 716
+#define F_OIDLE 717
+#define F_OCTET_LENGTH_BYTEA 720
+#define F_GET_BYTE 721
+#define F_SET_BYTE 722
+#define F_GET_BIT_BYTEA_INT8 723
+#define F_SET_BIT_BYTEA_INT8_INT4 724
+#define F_DIST_PL 725
+#define F_DIST_SL 727
+#define F_DIST_CPOLY 728
+#define F_POLY_DISTANCE 729
+#define F_TEXT_INET 730
+#define F_TEXT_LT 740
+#define F_TEXT_LE 741
+#define F_TEXT_GT 742
+#define F_TEXT_GE 743
+#define F_ARRAY_EQ 744
+#define F_CURRENT_USER 745
+#define F_SESSION_USER 746
+#define F_ARRAY_DIMS 747
+#define F_ARRAY_NDIMS 748
+#define F_OVERLAY_BYTEA_BYTEA_INT4_INT4 749
+#define F_ARRAY_IN 750
+#define F_ARRAY_OUT 751
+#define F_OVERLAY_BYTEA_BYTEA_INT4 752
+#define F_TRUNC_MACADDR 753
+#define F_INT8_INT2 754
+#define F_LO_IMPORT_TEXT 764
+#define F_LO_EXPORT 765
+#define F_INT4INC 766
+#define F_LO_IMPORT_TEXT_OID 767
+#define F_INT4LARGER 768
+#define F_INT4SMALLER 769
+#define F_INT2LARGER 770
+#define F_INT2SMALLER 771
+#define F_HASHVARLENAEXTENDED 772
+#define F_HASHOIDVECTOREXTENDED 776
+#define F_HASH_ACLITEM_EXTENDED 777
+#define F_HASHMACADDREXTENDED 778
+#define F_HASHINETEXTENDED 779
+#define F_HASH_NUMERIC_EXTENDED 780
+#define F_HASHMACADDR8EXTENDED 781
+#define F_HASH_ARRAY_EXTENDED 782
+#define F_DIST_POLYC 785
+#define F_PG_CLIENT_ENCODING 810
+#define F_CURRENT_QUERY 817
+#define F_MACADDR_EQ 830
+#define F_MACADDR_LT 831
+#define F_MACADDR_LE 832
+#define F_MACADDR_GT 833
+#define F_MACADDR_GE 834
+#define F_MACADDR_NE 835
+#define F_MACADDR_CMP 836
+#define F_INT82PL 837
+#define F_INT82MI 838
+#define F_INT82MUL 839
+#define F_INT82DIV 840
+#define F_INT28PL 841
+#define F_BTINT8CMP 842
+#define F_CASH_MUL_FLT4 846
+#define F_CASH_DIV_FLT4 847
+#define F_FLT4_MUL_CASH 848
+#define F_POSITION_TEXT_TEXT 849
+#define F_TEXTLIKE 850
+#define F_TEXTNLIKE 851
+#define F_INT48EQ 852
+#define F_INT48NE 853
+#define F_INT48LT 854
+#define F_INT48GT 855
+#define F_INT48LE 856
+#define F_INT48GE 857
+#define F_NAMELIKE 858
+#define F_NAMENLIKE 859
+#define F_BPCHAR_CHAR 860
+#define F_CURRENT_DATABASE 861
+#define F_INT4_MUL_CASH 862
+#define F_INT2_MUL_CASH 863
+#define F_CASH_MUL_INT4 864
+#define F_CASH_DIV_INT4 865
+#define F_CASH_MUL_INT2 866
+#define F_CASH_DIV_INT2 867
+#define F_STRPOS 868
+#define F_LOWER_TEXT 870
+#define F_UPPER_TEXT 871
+#define F_INITCAP 872
+#define F_LPAD_TEXT_INT4_TEXT 873
+#define F_RPAD_TEXT_INT4_TEXT 874
+#define F_LTRIM_TEXT_TEXT 875
+#define F_RTRIM_TEXT_TEXT 876
+#define F_SUBSTR_TEXT_INT4_INT4 877
+#define F_TRANSLATE 878
+#define F_LPAD_TEXT_INT4 879
+#define F_RPAD_TEXT_INT4 880
+#define F_LTRIM_TEXT 881
+#define F_RTRIM_TEXT 882
+#define F_SUBSTR_TEXT_INT4 883
+#define F_BTRIM_TEXT_TEXT 884
+#define F_BTRIM_TEXT 885
+#define F_CASH_IN 886
+#define F_CASH_OUT 887
+#define F_CASH_EQ 888
+#define F_CASH_NE 889
+#define F_CASH_LT 890
+#define F_CASH_LE 891
+#define F_CASH_GT 892
+#define F_CASH_GE 893
+#define F_CASH_PL 894
+#define F_CASH_MI 895
+#define F_CASH_MUL_FLT8 896
+#define F_CASH_DIV_FLT8 897
+#define F_CASHLARGER 898
+#define F_CASHSMALLER 899
+#define F_INET_IN 910
+#define F_INET_OUT 911
+#define F_FLT8_MUL_CASH 919
+#define F_NETWORK_EQ 920
+#define F_NETWORK_LT 921
+#define F_NETWORK_LE 922
+#define F_NETWORK_GT 923
+#define F_NETWORK_GE 924
+#define F_NETWORK_NE 925
+#define F_NETWORK_CMP 926
+#define F_NETWORK_SUB 927
+#define F_NETWORK_SUBEQ 928
+#define F_NETWORK_SUP 929
+#define F_NETWORK_SUPEQ 930
+#define F_CASH_WORDS 935
+#define F_SUBSTRING_TEXT_INT4_INT4 936
+#define F_SUBSTRING_TEXT_INT4 937
+#define F_GENERATE_SERIES_TIMESTAMP_TIMESTAMP_INTERVAL 938
+#define F_GENERATE_SERIES_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL 939
+#define F_MOD_INT2_INT2 940
+#define F_MOD_INT4_INT4 941
+#define F_INT28MI 942
+#define F_INT28MUL 943
+#define F_CHAR_TEXT 944
+#define F_INT8MOD 945
+#define F_TEXT_CHAR 946
+#define F_MOD_INT8_INT8 947
+#define F_INT28DIV 948
+#define F_HASHINT8 949
+#define F_LO_OPEN 952
+#define F_LO_CLOSE 953
+#define F_LOREAD 954
+#define F_LOWRITE 955
+#define F_LO_LSEEK 956
+#define F_LO_CREAT 957
+#define F_LO_TELL 958
+#define F_ON_PL 959
+#define F_ON_SL 960
+#define F_CLOSE_PL 961
+#define F_LO_UNLINK 964
+#define F_HASHBPCHAREXTENDED 972
+#define F_PATH_INTER 973
+#define F_AREA_BOX 975
+#define F_WIDTH 976
+#define F_HEIGHT 977
+#define F_BOX_DISTANCE 978
+#define F_AREA_PATH 979
+#define F_BOX_INTERSECT 980
+#define F_DIAGONAL 981
+#define F_PATH_N_LT 982
+#define F_PATH_N_GT 983
+#define F_PATH_N_EQ 984
+#define F_PATH_N_LE 985
+#define F_PATH_N_GE 986
+#define F_PATH_LENGTH 987
+#define F_POINT_NE 988
+#define F_POINT_VERT 989
+#define F_POINT_HORIZ 990
+#define F_POINT_DISTANCE 991
+#define F_SLOPE 992
+#define F_LSEG_POINT_POINT 993
+#define F_LSEG_INTERSECT 994
+#define F_LSEG_PARALLEL 995
+#define F_LSEG_PERP 996
+#define F_LSEG_VERTICAL 997
+#define F_LSEG_HORIZONTAL 998
+#define F_LSEG_EQ 999
+#define F_LO_TRUNCATE 1004
+#define F_TEXTLIKE_SUPPORT 1023
+#define F_TEXTICREGEXEQ_SUPPORT 1024
+#define F_TEXTICLIKE_SUPPORT 1025
+#define F_TIMEZONE_INTERVAL_TIMESTAMPTZ 1026
+#define F_GIST_POINT_COMPRESS 1030
+#define F_ACLITEMIN 1031
+#define F_ACLITEMOUT 1032
+#define F_ACLINSERT 1035
+#define F_ACLREMOVE 1036
+#define F_ACLCONTAINS 1037
+#define F_GETDATABASEENCODING 1039
+#define F_BPCHARIN 1044
+#define F_BPCHAROUT 1045
+#define F_VARCHARIN 1046
+#define F_VARCHAROUT 1047
+#define F_BPCHAREQ 1048
+#define F_BPCHARLT 1049
+#define F_BPCHARLE 1050
+#define F_BPCHARGT 1051
+#define F_BPCHARGE 1052
+#define F_BPCHARNE 1053
+#define F_ACLITEMEQ 1062
+#define F_BPCHAR_LARGER 1063
+#define F_BPCHAR_SMALLER 1064
+#define F_PG_PREPARED_XACT 1065
+#define F_GENERATE_SERIES_INT4_INT4_INT4 1066
+#define F_GENERATE_SERIES_INT4_INT4 1067
+#define F_GENERATE_SERIES_INT8_INT8_INT8 1068
+#define F_GENERATE_SERIES_INT8_INT8 1069
+#define F_BPCHARCMP 1078
+#define F_REGCLASS 1079
+#define F_HASHBPCHAR 1080
+#define F_FORMAT_TYPE 1081
+#define F_DATE_IN 1084
+#define F_DATE_OUT 1085
+#define F_DATE_EQ 1086
+#define F_DATE_LT 1087
+#define F_DATE_LE 1088
+#define F_DATE_GT 1089
+#define F_DATE_GE 1090
+#define F_DATE_NE 1091
+#define F_DATE_CMP 1092
+#define F_TIME_LT 1102
+#define F_TIME_LE 1103
+#define F_TIME_GT 1104
+#define F_TIME_GE 1105
+#define F_TIME_NE 1106
+#define F_TIME_CMP 1107
+#define F_PG_STAT_GET_WAL 1136
+#define F_PG_GET_WAL_REPLAY_PAUSE_STATE 1137
+#define F_DATE_LARGER 1138
+#define F_DATE_SMALLER 1139
+#define F_DATE_MI 1140
+#define F_DATE_PLI 1141
+#define F_DATE_MII 1142
+#define F_TIME_IN 1143
+#define F_TIME_OUT 1144
+#define F_TIME_EQ 1145
+#define F_CIRCLE_ADD_PT 1146
+#define F_CIRCLE_SUB_PT 1147
+#define F_CIRCLE_MUL_PT 1148
+#define F_CIRCLE_DIV_PT 1149
+#define F_TIMESTAMPTZ_IN 1150
+#define F_TIMESTAMPTZ_OUT 1151
+#define F_TIMESTAMPTZ_EQ 1152
+#define F_TIMESTAMPTZ_NE 1153
+#define F_TIMESTAMPTZ_LT 1154
+#define F_TIMESTAMPTZ_LE 1155
+#define F_TIMESTAMPTZ_GE 1156
+#define F_TIMESTAMPTZ_GT 1157
+#define F_TO_TIMESTAMP_FLOAT8 1158
+#define F_TIMEZONE_TEXT_TIMESTAMPTZ 1159
+#define F_INTERVAL_IN 1160
+#define F_INTERVAL_OUT 1161
+#define F_INTERVAL_EQ 1162
+#define F_INTERVAL_NE 1163
+#define F_INTERVAL_LT 1164
+#define F_INTERVAL_LE 1165
+#define F_INTERVAL_GE 1166
+#define F_INTERVAL_GT 1167
+#define F_INTERVAL_UM 1168
+#define F_INTERVAL_PL 1169
+#define F_INTERVAL_MI 1170
+#define F_DATE_PART_TEXT_TIMESTAMPTZ 1171
+#define F_DATE_PART_TEXT_INTERVAL 1172
+#define F_NETWORK_SUBSET_SUPPORT 1173
+#define F_TIMESTAMPTZ_DATE 1174
+#define F_JUSTIFY_HOURS 1175
+#define F_TIMESTAMPTZ_DATE_TIME 1176
+#define F_JSONB_PATH_EXISTS_TZ 1177
+#define F_DATE_TIMESTAMPTZ 1178
+#define F_JSONB_PATH_QUERY_TZ 1179
+#define F_JSONB_PATH_QUERY_ARRAY_TZ 1180
+#define F_AGE_XID 1181
+#define F_TIMESTAMPTZ_MI 1188
+#define F_TIMESTAMPTZ_PL_INTERVAL 1189
+#define F_TIMESTAMPTZ_MI_INTERVAL 1190
+#define F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4_BOOL 1191
+#define F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4 1192
+#define F_ARRAY_FILL_ANYELEMENT__INT4 1193
+#define F_LOG10_FLOAT8 1194
+#define F_TIMESTAMPTZ_SMALLER 1195
+#define F_TIMESTAMPTZ_LARGER 1196
+#define F_INTERVAL_SMALLER 1197
+#define F_INTERVAL_LARGER 1198
+#define F_AGE_TIMESTAMPTZ_TIMESTAMPTZ 1199
+#define F_INTERVAL_INTERVAL_INT4 1200
+#define F_OBJ_DESCRIPTION_OID_NAME 1215
+#define F_COL_DESCRIPTION 1216
+#define F_DATE_TRUNC_TEXT_TIMESTAMPTZ 1217
+#define F_DATE_TRUNC_TEXT_INTERVAL 1218
+#define F_INT8INC 1219
+#define F_INT8ABS 1230
+#define F_INT8LARGER 1236
+#define F_INT8SMALLER 1237
+#define F_TEXTICREGEXEQ 1238
+#define F_TEXTICREGEXNE 1239
+#define F_NAMEICREGEXEQ 1240
+#define F_NAMEICREGEXNE 1241
+#define F_BOOLIN 1242
+#define F_BOOLOUT 1243
+#define F_BYTEAIN 1244
+#define F_CHARIN 1245
+#define F_CHARLT 1246
+#define F_UNIQUE_KEY_RECHECK 1250
+#define F_INT4ABS 1251
+#define F_NAMEREGEXNE 1252
+#define F_INT2ABS 1253
+#define F_TEXTREGEXEQ 1254
+#define F_TEXTREGEXNE 1256
+#define F_TEXTLEN 1257
+#define F_TEXTCAT 1258
+#define F_PG_CHAR_TO_ENCODING 1264
+#define F_TIDNE 1265
+#define F_CIDR_IN 1267
+#define F_PARSE_IDENT 1268
+#define F_PG_COLUMN_SIZE 1269
+#define F_OVERLAPS_TIMETZ_TIMETZ_TIMETZ_TIMETZ 1271
+#define F_DATETIME_PL 1272
+#define F_DATE_PART_TEXT_TIMETZ 1273
+#define F_INT84PL 1274
+#define F_INT84MI 1275
+#define F_INT84MUL 1276
+#define F_INT84DIV 1277
+#define F_INT48PL 1278
+#define F_INT48MI 1279
+#define F_INT48MUL 1280
+#define F_INT48DIV 1281
+#define F_QUOTE_IDENT 1282
+#define F_QUOTE_LITERAL_TEXT 1283
+#define F_DATE_TRUNC_TEXT_TIMESTAMPTZ_TEXT 1284
+#define F_QUOTE_LITERAL_ANYELEMENT 1285
+#define F_ARRAY_FILL_ANYELEMENT__INT4__INT4 1286
+#define F_OID 1287
+#define F_INT8_OID 1288
+#define F_QUOTE_NULLABLE_TEXT 1289
+#define F_QUOTE_NULLABLE_ANYELEMENT 1290
+#define F_SUPPRESS_REDUNDANT_UPDATES_TRIGGER 1291
+#define F_TIDEQ 1292
+#define F_UNNEST_ANYMULTIRANGE 1293
+#define F_CURRTID2 1294
+#define F_JUSTIFY_DAYS 1295
+#define F_TIMEDATE_PL 1296
+#define F_DATETIMETZ_PL 1297
+#define F_TIMETZDATE_PL 1298
+#define F_NOW 1299
+#define F_POSITIONSEL 1300
+#define F_POSITIONJOINSEL 1301
+#define F_CONTSEL 1302
+#define F_CONTJOINSEL 1303
+#define F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ 1304
+#define F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_INTERVAL 1305
+#define F_OVERLAPS_TIMESTAMPTZ_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL 1306
+#define F_OVERLAPS_TIMESTAMPTZ_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ 1307
+#define F_OVERLAPS_TIME_TIME_TIME_TIME 1308
+#define F_OVERLAPS_TIME_INTERVAL_TIME_INTERVAL 1309
+#define F_OVERLAPS_TIME_TIME_TIME_INTERVAL 1310
+#define F_OVERLAPS_TIME_INTERVAL_TIME_TIME 1311
+#define F_TIMESTAMP_IN 1312
+#define F_TIMESTAMP_OUT 1313
+#define F_TIMESTAMPTZ_CMP 1314
+#define F_INTERVAL_CMP 1315
+#define F_TIME_TIMESTAMP 1316
+#define F_LENGTH_TEXT 1317
+#define F_LENGTH_BPCHAR 1318
+#define F_XIDEQINT4 1319
+#define F_INTERVAL_DIV 1326
+#define F_DLOG10 1339
+#define F_LOG_FLOAT8 1340
+#define F_LN_FLOAT8 1341
+#define F_ROUND_FLOAT8 1342
+#define F_TRUNC_FLOAT8 1343
+#define F_SQRT_FLOAT8 1344
+#define F_CBRT 1345
+#define F_POW_FLOAT8_FLOAT8 1346
+#define F_EXP_FLOAT8 1347
+#define F_OBJ_DESCRIPTION_OID 1348
+#define F_OIDVECTORTYPES 1349
+#define F_TIMETZ_IN 1350
+#define F_TIMETZ_OUT 1351
+#define F_TIMETZ_EQ 1352
+#define F_TIMETZ_NE 1353
+#define F_TIMETZ_LT 1354
+#define F_TIMETZ_LE 1355
+#define F_TIMETZ_GE 1356
+#define F_TIMETZ_GT 1357
+#define F_TIMETZ_CMP 1358
+#define F_TIMESTAMPTZ_DATE_TIMETZ 1359
+#define F_HOSTMASK 1362
+#define F_TEXTREGEXEQ_SUPPORT 1364
+#define F_MAKEACLITEM 1365
+#define F_CHARACTER_LENGTH_BPCHAR 1367
+#define F_POWER_FLOAT8_FLOAT8 1368
+#define F_CHARACTER_LENGTH_TEXT 1369
+#define F_INTERVAL_TIME 1370
+#define F_PG_LOCK_STATUS 1371
+#define F_CHAR_LENGTH_BPCHAR 1372
+#define F_ISFINITE_DATE 1373
+#define F_OCTET_LENGTH_TEXT 1374
+#define F_OCTET_LENGTH_BPCHAR 1375
+#define F_FACTORIAL 1376
+#define F_TIME_LARGER 1377
+#define F_TIME_SMALLER 1378
+#define F_TIMETZ_LARGER 1379
+#define F_TIMETZ_SMALLER 1380
+#define F_CHAR_LENGTH_TEXT 1381
+#define F_DATE_PART_TEXT_DATE 1384
+#define F_DATE_PART_TEXT_TIME 1385
+#define F_AGE_TIMESTAMPTZ 1386
+#define F_PG_GET_CONSTRAINTDEF_OID 1387
+#define F_TIMETZ_TIMESTAMPTZ 1388
+#define F_ISFINITE_TIMESTAMPTZ 1389
+#define F_ISFINITE_INTERVAL 1390
+#define F_PG_STAT_GET_BACKEND_START 1391
+#define F_PG_STAT_GET_BACKEND_CLIENT_ADDR 1392
+#define F_PG_STAT_GET_BACKEND_CLIENT_PORT 1393
+#define F_ABS_FLOAT4 1394
+#define F_ABS_FLOAT8 1395
+#define F_ABS_INT8 1396
+#define F_ABS_INT4 1397
+#define F_ABS_INT2 1398
+#define F_NAME_VARCHAR 1400
+#define F_VARCHAR_NAME 1401
+#define F_CURRENT_SCHEMA 1402
+#define F_CURRENT_SCHEMAS 1403
+#define F_OVERLAY_TEXT_TEXT_INT4_INT4 1404
+#define F_OVERLAY_TEXT_TEXT_INT4 1405
+#define F_ISVERTICAL_POINT_POINT 1406
+#define F_ISHORIZONTAL_POINT_POINT 1407
+#define F_ISPARALLEL_LSEG_LSEG 1408
+#define F_ISPERP_LSEG_LSEG 1409
+#define F_ISVERTICAL_LSEG 1410
+#define F_ISHORIZONTAL_LSEG 1411
+#define F_ISPARALLEL_LINE_LINE 1412
+#define F_ISPERP_LINE_LINE 1413
+#define F_ISVERTICAL_LINE 1414
+#define F_ISHORIZONTAL_LINE 1415
+#define F_POINT_CIRCLE 1416
+#define F_TIME_INTERVAL 1419
+#define F_BOX_POINT_POINT 1421
+#define F_BOX_ADD 1422
+#define F_BOX_SUB 1423
+#define F_BOX_MUL 1424
+#define F_BOX_DIV 1425
+#define F_PATH_CONTAIN_PT 1426
+#define F_CIDR_OUT 1427
+#define F_POLY_CONTAIN_PT 1428
+#define F_PT_CONTAINED_POLY 1429
+#define F_ISCLOSED 1430
+#define F_ISOPEN 1431
+#define F_PATH_NPOINTS 1432
+#define F_PCLOSE 1433
+#define F_POPEN 1434
+#define F_PATH_ADD 1435
+#define F_PATH_ADD_PT 1436
+#define F_PATH_SUB_PT 1437
+#define F_PATH_MUL_PT 1438
+#define F_PATH_DIV_PT 1439
+#define F_POINT_FLOAT8_FLOAT8 1440
+#define F_POINT_ADD 1441
+#define F_POINT_SUB 1442
+#define F_POINT_MUL 1443
+#define F_POINT_DIV 1444
+#define F_POLY_NPOINTS 1445
+#define F_BOX_POLYGON 1446
+#define F_PATH 1447
+#define F_POLYGON_BOX 1448
+#define F_POLYGON_PATH 1449
+#define F_CIRCLE_IN 1450
+#define F_CIRCLE_OUT 1451
+#define F_CIRCLE_SAME 1452
+#define F_CIRCLE_CONTAIN 1453
+#define F_CIRCLE_LEFT 1454
+#define F_CIRCLE_OVERLEFT 1455
+#define F_CIRCLE_OVERRIGHT 1456
+#define F_CIRCLE_RIGHT 1457
+#define F_CIRCLE_CONTAINED 1458
+#define F_CIRCLE_OVERLAP 1459
+#define F_CIRCLE_BELOW 1460
+#define F_CIRCLE_ABOVE 1461
+#define F_CIRCLE_EQ 1462
+#define F_CIRCLE_NE 1463
+#define F_CIRCLE_LT 1464
+#define F_CIRCLE_GT 1465
+#define F_CIRCLE_LE 1466
+#define F_CIRCLE_GE 1467
+#define F_AREA_CIRCLE 1468
+#define F_DIAMETER 1469
+#define F_RADIUS 1470
+#define F_CIRCLE_DISTANCE 1471
+#define F_CIRCLE_CENTER 1472
+#define F_CIRCLE_POINT_FLOAT8 1473
+#define F_CIRCLE_POLYGON 1474
+#define F_POLYGON_INT4_CIRCLE 1475
+#define F_DIST_PC 1476
+#define F_CIRCLE_CONTAIN_PT 1477
+#define F_PT_CONTAINED_CIRCLE 1478
+#define F_CIRCLE_BOX 1479
+#define F_BOX_CIRCLE 1480
+#define F_LOG10_NUMERIC 1481
+#define F_LSEG_NE 1482
+#define F_LSEG_LT 1483
+#define F_LSEG_LE 1484
+#define F_LSEG_GT 1485
+#define F_LSEG_GE 1486
+#define F_LSEG_LENGTH 1487
+#define F_CLOSE_LS 1488
+#define F_CLOSE_LSEG 1489
+#define F_LINE_IN 1490
+#define F_LINE_OUT 1491
+#define F_LINE_EQ 1492
+#define F_LINE 1493
+#define F_LINE_INTERPT 1494
+#define F_LINE_INTERSECT 1495
+#define F_LINE_PARALLEL 1496
+#define F_LINE_PERP 1497
+#define F_LINE_VERTICAL 1498
+#define F_LINE_HORIZONTAL 1499
+#define F_LENGTH_LSEG 1530
+#define F_LENGTH_PATH 1531
+#define F_POINT_LSEG 1532
+#define F_POINT_BOX 1534
+#define F_POINT_POLYGON 1540
+#define F_LSEG_BOX 1541
+#define F_CENTER_BOX 1542
+#define F_CENTER_CIRCLE 1543
+#define F_POLYGON_CIRCLE 1544
+#define F_NPOINTS_PATH 1545
+#define F_NPOINTS_POLYGON 1556
+#define F_BIT_IN 1564
+#define F_BIT_OUT 1565
+#define F_LIKE_TEXT_TEXT 1569
+#define F_NOTLIKE_TEXT_TEXT 1570
+#define F_LIKE_NAME_TEXT 1571
+#define F_NOTLIKE_NAME_TEXT 1572
+#define F_PG_GET_RULEDEF_OID 1573
+#define F_NEXTVAL 1574
+#define F_CURRVAL 1575
+#define F_SETVAL_REGCLASS_INT8 1576
+#define F_VARBIT_IN 1579
+#define F_VARBIT_OUT 1580
+#define F_BITEQ 1581
+#define F_BITNE 1582
+#define F_BITGE 1592
+#define F_BITGT 1593
+#define F_BITLE 1594
+#define F_BITLT 1595
+#define F_BITCMP 1596
+#define F_PG_ENCODING_TO_CHAR 1597
+#define F_RANDOM 1598
+#define F_SETSEED 1599
+#define F_ASIN 1600
+#define F_ACOS 1601
+#define F_ATAN 1602
+#define F_ATAN2 1603
+#define F_SIN 1604
+#define F_COS 1605
+#define F_TAN 1606
+#define F_COT 1607
+#define F_DEGREES 1608
+#define F_RADIANS 1609
+#define F_PI 1610
+#define F_INTERVAL_MUL 1618
+#define F_PG_TYPEOF 1619
+#define F_ASCII 1620
+#define F_CHR 1621
+#define F_REPEAT 1622
+#define F_SIMILAR_ESCAPE 1623
+#define F_MUL_D_INTERVAL 1624
+#define F_BPCHARLIKE 1631
+#define F_BPCHARNLIKE 1632
+#define F_TEXTICLIKE 1633
+#define F_TEXTICNLIKE 1634
+#define F_NAMEICLIKE 1635
+#define F_NAMEICNLIKE 1636
+#define F_LIKE_ESCAPE_TEXT_TEXT 1637
+#define F_OIDGT 1638
+#define F_OIDGE 1639
+#define F_PG_GET_VIEWDEF_TEXT 1640
+#define F_PG_GET_VIEWDEF_OID 1641
+#define F_PG_GET_USERBYID 1642
+#define F_PG_GET_INDEXDEF_OID 1643
+#define F_RI_FKEY_CHECK_INS 1644
+#define F_RI_FKEY_CHECK_UPD 1645
+#define F_RI_FKEY_CASCADE_DEL 1646
+#define F_RI_FKEY_CASCADE_UPD 1647
+#define F_RI_FKEY_RESTRICT_DEL 1648
+#define F_RI_FKEY_RESTRICT_UPD 1649
+#define F_RI_FKEY_SETNULL_DEL 1650
+#define F_RI_FKEY_SETNULL_UPD 1651
+#define F_RI_FKEY_SETDEFAULT_DEL 1652
+#define F_RI_FKEY_SETDEFAULT_UPD 1653
+#define F_RI_FKEY_NOACTION_DEL 1654
+#define F_RI_FKEY_NOACTION_UPD 1655
+#define F_BPCHARICREGEXEQ 1656
+#define F_BPCHARICREGEXNE 1657
+#define F_BPCHARREGEXEQ 1658
+#define F_BPCHARREGEXNE 1659
+#define F_BPCHARICLIKE 1660
+#define F_BPCHARICNLIKE 1661
+#define F_PG_GET_TRIGGERDEF_OID 1662
+#define F_PG_GET_SERIAL_SEQUENCE 1665
+#define F_VARBITEQ 1666
+#define F_VARBITNE 1667
+#define F_VARBITGE 1668
+#define F_VARBITGT 1669
+#define F_VARBITLE 1670
+#define F_VARBITLT 1671
+#define F_VARBITCMP 1672
+#define F_BITAND 1673
+#define F_BITOR 1674
+#define F_BITXOR 1675
+#define F_BITNOT 1676
+#define F_BITSHIFTLEFT 1677
+#define F_BITSHIFTRIGHT 1678
+#define F_BITCAT 1679
+#define F_SUBSTRING_BIT_INT4_INT4 1680
+#define F_LENGTH_BIT 1681
+#define F_OCTET_LENGTH_BIT 1682
+#define F_BIT_INT4_INT4 1683
+#define F_INT4_BIT 1684
+#define F_BIT_BIT_INT4_BOOL 1685
+#define F_PG_GET_KEYWORDS 1686
+#define F_VARBIT 1687
+#define F_TIME_HASH 1688
+#define F_ACLEXPLODE 1689
+#define F_TIME_MI_TIME 1690
+#define F_BOOLLE 1691
+#define F_BOOLGE 1692
+#define F_BTBOOLCMP 1693
+#define F_TIMETZ_HASH 1696
+#define F_INTERVAL_HASH 1697
+#define F_POSITION_BIT_BIT 1698
+#define F_SUBSTRING_BIT_INT4 1699
+#define F_NUMERIC_IN 1701
+#define F_NUMERIC_OUT 1702
+#define F_NUMERIC_NUMERIC_INT4 1703
+#define F_NUMERIC_ABS 1704
+#define F_ABS_NUMERIC 1705
+#define F_SIGN_NUMERIC 1706
+#define F_ROUND_NUMERIC_INT4 1707
+#define F_ROUND_NUMERIC 1708
+#define F_TRUNC_NUMERIC_INT4 1709
+#define F_TRUNC_NUMERIC 1710
+#define F_CEIL_NUMERIC 1711
+#define F_FLOOR_NUMERIC 1712
+#define F_LENGTH_BYTEA_NAME 1713
+#define F_CONVERT_FROM 1714
+#define F_CIDR 1715
+#define F_PG_GET_EXPR_PG_NODE_TREE_OID 1716
+#define F_CONVERT_TO 1717
+#define F_NUMERIC_EQ 1718
+#define F_NUMERIC_NE 1719
+#define F_NUMERIC_GT 1720
+#define F_NUMERIC_GE 1721
+#define F_NUMERIC_LT 1722
+#define F_NUMERIC_LE 1723
+#define F_NUMERIC_ADD 1724
+#define F_NUMERIC_SUB 1725
+#define F_NUMERIC_MUL 1726
+#define F_NUMERIC_DIV 1727
+#define F_MOD_NUMERIC_NUMERIC 1728
+#define F_NUMERIC_MOD 1729
+#define F_SQRT_NUMERIC 1730
+#define F_NUMERIC_SQRT 1731
+#define F_EXP_NUMERIC 1732
+#define F_NUMERIC_EXP 1733
+#define F_LN_NUMERIC 1734
+#define F_NUMERIC_LN 1735
+#define F_LOG_NUMERIC_NUMERIC 1736
+#define F_NUMERIC_LOG 1737
+#define F_POW_NUMERIC_NUMERIC 1738
+#define F_NUMERIC_POWER 1739
+#define F_NUMERIC_INT4 1740
+#define F_LOG_NUMERIC 1741
+#define F_NUMERIC_FLOAT4 1742
+#define F_NUMERIC_FLOAT8 1743
+#define F_INT4_NUMERIC 1744
+#define F_FLOAT4_NUMERIC 1745
+#define F_FLOAT8_NUMERIC 1746
+#define F_TIME_PL_INTERVAL 1747
+#define F_TIME_MI_INTERVAL 1748
+#define F_TIMETZ_PL_INTERVAL 1749
+#define F_TIMETZ_MI_INTERVAL 1750
+#define F_NUMERIC_INC 1764
+#define F_SETVAL_REGCLASS_INT8_BOOL 1765
+#define F_NUMERIC_SMALLER 1766
+#define F_NUMERIC_LARGER 1767
+#define F_TO_CHAR_INTERVAL_TEXT 1768
+#define F_NUMERIC_CMP 1769
+#define F_TO_CHAR_TIMESTAMPTZ_TEXT 1770
+#define F_NUMERIC_UMINUS 1771
+#define F_TO_CHAR_NUMERIC_TEXT 1772
+#define F_TO_CHAR_INT4_TEXT 1773
+#define F_TO_CHAR_INT8_TEXT 1774
+#define F_TO_CHAR_FLOAT4_TEXT 1775
+#define F_TO_CHAR_FLOAT8_TEXT 1776
+#define F_TO_NUMBER 1777
+#define F_TO_TIMESTAMP_TEXT_TEXT 1778
+#define F_INT8_NUMERIC 1779
+#define F_TO_DATE 1780
+#define F_NUMERIC_INT8 1781
+#define F_NUMERIC_INT2 1782
+#define F_INT2_NUMERIC 1783
+#define F_OIDIN 1798
+#define F_OIDOUT 1799
+#define F_BIT_LENGTH_BYTEA 1810
+#define F_BIT_LENGTH_TEXT 1811
+#define F_BIT_LENGTH_BIT 1812
+#define F_CONVERT 1813
+#define F_ICLIKESEL 1814
+#define F_ICNLIKESEL 1815
+#define F_ICLIKEJOINSEL 1816
+#define F_ICNLIKEJOINSEL 1817
+#define F_REGEXEQSEL 1818
+#define F_LIKESEL 1819
+#define F_ICREGEXEQSEL 1820
+#define F_REGEXNESEL 1821
+#define F_NLIKESEL 1822
+#define F_ICREGEXNESEL 1823
+#define F_REGEXEQJOINSEL 1824
+#define F_LIKEJOINSEL 1825
+#define F_ICREGEXEQJOINSEL 1826
+#define F_REGEXNEJOINSEL 1827
+#define F_NLIKEJOINSEL 1828
+#define F_ICREGEXNEJOINSEL 1829
+#define F_FLOAT8_AVG 1830
+#define F_FLOAT8_VAR_SAMP 1831
+#define F_FLOAT8_STDDEV_SAMP 1832
+#define F_NUMERIC_ACCUM 1833
+#define F_INT2_ACCUM 1834
+#define F_INT4_ACCUM 1835
+#define F_INT8_ACCUM 1836
+#define F_NUMERIC_AVG 1837
+#define F_NUMERIC_VAR_SAMP 1838
+#define F_NUMERIC_STDDEV_SAMP 1839
+#define F_INT2_SUM 1840
+#define F_INT4_SUM 1841
+#define F_INT8_SUM 1842
+#define F_INTERVAL_ACCUM 1843
+#define F_INTERVAL_AVG 1844
+#define F_TO_ASCII_TEXT 1845
+#define F_TO_ASCII_TEXT_INT4 1846
+#define F_TO_ASCII_TEXT_NAME 1847
+#define F_INTERVAL_PL_TIME 1848
+#define F_INT28EQ 1850
+#define F_INT28NE 1851
+#define F_INT28LT 1852
+#define F_INT28GT 1853
+#define F_INT28LE 1854
+#define F_INT28GE 1855
+#define F_INT82EQ 1856
+#define F_INT82NE 1857
+#define F_INT82LT 1858
+#define F_INT82GT 1859
+#define F_INT82LE 1860
+#define F_INT82GE 1861
+#define F_INT2AND 1892
+#define F_INT2OR 1893
+#define F_INT2XOR 1894
+#define F_INT2NOT 1895
+#define F_INT2SHL 1896
+#define F_INT2SHR 1897
+#define F_INT4AND 1898
+#define F_INT4OR 1899
+#define F_INT4XOR 1900
+#define F_INT4NOT 1901
+#define F_INT4SHL 1902
+#define F_INT4SHR 1903
+#define F_INT8AND 1904
+#define F_INT8OR 1905
+#define F_INT8XOR 1906
+#define F_INT8NOT 1907
+#define F_INT8SHL 1908
+#define F_INT8SHR 1909
+#define F_INT8UP 1910
+#define F_INT2UP 1911
+#define F_INT4UP 1912
+#define F_FLOAT4UP 1913
+#define F_FLOAT8UP 1914
+#define F_NUMERIC_UPLUS 1915
+#define F_HAS_TABLE_PRIVILEGE_NAME_TEXT_TEXT 1922
+#define F_HAS_TABLE_PRIVILEGE_NAME_OID_TEXT 1923
+#define F_HAS_TABLE_PRIVILEGE_OID_TEXT_TEXT 1924
+#define F_HAS_TABLE_PRIVILEGE_OID_OID_TEXT 1925
+#define F_HAS_TABLE_PRIVILEGE_TEXT_TEXT 1926
+#define F_HAS_TABLE_PRIVILEGE_OID_TEXT 1927
+#define F_PG_STAT_GET_NUMSCANS 1928
+#define F_PG_STAT_GET_TUPLES_RETURNED 1929
+#define F_PG_STAT_GET_TUPLES_FETCHED 1930
+#define F_PG_STAT_GET_TUPLES_INSERTED 1931
+#define F_PG_STAT_GET_TUPLES_UPDATED 1932
+#define F_PG_STAT_GET_TUPLES_DELETED 1933
+#define F_PG_STAT_GET_BLOCKS_FETCHED 1934
+#define F_PG_STAT_GET_BLOCKS_HIT 1935
+#define F_PG_STAT_GET_BACKEND_IDSET 1936
+#define F_PG_STAT_GET_BACKEND_PID 1937
+#define F_PG_STAT_GET_BACKEND_DBID 1938
+#define F_PG_STAT_GET_BACKEND_USERID 1939
+#define F_PG_STAT_GET_BACKEND_ACTIVITY 1940
+#define F_PG_STAT_GET_DB_NUMBACKENDS 1941
+#define F_PG_STAT_GET_DB_XACT_COMMIT 1942
+#define F_PG_STAT_GET_DB_XACT_ROLLBACK 1943
+#define F_PG_STAT_GET_DB_BLOCKS_FETCHED 1944
+#define F_PG_STAT_GET_DB_BLOCKS_HIT 1945
+#define F_ENCODE 1946
+#define F_DECODE 1947
+#define F_BYTEAEQ 1948
+#define F_BYTEALT 1949
+#define F_BYTEALE 1950
+#define F_BYTEAGT 1951
+#define F_BYTEAGE 1952
+#define F_BYTEANE 1953
+#define F_BYTEACMP 1954
+#define F_TIMESTAMP_TIMESTAMP_INT4 1961
+#define F_INT2_AVG_ACCUM 1962
+#define F_INT4_AVG_ACCUM 1963
+#define F_INT8_AVG 1964
+#define F_OIDLARGER 1965
+#define F_OIDSMALLER 1966
+#define F_TIMESTAMPTZ_TIMESTAMPTZ_INT4 1967
+#define F_TIME_TIME_INT4 1968
+#define F_TIMETZ_TIMETZ_INT4 1969
+#define F_PG_STAT_GET_TUPLES_HOT_UPDATED 1972
+#define F_DIV 1973
+#define F_NUMERIC_DIV_TRUNC 1980
+#define F_SIMILAR_TO_ESCAPE_TEXT_TEXT 1986
+#define F_SIMILAR_TO_ESCAPE_TEXT 1987
+#define F_SHOBJ_DESCRIPTION 1993
+#define F_TEXTANYCAT 2003
+#define F_ANYTEXTCAT 2004
+#define F_BYTEALIKE 2005
+#define F_BYTEANLIKE 2006
+#define F_LIKE_BYTEA_BYTEA 2007
+#define F_NOTLIKE_BYTEA_BYTEA 2008
+#define F_LIKE_ESCAPE_BYTEA_BYTEA 2009
+#define F_LENGTH_BYTEA 2010
+#define F_BYTEACAT 2011
+#define F_SUBSTRING_BYTEA_INT4_INT4 2012
+#define F_SUBSTRING_BYTEA_INT4 2013
+#define F_POSITION_BYTEA_BYTEA 2014
+#define F_BTRIM_BYTEA_BYTEA 2015
+#define F_TIME_TIMESTAMPTZ 2019
+#define F_DATE_TRUNC_TEXT_TIMESTAMP 2020
+#define F_DATE_PART_TEXT_TIMESTAMP 2021
+#define F_PG_STAT_GET_ACTIVITY 2022
+#define F_JSONB_PATH_QUERY_FIRST_TZ 2023
+#define F_TIMESTAMP_DATE 2024
+#define F_TIMESTAMP_DATE_TIME 2025
+#define F_PG_BACKEND_PID 2026
+#define F_TIMESTAMP_TIMESTAMPTZ 2027
+#define F_TIMESTAMPTZ_TIMESTAMP 2028
+#define F_DATE_TIMESTAMP 2029
+#define F_JSONB_PATH_MATCH_TZ 2030
+#define F_TIMESTAMP_MI 2031
+#define F_TIMESTAMP_PL_INTERVAL 2032
+#define F_TIMESTAMP_MI_INTERVAL 2033
+#define F_PG_CONF_LOAD_TIME 2034
+#define F_TIMESTAMP_SMALLER 2035
+#define F_TIMESTAMP_LARGER 2036
+#define F_TIMEZONE_TEXT_TIMETZ 2037
+#define F_TIMEZONE_INTERVAL_TIMETZ 2038
+#define F_TIMESTAMP_HASH 2039
+#define F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_TIMESTAMP 2041
+#define F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_INTERVAL 2042
+#define F_OVERLAPS_TIMESTAMP_TIMESTAMP_TIMESTAMP_INTERVAL 2043
+#define F_OVERLAPS_TIMESTAMP_INTERVAL_TIMESTAMP_TIMESTAMP 2044
+#define F_TIMESTAMP_CMP 2045
+#define F_TIME_TIMETZ 2046
+#define F_TIMETZ_TIME 2047
+#define F_ISFINITE_TIMESTAMP 2048
+#define F_TO_CHAR_TIMESTAMP_TEXT 2049
+#define F_MAX_ANYARRAY 2050
+#define F_MIN_ANYARRAY 2051
+#define F_TIMESTAMP_EQ 2052
+#define F_TIMESTAMP_NE 2053
+#define F_TIMESTAMP_LT 2054
+#define F_TIMESTAMP_LE 2055
+#define F_TIMESTAMP_GE 2056
+#define F_TIMESTAMP_GT 2057
+#define F_AGE_TIMESTAMP_TIMESTAMP 2058
+#define F_AGE_TIMESTAMP 2059
+#define F_TIMEZONE_TEXT_TIMESTAMP 2069
+#define F_TIMEZONE_INTERVAL_TIMESTAMP 2070
+#define F_DATE_PL_INTERVAL 2071
+#define F_DATE_MI_INTERVAL 2072
+#define F_SUBSTRING_TEXT_TEXT 2073
+#define F_SUBSTRING_TEXT_TEXT_TEXT 2074
+#define F_BIT_INT8_INT4 2075
+#define F_INT8_BIT 2076
+#define F_CURRENT_SETTING_TEXT 2077
+#define F_SET_CONFIG 2078
+#define F_PG_TABLE_IS_VISIBLE 2079
+#define F_PG_TYPE_IS_VISIBLE 2080
+#define F_PG_FUNCTION_IS_VISIBLE 2081
+#define F_PG_OPERATOR_IS_VISIBLE 2082
+#define F_PG_OPCLASS_IS_VISIBLE 2083
+#define F_PG_SHOW_ALL_SETTINGS 2084
+#define F_SUBSTR_BYTEA_INT4_INT4 2085
+#define F_SUBSTR_BYTEA_INT4 2086
+#define F_REPLACE 2087
+#define F_SPLIT_PART 2088
+#define F_TO_HEX_INT4 2089
+#define F_TO_HEX_INT8 2090
+#define F_ARRAY_LOWER 2091
+#define F_ARRAY_UPPER 2092
+#define F_PG_CONVERSION_IS_VISIBLE 2093
+#define F_PG_STAT_GET_BACKEND_ACTIVITY_START 2094
+#define F_PG_TERMINATE_BACKEND 2096
+#define F_PG_GET_FUNCTIONDEF 2098
+#define F_AVG_INT8 2100
+#define F_AVG_INT4 2101
+#define F_AVG_INT2 2102
+#define F_AVG_NUMERIC 2103
+#define F_AVG_FLOAT4 2104
+#define F_AVG_FLOAT8 2105
+#define F_AVG_INTERVAL 2106
+#define F_SUM_INT8 2107
+#define F_SUM_INT4 2108
+#define F_SUM_INT2 2109
+#define F_SUM_FLOAT4 2110
+#define F_SUM_FLOAT8 2111
+#define F_SUM_MONEY 2112
+#define F_SUM_INTERVAL 2113
+#define F_SUM_NUMERIC 2114
+#define F_MAX_INT8 2115
+#define F_MAX_INT4 2116
+#define F_MAX_INT2 2117
+#define F_MAX_OID 2118
+#define F_MAX_FLOAT4 2119
+#define F_MAX_FLOAT8 2120
+#define F_PG_COLUMN_COMPRESSION 2121
+#define F_MAX_DATE 2122
+#define F_MAX_TIME 2123
+#define F_MAX_TIMETZ 2124
+#define F_MAX_MONEY 2125
+#define F_MAX_TIMESTAMP 2126
+#define F_MAX_TIMESTAMPTZ 2127
+#define F_MAX_INTERVAL 2128
+#define F_MAX_TEXT 2129
+#define F_MAX_NUMERIC 2130
+#define F_MIN_INT8 2131
+#define F_MIN_INT4 2132
+#define F_MIN_INT2 2133
+#define F_MIN_OID 2134
+#define F_MIN_FLOAT4 2135
+#define F_MIN_FLOAT8 2136
+#define F_PG_STAT_FORCE_NEXT_FLUSH 2137
+#define F_MIN_DATE 2138
+#define F_MIN_TIME 2139
+#define F_MIN_TIMETZ 2140
+#define F_MIN_MONEY 2141
+#define F_MIN_TIMESTAMP 2142
+#define F_MIN_TIMESTAMPTZ 2143
+#define F_MIN_INTERVAL 2144
+#define F_MIN_TEXT 2145
+#define F_MIN_NUMERIC 2146
+#define F_COUNT_ANY 2147
+#define F_VARIANCE_INT8 2148
+#define F_VARIANCE_INT4 2149
+#define F_VARIANCE_INT2 2150
+#define F_VARIANCE_FLOAT4 2151
+#define F_VARIANCE_FLOAT8 2152
+#define F_VARIANCE_NUMERIC 2153
+#define F_STDDEV_INT8 2154
+#define F_STDDEV_INT4 2155
+#define F_STDDEV_INT2 2156
+#define F_STDDEV_FLOAT4 2157
+#define F_STDDEV_FLOAT8 2158
+#define F_STDDEV_NUMERIC 2159
+#define F_TEXT_PATTERN_LT 2160
+#define F_TEXT_PATTERN_LE 2161
+#define F_PG_GET_FUNCTION_ARGUMENTS 2162
+#define F_TEXT_PATTERN_GE 2163
+#define F_TEXT_PATTERN_GT 2164
+#define F_PG_GET_FUNCTION_RESULT 2165
+#define F_BTTEXT_PATTERN_CMP 2166
+#define F_CEILING_NUMERIC 2167
+#define F_PG_DATABASE_SIZE_NAME 2168
+#define F_POWER_NUMERIC_NUMERIC 2169
+#define F_WIDTH_BUCKET_NUMERIC_NUMERIC_NUMERIC_INT4 2170
+#define F_PG_CANCEL_BACKEND 2171
+#define F_PG_BACKUP_START 2172
+#define F_BPCHAR_PATTERN_LT 2174
+#define F_BPCHAR_PATTERN_LE 2175
+#define F_ARRAY_LENGTH 2176
+#define F_BPCHAR_PATTERN_GE 2177
+#define F_BPCHAR_PATTERN_GT 2178
+#define F_GIST_POINT_CONSISTENT 2179
+#define F_BTBPCHAR_PATTERN_CMP 2180
+#define F_HAS_SEQUENCE_PRIVILEGE_NAME_TEXT_TEXT 2181
+#define F_HAS_SEQUENCE_PRIVILEGE_NAME_OID_TEXT 2182
+#define F_HAS_SEQUENCE_PRIVILEGE_OID_TEXT_TEXT 2183
+#define F_HAS_SEQUENCE_PRIVILEGE_OID_OID_TEXT 2184
+#define F_HAS_SEQUENCE_PRIVILEGE_TEXT_TEXT 2185
+#define F_HAS_SEQUENCE_PRIVILEGE_OID_TEXT 2186
+#define F_BTINT48CMP 2188
+#define F_BTINT84CMP 2189
+#define F_BTINT24CMP 2190
+#define F_BTINT42CMP 2191
+#define F_BTINT28CMP 2192
+#define F_BTINT82CMP 2193
+#define F_BTFLOAT48CMP 2194
+#define F_BTFLOAT84CMP 2195
+#define F_INET_CLIENT_ADDR 2196
+#define F_INET_CLIENT_PORT 2197
+#define F_INET_SERVER_ADDR 2198
+#define F_INET_SERVER_PORT 2199
+#define F_REGPROCEDUREIN 2212
+#define F_REGPROCEDUREOUT 2213
+#define F_REGOPERIN 2214
+#define F_REGOPEROUT 2215
+#define F_REGOPERATORIN 2216
+#define F_REGOPERATOROUT 2217
+#define F_REGCLASSIN 2218
+#define F_REGCLASSOUT 2219
+#define F_REGTYPEIN 2220
+#define F_REGTYPEOUT 2221
+#define F_PG_STAT_CLEAR_SNAPSHOT 2230
+#define F_PG_GET_FUNCTION_IDENTITY_ARGUMENTS 2232
+#define F_HASHTID 2233
+#define F_HASHTIDEXTENDED 2234
+#define F_BIT_AND_INT2 2236
+#define F_BIT_OR_INT2 2237
+#define F_BIT_AND_INT4 2238
+#define F_BIT_OR_INT4 2239
+#define F_BIT_AND_INT8 2240
+#define F_BIT_OR_INT8 2241
+#define F_BIT_AND_BIT 2242
+#define F_BIT_OR_BIT 2243
+#define F_MAX_BPCHAR 2244
+#define F_MIN_BPCHAR 2245
+#define F_FMGR_INTERNAL_VALIDATOR 2246
+#define F_FMGR_C_VALIDATOR 2247
+#define F_FMGR_SQL_VALIDATOR 2248
+#define F_HAS_DATABASE_PRIVILEGE_NAME_TEXT_TEXT 2250
+#define F_HAS_DATABASE_PRIVILEGE_NAME_OID_TEXT 2251
+#define F_HAS_DATABASE_PRIVILEGE_OID_TEXT_TEXT 2252
+#define F_HAS_DATABASE_PRIVILEGE_OID_OID_TEXT 2253
+#define F_HAS_DATABASE_PRIVILEGE_TEXT_TEXT 2254
+#define F_HAS_DATABASE_PRIVILEGE_OID_TEXT 2255
+#define F_HAS_FUNCTION_PRIVILEGE_NAME_TEXT_TEXT 2256
+#define F_HAS_FUNCTION_PRIVILEGE_NAME_OID_TEXT 2257
+#define F_HAS_FUNCTION_PRIVILEGE_OID_TEXT_TEXT 2258
+#define F_HAS_FUNCTION_PRIVILEGE_OID_OID_TEXT 2259
+#define F_HAS_FUNCTION_PRIVILEGE_TEXT_TEXT 2260
+#define F_HAS_FUNCTION_PRIVILEGE_OID_TEXT 2261
+#define F_HAS_LANGUAGE_PRIVILEGE_NAME_TEXT_TEXT 2262
+#define F_HAS_LANGUAGE_PRIVILEGE_NAME_OID_TEXT 2263
+#define F_HAS_LANGUAGE_PRIVILEGE_OID_TEXT_TEXT 2264
+#define F_HAS_LANGUAGE_PRIVILEGE_OID_OID_TEXT 2265
+#define F_HAS_LANGUAGE_PRIVILEGE_TEXT_TEXT 2266
+#define F_HAS_LANGUAGE_PRIVILEGE_OID_TEXT 2267
+#define F_HAS_SCHEMA_PRIVILEGE_NAME_TEXT_TEXT 2268
+#define F_HAS_SCHEMA_PRIVILEGE_NAME_OID_TEXT 2269
+#define F_HAS_SCHEMA_PRIVILEGE_OID_TEXT_TEXT 2270
+#define F_HAS_SCHEMA_PRIVILEGE_OID_OID_TEXT 2271
+#define F_HAS_SCHEMA_PRIVILEGE_TEXT_TEXT 2272
+#define F_HAS_SCHEMA_PRIVILEGE_OID_TEXT 2273
+#define F_PG_STAT_RESET 2274
+#define F_PG_GET_BACKEND_MEMORY_CONTEXTS 2282
+#define F_REGEXP_REPLACE_TEXT_TEXT_TEXT 2284
+#define F_REGEXP_REPLACE_TEXT_TEXT_TEXT_TEXT 2285
+#define F_PG_TOTAL_RELATION_SIZE 2286
+#define F_PG_SIZE_PRETTY_INT8 2288
+#define F_PG_OPTIONS_TO_TABLE 2289
+#define F_RECORD_IN 2290
+#define F_RECORD_OUT 2291
+#define F_CSTRING_IN 2292
+#define F_CSTRING_OUT 2293
+#define F_ANY_IN 2294
+#define F_ANY_OUT 2295
+#define F_ANYARRAY_IN 2296
+#define F_ANYARRAY_OUT 2297
+#define F_VOID_IN 2298
+#define F_VOID_OUT 2299
+#define F_TRIGGER_IN 2300
+#define F_TRIGGER_OUT 2301
+#define F_LANGUAGE_HANDLER_IN 2302
+#define F_LANGUAGE_HANDLER_OUT 2303
+#define F_INTERNAL_IN 2304
+#define F_INTERNAL_OUT 2305
+#define F_PG_STAT_GET_SLRU 2306
+#define F_PG_STAT_RESET_SLRU 2307
+#define F_CEIL_FLOAT8 2308
+#define F_FLOOR_FLOAT8 2309
+#define F_SIGN_FLOAT8 2310
+#define F_MD5_TEXT 2311
+#define F_ANYELEMENT_IN 2312
+#define F_ANYELEMENT_OUT 2313
+#define F_POSTGRESQL_FDW_VALIDATOR 2316
+#define F_PG_ENCODING_MAX_LENGTH 2319
+#define F_CEILING_FLOAT8 2320
+#define F_MD5_BYTEA 2321
+#define F_PG_TABLESPACE_SIZE_OID 2322
+#define F_PG_TABLESPACE_SIZE_NAME 2323
+#define F_PG_DATABASE_SIZE_OID 2324
+#define F_PG_RELATION_SIZE_REGCLASS 2325
+#define F_UNNEST_ANYARRAY 2331
+#define F_PG_RELATION_SIZE_REGCLASS_TEXT 2332
+#define F_ARRAY_AGG_TRANSFN 2333
+#define F_ARRAY_AGG_FINALFN 2334
+#define F_ARRAY_AGG_ANYNONARRAY 2335
+#define F_DATE_LT_TIMESTAMP 2338
+#define F_DATE_LE_TIMESTAMP 2339
+#define F_DATE_EQ_TIMESTAMP 2340
+#define F_DATE_GT_TIMESTAMP 2341
+#define F_DATE_GE_TIMESTAMP 2342
+#define F_DATE_NE_TIMESTAMP 2343
+#define F_DATE_CMP_TIMESTAMP 2344
+#define F_DATE_LT_TIMESTAMPTZ 2351
+#define F_DATE_LE_TIMESTAMPTZ 2352
+#define F_DATE_EQ_TIMESTAMPTZ 2353
+#define F_DATE_GT_TIMESTAMPTZ 2354
+#define F_DATE_GE_TIMESTAMPTZ 2355
+#define F_DATE_NE_TIMESTAMPTZ 2356
+#define F_DATE_CMP_TIMESTAMPTZ 2357
+#define F_TIMESTAMP_LT_DATE 2364
+#define F_TIMESTAMP_LE_DATE 2365
+#define F_TIMESTAMP_EQ_DATE 2366
+#define F_TIMESTAMP_GT_DATE 2367
+#define F_TIMESTAMP_GE_DATE 2368
+#define F_TIMESTAMP_NE_DATE 2369
+#define F_TIMESTAMP_CMP_DATE 2370
+#define F_TIMESTAMPTZ_LT_DATE 2377
+#define F_TIMESTAMPTZ_LE_DATE 2378
+#define F_TIMESTAMPTZ_EQ_DATE 2379
+#define F_TIMESTAMPTZ_GT_DATE 2380
+#define F_TIMESTAMPTZ_GE_DATE 2381
+#define F_TIMESTAMPTZ_NE_DATE 2382
+#define F_TIMESTAMPTZ_CMP_DATE 2383
+#define F_HAS_TABLESPACE_PRIVILEGE_NAME_TEXT_TEXT 2390
+#define F_HAS_TABLESPACE_PRIVILEGE_NAME_OID_TEXT 2391
+#define F_HAS_TABLESPACE_PRIVILEGE_OID_TEXT_TEXT 2392
+#define F_HAS_TABLESPACE_PRIVILEGE_OID_OID_TEXT 2393
+#define F_HAS_TABLESPACE_PRIVILEGE_TEXT_TEXT 2394
+#define F_HAS_TABLESPACE_PRIVILEGE_OID_TEXT 2395
+#define F_SHELL_IN 2398
+#define F_SHELL_OUT 2399
+#define F_ARRAY_RECV 2400
+#define F_ARRAY_SEND 2401
+#define F_RECORD_RECV 2402
+#define F_RECORD_SEND 2403
+#define F_INT2RECV 2404
+#define F_INT2SEND 2405
+#define F_INT4RECV 2406
+#define F_INT4SEND 2407
+#define F_INT8RECV 2408
+#define F_INT8SEND 2409
+#define F_INT2VECTORRECV 2410
+#define F_INT2VECTORSEND 2411
+#define F_BYTEARECV 2412
+#define F_BYTEASEND 2413
+#define F_TEXTRECV 2414
+#define F_TEXTSEND 2415
+#define F_UNKNOWNRECV 2416
+#define F_UNKNOWNSEND 2417
+#define F_OIDRECV 2418
+#define F_OIDSEND 2419
+#define F_OIDVECTORRECV 2420
+#define F_OIDVECTORSEND 2421
+#define F_NAMERECV 2422
+#define F_NAMESEND 2423
+#define F_FLOAT4RECV 2424
+#define F_FLOAT4SEND 2425
+#define F_FLOAT8RECV 2426
+#define F_FLOAT8SEND 2427
+#define F_POINT_RECV 2428
+#define F_POINT_SEND 2429
+#define F_BPCHARRECV 2430
+#define F_BPCHARSEND 2431
+#define F_VARCHARRECV 2432
+#define F_VARCHARSEND 2433
+#define F_CHARRECV 2434
+#define F_CHARSEND 2435
+#define F_BOOLRECV 2436
+#define F_BOOLSEND 2437
+#define F_TIDRECV 2438
+#define F_TIDSEND 2439
+#define F_XIDRECV 2440
+#define F_XIDSEND 2441
+#define F_CIDRECV 2442
+#define F_CIDSEND 2443
+#define F_REGPROCRECV 2444
+#define F_REGPROCSEND 2445
+#define F_REGPROCEDURERECV 2446
+#define F_REGPROCEDURESEND 2447
+#define F_REGOPERRECV 2448
+#define F_REGOPERSEND 2449
+#define F_REGOPERATORRECV 2450
+#define F_REGOPERATORSEND 2451
+#define F_REGCLASSRECV 2452
+#define F_REGCLASSSEND 2453
+#define F_REGTYPERECV 2454
+#define F_REGTYPESEND 2455
+#define F_BIT_RECV 2456
+#define F_BIT_SEND 2457
+#define F_VARBIT_RECV 2458
+#define F_VARBIT_SEND 2459
+#define F_NUMERIC_RECV 2460
+#define F_NUMERIC_SEND 2461
+#define F_SINH 2462
+#define F_COSH 2463
+#define F_TANH 2464
+#define F_ASINH 2465
+#define F_ACOSH 2466
+#define F_ATANH 2467
+#define F_DATE_RECV 2468
+#define F_DATE_SEND 2469
+#define F_TIME_RECV 2470
+#define F_TIME_SEND 2471
+#define F_TIMETZ_RECV 2472
+#define F_TIMETZ_SEND 2473
+#define F_TIMESTAMP_RECV 2474
+#define F_TIMESTAMP_SEND 2475
+#define F_TIMESTAMPTZ_RECV 2476
+#define F_TIMESTAMPTZ_SEND 2477
+#define F_INTERVAL_RECV 2478
+#define F_INTERVAL_SEND 2479
+#define F_LSEG_RECV 2480
+#define F_LSEG_SEND 2481
+#define F_PATH_RECV 2482
+#define F_PATH_SEND 2483
+#define F_BOX_RECV 2484
+#define F_BOX_SEND 2485
+#define F_POLY_RECV 2486
+#define F_POLY_SEND 2487
+#define F_LINE_RECV 2488
+#define F_LINE_SEND 2489
+#define F_CIRCLE_RECV 2490
+#define F_CIRCLE_SEND 2491
+#define F_CASH_RECV 2492
+#define F_CASH_SEND 2493
+#define F_MACADDR_RECV 2494
+#define F_MACADDR_SEND 2495
+#define F_INET_RECV 2496
+#define F_INET_SEND 2497
+#define F_CIDR_RECV 2498
+#define F_CIDR_SEND 2499
+#define F_CSTRING_RECV 2500
+#define F_CSTRING_SEND 2501
+#define F_ANYARRAY_RECV 2502
+#define F_ANYARRAY_SEND 2503
+#define F_PG_GET_RULEDEF_OID_BOOL 2504
+#define F_PG_GET_VIEWDEF_TEXT_BOOL 2505
+#define F_PG_GET_VIEWDEF_OID_BOOL 2506
+#define F_PG_GET_INDEXDEF_OID_INT4_BOOL 2507
+#define F_PG_GET_CONSTRAINTDEF_OID_BOOL 2508
+#define F_PG_GET_EXPR_PG_NODE_TREE_OID_BOOL 2509
+#define F_PG_PREPARED_STATEMENT 2510
+#define F_PG_CURSOR 2511
+#define F_FLOAT8_VAR_POP 2512
+#define F_FLOAT8_STDDEV_POP 2513
+#define F_NUMERIC_VAR_POP 2514
+#define F_BOOLAND_STATEFUNC 2515
+#define F_BOOLOR_STATEFUNC 2516
+#define F_BOOL_AND 2517
+#define F_BOOL_OR 2518
+#define F_EVERY 2519
+#define F_TIMESTAMP_LT_TIMESTAMPTZ 2520
+#define F_TIMESTAMP_LE_TIMESTAMPTZ 2521
+#define F_TIMESTAMP_EQ_TIMESTAMPTZ 2522
+#define F_TIMESTAMP_GT_TIMESTAMPTZ 2523
+#define F_TIMESTAMP_GE_TIMESTAMPTZ 2524
+#define F_TIMESTAMP_NE_TIMESTAMPTZ 2525
+#define F_TIMESTAMP_CMP_TIMESTAMPTZ 2526
+#define F_TIMESTAMPTZ_LT_TIMESTAMP 2527
+#define F_TIMESTAMPTZ_LE_TIMESTAMP 2528
+#define F_TIMESTAMPTZ_EQ_TIMESTAMP 2529
+#define F_TIMESTAMPTZ_GT_TIMESTAMP 2530
+#define F_TIMESTAMPTZ_GE_TIMESTAMP 2531
+#define F_TIMESTAMPTZ_NE_TIMESTAMP 2532
+#define F_TIMESTAMPTZ_CMP_TIMESTAMP 2533
+#define F_INTERVAL_PL_DATE 2546
+#define F_INTERVAL_PL_TIMETZ 2547
+#define F_INTERVAL_PL_TIMESTAMP 2548
+#define F_INTERVAL_PL_TIMESTAMPTZ 2549
+#define F_INTEGER_PL_DATE 2550
+#define F_PG_TABLESPACE_DATABASES 2556
+#define F_BOOL_INT4 2557
+#define F_INT4_BOOL 2558
+#define F_LASTVAL 2559
+#define F_PG_POSTMASTER_START_TIME 2560
+#define F_PG_BLOCKING_PIDS 2561
+#define F_BOX_BELOW 2562
+#define F_BOX_OVERBELOW 2563
+#define F_BOX_OVERABOVE 2564
+#define F_BOX_ABOVE 2565
+#define F_POLY_BELOW 2566
+#define F_POLY_OVERBELOW 2567
+#define F_POLY_OVERABOVE 2568
+#define F_POLY_ABOVE 2569
+#define F_GIST_BOX_CONSISTENT 2578
+#define F_FLOAT8_JSONB 2580
+#define F_GIST_BOX_PENALTY 2581
+#define F_GIST_BOX_PICKSPLIT 2582
+#define F_GIST_BOX_UNION 2583
+#define F_GIST_BOX_SAME 2584
+#define F_GIST_POLY_CONSISTENT 2585
+#define F_GIST_POLY_COMPRESS 2586
+#define F_CIRCLE_OVERBELOW 2587
+#define F_CIRCLE_OVERABOVE 2588
+#define F_GIST_CIRCLE_CONSISTENT 2591
+#define F_GIST_CIRCLE_COMPRESS 2592
+#define F_NUMERIC_STDDEV_POP 2596
+#define F_DOMAIN_IN 2597
+#define F_DOMAIN_RECV 2598
+#define F_PG_TIMEZONE_ABBREVS 2599
+#define F_XMLEXISTS 2614
+#define F_PG_RELOAD_CONF 2621
+#define F_PG_ROTATE_LOGFILE 2622
+#define F_PG_STAT_FILE_TEXT 2623
+#define F_PG_READ_FILE_TEXT_INT8_INT8 2624
+#define F_PG_LS_DIR_TEXT 2625
+#define F_PG_SLEEP 2626
+#define F_INETNOT 2627
+#define F_INETAND 2628
+#define F_INETOR 2629
+#define F_INETPL 2630
+#define F_INT8PL_INET 2631
+#define F_INETMI_INT8 2632
+#define F_INETMI 2633
+#define F_VAR_SAMP_INT8 2641
+#define F_VAR_SAMP_INT4 2642
+#define F_VAR_SAMP_INT2 2643
+#define F_VAR_SAMP_FLOAT4 2644
+#define F_VAR_SAMP_FLOAT8 2645
+#define F_VAR_SAMP_NUMERIC 2646
+#define F_TRANSACTION_TIMESTAMP 2647
+#define F_STATEMENT_TIMESTAMP 2648
+#define F_CLOCK_TIMESTAMP 2649
+#define F_GIN_CMP_PREFIX 2700
+#define F_PG_HAS_ROLE_NAME_NAME_TEXT 2705
+#define F_PG_HAS_ROLE_NAME_OID_TEXT 2706
+#define F_PG_HAS_ROLE_OID_NAME_TEXT 2707
+#define F_PG_HAS_ROLE_OID_OID_TEXT 2708
+#define F_PG_HAS_ROLE_NAME_TEXT 2709
+#define F_PG_HAS_ROLE_OID_TEXT 2710
+#define F_JUSTIFY_INTERVAL 2711
+#define F_STDDEV_SAMP_INT8 2712
+#define F_STDDEV_SAMP_INT4 2713
+#define F_STDDEV_SAMP_INT2 2714
+#define F_STDDEV_SAMP_FLOAT4 2715
+#define F_STDDEV_SAMP_FLOAT8 2716
+#define F_STDDEV_SAMP_NUMERIC 2717
+#define F_VAR_POP_INT8 2718
+#define F_VAR_POP_INT4 2719
+#define F_VAR_POP_INT2 2720
+#define F_VAR_POP_FLOAT4 2721
+#define F_VAR_POP_FLOAT8 2722
+#define F_VAR_POP_NUMERIC 2723
+#define F_STDDEV_POP_INT8 2724
+#define F_STDDEV_POP_INT4 2725
+#define F_STDDEV_POP_INT2 2726
+#define F_STDDEV_POP_FLOAT4 2727
+#define F_STDDEV_POP_FLOAT8 2728
+#define F_STDDEV_POP_NUMERIC 2729
+#define F_PG_GET_TRIGGERDEF_OID_BOOL 2730
+#define F_ASIND 2731
+#define F_ACOSD 2732
+#define F_ATAND 2733
+#define F_ATAN2D 2734
+#define F_SIND 2735
+#define F_COSD 2736
+#define F_TAND 2737
+#define F_COTD 2738
+#define F_PG_BACKUP_STOP 2739
+#define F_NUMERIC_AVG_SERIALIZE 2740
+#define F_NUMERIC_AVG_DESERIALIZE 2741
+#define F_GINARRAYEXTRACT_ANYARRAY_INTERNAL_INTERNAL 2743
+#define F_GINARRAYCONSISTENT 2744
+#define F_INT8_AVG_ACCUM 2746
+#define F_ARRAYOVERLAP 2747
+#define F_ARRAYCONTAINS 2748
+#define F_ARRAYCONTAINED 2749
+#define F_PG_STAT_GET_DB_TUPLES_RETURNED 2758
+#define F_PG_STAT_GET_DB_TUPLES_FETCHED 2759
+#define F_PG_STAT_GET_DB_TUPLES_INSERTED 2760
+#define F_PG_STAT_GET_DB_TUPLES_UPDATED 2761
+#define F_PG_STAT_GET_DB_TUPLES_DELETED 2762
+#define F_REGEXP_MATCHES_TEXT_TEXT 2763
+#define F_REGEXP_MATCHES_TEXT_TEXT_TEXT 2764
+#define F_REGEXP_SPLIT_TO_TABLE_TEXT_TEXT 2765
+#define F_REGEXP_SPLIT_TO_TABLE_TEXT_TEXT_TEXT 2766
+#define F_REGEXP_SPLIT_TO_ARRAY_TEXT_TEXT 2767
+#define F_REGEXP_SPLIT_TO_ARRAY_TEXT_TEXT_TEXT 2768
+#define F_PG_STAT_GET_BGWRITER_TIMED_CHECKPOINTS 2769
+#define F_PG_STAT_GET_BGWRITER_REQUESTED_CHECKPOINTS 2770
+#define F_PG_STAT_GET_BGWRITER_BUF_WRITTEN_CHECKPOINTS 2771
+#define F_PG_STAT_GET_BGWRITER_BUF_WRITTEN_CLEAN 2772
+#define F_PG_STAT_GET_BGWRITER_MAXWRITTEN_CLEAN 2773
+#define F_GINQUERYARRAYEXTRACT 2774
+#define F_PG_STAT_GET_BUF_WRITTEN_BACKEND 2775
+#define F_ANYNONARRAY_IN 2777
+#define F_ANYNONARRAY_OUT 2778
+#define F_PG_STAT_GET_LAST_VACUUM_TIME 2781
+#define F_PG_STAT_GET_LAST_AUTOVACUUM_TIME 2782
+#define F_PG_STAT_GET_LAST_ANALYZE_TIME 2783
+#define F_PG_STAT_GET_LAST_AUTOANALYZE_TIME 2784
+#define F_INT8_AVG_COMBINE 2785
+#define F_INT8_AVG_SERIALIZE 2786
+#define F_INT8_AVG_DESERIALIZE 2787
+#define F_PG_STAT_GET_BACKEND_WAIT_EVENT_TYPE 2788
+#define F_TIDGT 2790
+#define F_TIDLT 2791
+#define F_TIDGE 2792
+#define F_TIDLE 2793
+#define F_BTTIDCMP 2794
+#define F_TIDLARGER 2795
+#define F_TIDSMALLER 2796
+#define F_MAX_TID 2797
+#define F_MIN_TID 2798
+#define F_COUNT_ 2803
+#define F_INT8INC_ANY 2804
+#define F_INT8INC_FLOAT8_FLOAT8 2805
+#define F_FLOAT8_REGR_ACCUM 2806
+#define F_FLOAT8_REGR_SXX 2807
+#define F_FLOAT8_REGR_SYY 2808
+#define F_FLOAT8_REGR_SXY 2809
+#define F_FLOAT8_REGR_AVGX 2810
+#define F_FLOAT8_REGR_AVGY 2811
+#define F_FLOAT8_REGR_R2 2812
+#define F_FLOAT8_REGR_SLOPE 2813
+#define F_FLOAT8_REGR_INTERCEPT 2814
+#define F_FLOAT8_COVAR_POP 2815
+#define F_FLOAT8_COVAR_SAMP 2816
+#define F_FLOAT8_CORR 2817
+#define F_REGR_COUNT 2818
+#define F_REGR_SXX 2819
+#define F_REGR_SYY 2820
+#define F_REGR_SXY 2821
+#define F_REGR_AVGX 2822
+#define F_REGR_AVGY 2823
+#define F_REGR_R2 2824
+#define F_REGR_SLOPE 2825
+#define F_REGR_INTERCEPT 2826
+#define F_COVAR_POP 2827
+#define F_COVAR_SAMP 2828
+#define F_CORR 2829
+#define F_PG_STAT_GET_DB_BLK_READ_TIME 2844
+#define F_PG_STAT_GET_DB_BLK_WRITE_TIME 2845
+#define F_PG_SWITCH_WAL 2848
+#define F_PG_CURRENT_WAL_LSN 2849
+#define F_PG_WALFILE_NAME_OFFSET 2850
+#define F_PG_WALFILE_NAME 2851
+#define F_PG_CURRENT_WAL_INSERT_LSN 2852
+#define F_PG_STAT_GET_BACKEND_WAIT_EVENT 2853
+#define F_PG_MY_TEMP_SCHEMA 2854
+#define F_PG_IS_OTHER_TEMP_SCHEMA 2855
+#define F_PG_TIMEZONE_NAMES 2856
+#define F_PG_STAT_GET_BACKEND_XACT_START 2857
+#define F_NUMERIC_AVG_ACCUM 2858
+#define F_PG_STAT_GET_BUF_ALLOC 2859
+#define F_PG_STAT_GET_LIVE_TUPLES 2878
+#define F_PG_STAT_GET_DEAD_TUPLES 2879
+#define F_PG_ADVISORY_LOCK_INT8 2880
+#define F_PG_ADVISORY_LOCK_SHARED_INT8 2881
+#define F_PG_TRY_ADVISORY_LOCK_INT8 2882
+#define F_PG_TRY_ADVISORY_LOCK_SHARED_INT8 2883
+#define F_PG_ADVISORY_UNLOCK_INT8 2884
+#define F_PG_ADVISORY_UNLOCK_SHARED_INT8 2885
+#define F_PG_ADVISORY_LOCK_INT4_INT4 2886
+#define F_PG_ADVISORY_LOCK_SHARED_INT4_INT4 2887
+#define F_PG_TRY_ADVISORY_LOCK_INT4_INT4 2888
+#define F_PG_TRY_ADVISORY_LOCK_SHARED_INT4_INT4 2889
+#define F_PG_ADVISORY_UNLOCK_INT4_INT4 2890
+#define F_PG_ADVISORY_UNLOCK_SHARED_INT4_INT4 2891
+#define F_PG_ADVISORY_UNLOCK_ALL 2892
+#define F_XML_IN 2893
+#define F_XML_OUT 2894
+#define F_XMLCOMMENT 2895
+#define F_XML 2896
+#define F_XMLVALIDATE 2897
+#define F_XML_RECV 2898
+#define F_XML_SEND 2899
+#define F_XMLCONCAT2 2900
+#define F_XMLAGG 2901
+#define F_VARBITTYPMODIN 2902
+#define F_INTERVALTYPMODIN 2903
+#define F_INTERVALTYPMODOUT 2904
+#define F_TIMESTAMPTYPMODIN 2905
+#define F_TIMESTAMPTYPMODOUT 2906
+#define F_TIMESTAMPTZTYPMODIN 2907
+#define F_TIMESTAMPTZTYPMODOUT 2908
+#define F_TIMETYPMODIN 2909
+#define F_TIMETYPMODOUT 2910
+#define F_TIMETZTYPMODIN 2911
+#define F_TIMETZTYPMODOUT 2912
+#define F_BPCHARTYPMODIN 2913
+#define F_BPCHARTYPMODOUT 2914
+#define F_VARCHARTYPMODIN 2915
+#define F_VARCHARTYPMODOUT 2916
+#define F_NUMERICTYPMODIN 2917
+#define F_NUMERICTYPMODOUT 2918
+#define F_BITTYPMODIN 2919
+#define F_BITTYPMODOUT 2920
+#define F_VARBITTYPMODOUT 2921
+#define F_TEXT_XML 2922
+#define F_TABLE_TO_XML 2923
+#define F_QUERY_TO_XML 2924
+#define F_CURSOR_TO_XML 2925
+#define F_TABLE_TO_XMLSCHEMA 2926
+#define F_QUERY_TO_XMLSCHEMA 2927
+#define F_CURSOR_TO_XMLSCHEMA 2928
+#define F_TABLE_TO_XML_AND_XMLSCHEMA 2929
+#define F_QUERY_TO_XML_AND_XMLSCHEMA 2930
+#define F_XPATH_TEXT_XML__TEXT 2931
+#define F_XPATH_TEXT_XML 2932
+#define F_SCHEMA_TO_XML 2933
+#define F_SCHEMA_TO_XMLSCHEMA 2934
+#define F_SCHEMA_TO_XML_AND_XMLSCHEMA 2935
+#define F_DATABASE_TO_XML 2936
+#define F_DATABASE_TO_XMLSCHEMA 2937
+#define F_DATABASE_TO_XML_AND_XMLSCHEMA 2938
+#define F_TXID_SNAPSHOT_IN 2939
+#define F_TXID_SNAPSHOT_OUT 2940
+#define F_TXID_SNAPSHOT_RECV 2941
+#define F_TXID_SNAPSHOT_SEND 2942
+#define F_TXID_CURRENT 2943
+#define F_TXID_CURRENT_SNAPSHOT 2944
+#define F_TXID_SNAPSHOT_XMIN 2945
+#define F_TXID_SNAPSHOT_XMAX 2946
+#define F_TXID_SNAPSHOT_XIP 2947
+#define F_TXID_VISIBLE_IN_SNAPSHOT 2948
+#define F_UUID_IN 2952
+#define F_UUID_OUT 2953
+#define F_UUID_LT 2954
+#define F_UUID_LE 2955
+#define F_UUID_EQ 2956
+#define F_UUID_GE 2957
+#define F_UUID_GT 2958
+#define F_UUID_NE 2959
+#define F_UUID_CMP 2960
+#define F_UUID_RECV 2961
+#define F_UUID_SEND 2962
+#define F_UUID_HASH 2963
+#define F_TEXT_BOOL 2971
+#define F_PG_STAT_GET_FUNCTION_CALLS 2978
+#define F_PG_STAT_GET_FUNCTION_TOTAL_TIME 2979
+#define F_PG_STAT_GET_FUNCTION_SELF_TIME 2980
+#define F_RECORD_EQ 2981
+#define F_RECORD_NE 2982
+#define F_RECORD_LT 2983
+#define F_RECORD_GT 2984
+#define F_RECORD_LE 2985
+#define F_RECORD_GE 2986
+#define F_BTRECORDCMP 2987
+#define F_PG_TABLE_SIZE 2997
+#define F_PG_INDEXES_SIZE 2998
+#define F_PG_RELATION_FILENODE 2999
+#define F_HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE_NAME_TEXT_TEXT 3000
+#define F_HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE_NAME_OID_TEXT 3001
+#define F_HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE_OID_TEXT_TEXT 3002
+#define F_HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE_OID_OID_TEXT 3003
+#define F_HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE_TEXT_TEXT 3004
+#define F_HAS_FOREIGN_DATA_WRAPPER_PRIVILEGE_OID_TEXT 3005
+#define F_HAS_SERVER_PRIVILEGE_NAME_TEXT_TEXT 3006
+#define F_HAS_SERVER_PRIVILEGE_NAME_OID_TEXT 3007
+#define F_HAS_SERVER_PRIVILEGE_OID_TEXT_TEXT 3008
+#define F_HAS_SERVER_PRIVILEGE_OID_OID_TEXT 3009
+#define F_HAS_SERVER_PRIVILEGE_TEXT_TEXT 3010
+#define F_HAS_SERVER_PRIVILEGE_OID_TEXT 3011
+#define F_HAS_COLUMN_PRIVILEGE_NAME_TEXT_TEXT_TEXT 3012
+#define F_HAS_COLUMN_PRIVILEGE_NAME_TEXT_INT2_TEXT 3013
+#define F_HAS_COLUMN_PRIVILEGE_NAME_OID_TEXT_TEXT 3014
+#define F_HAS_COLUMN_PRIVILEGE_NAME_OID_INT2_TEXT 3015
+#define F_HAS_COLUMN_PRIVILEGE_OID_TEXT_TEXT_TEXT 3016
+#define F_HAS_COLUMN_PRIVILEGE_OID_TEXT_INT2_TEXT 3017
+#define F_HAS_COLUMN_PRIVILEGE_OID_OID_TEXT_TEXT 3018
+#define F_HAS_COLUMN_PRIVILEGE_OID_OID_INT2_TEXT 3019
+#define F_HAS_COLUMN_PRIVILEGE_TEXT_TEXT_TEXT 3020
+#define F_HAS_COLUMN_PRIVILEGE_TEXT_INT2_TEXT 3021
+#define F_HAS_COLUMN_PRIVILEGE_OID_TEXT_TEXT 3022
+#define F_HAS_COLUMN_PRIVILEGE_OID_INT2_TEXT 3023
+#define F_HAS_ANY_COLUMN_PRIVILEGE_NAME_TEXT_TEXT 3024
+#define F_HAS_ANY_COLUMN_PRIVILEGE_NAME_OID_TEXT 3025
+#define F_HAS_ANY_COLUMN_PRIVILEGE_OID_TEXT_TEXT 3026
+#define F_HAS_ANY_COLUMN_PRIVILEGE_OID_OID_TEXT 3027
+#define F_HAS_ANY_COLUMN_PRIVILEGE_TEXT_TEXT 3028
+#define F_HAS_ANY_COLUMN_PRIVILEGE_OID_TEXT 3029
+#define F_OVERLAY_BIT_BIT_INT4_INT4 3030
+#define F_OVERLAY_BIT_BIT_INT4 3031
+#define F_GET_BIT_BIT_INT4 3032
+#define F_SET_BIT_BIT_INT4_INT4 3033
+#define F_PG_RELATION_FILEPATH 3034
+#define F_PG_LISTENING_CHANNELS 3035
+#define F_PG_NOTIFY 3036
+#define F_PG_STAT_GET_XACT_NUMSCANS 3037
+#define F_PG_STAT_GET_XACT_TUPLES_RETURNED 3038
+#define F_PG_STAT_GET_XACT_TUPLES_FETCHED 3039
+#define F_PG_STAT_GET_XACT_TUPLES_INSERTED 3040
+#define F_PG_STAT_GET_XACT_TUPLES_UPDATED 3041
+#define F_PG_STAT_GET_XACT_TUPLES_DELETED 3042
+#define F_PG_STAT_GET_XACT_TUPLES_HOT_UPDATED 3043
+#define F_PG_STAT_GET_XACT_BLOCKS_FETCHED 3044
+#define F_PG_STAT_GET_XACT_BLOCKS_HIT 3045
+#define F_PG_STAT_GET_XACT_FUNCTION_CALLS 3046
+#define F_PG_STAT_GET_XACT_FUNCTION_TOTAL_TIME 3047
+#define F_PG_STAT_GET_XACT_FUNCTION_SELF_TIME 3048
+#define F_XPATH_EXISTS_TEXT_XML__TEXT 3049
+#define F_XPATH_EXISTS_TEXT_XML 3050
+#define F_XML_IS_WELL_FORMED 3051
+#define F_XML_IS_WELL_FORMED_DOCUMENT 3052
+#define F_XML_IS_WELL_FORMED_CONTENT 3053
+#define F_PG_STAT_GET_VACUUM_COUNT 3054
+#define F_PG_STAT_GET_AUTOVACUUM_COUNT 3055
+#define F_PG_STAT_GET_ANALYZE_COUNT 3056
+#define F_PG_STAT_GET_AUTOANALYZE_COUNT 3057
+#define F_CONCAT 3058
+#define F_CONCAT_WS 3059
+#define F_LEFT 3060
+#define F_RIGHT 3061
+#define F_REVERSE 3062
+#define F_PG_STAT_GET_BUF_FSYNC_BACKEND 3063
+#define F_GIST_POINT_DISTANCE 3064
+#define F_PG_STAT_GET_DB_CONFLICT_TABLESPACE 3065
+#define F_PG_STAT_GET_DB_CONFLICT_LOCK 3066
+#define F_PG_STAT_GET_DB_CONFLICT_SNAPSHOT 3067
+#define F_PG_STAT_GET_DB_CONFLICT_BUFFERPIN 3068
+#define F_PG_STAT_GET_DB_CONFLICT_STARTUP_DEADLOCK 3069
+#define F_PG_STAT_GET_DB_CONFLICT_ALL 3070
+#define F_PG_WAL_REPLAY_PAUSE 3071
+#define F_PG_WAL_REPLAY_RESUME 3072
+#define F_PG_IS_WAL_REPLAY_PAUSED 3073
+#define F_PG_STAT_GET_DB_STAT_RESET_TIME 3074
+#define F_PG_STAT_GET_BGWRITER_STAT_RESET_TIME 3075
+#define F_GINARRAYEXTRACT_ANYARRAY_INTERNAL 3076
+#define F_GIN_EXTRACT_TSVECTOR_TSVECTOR_INTERNAL 3077
+#define F_PG_SEQUENCE_PARAMETERS 3078
+#define F_PG_AVAILABLE_EXTENSIONS 3082
+#define F_PG_AVAILABLE_EXTENSION_VERSIONS 3083
+#define F_PG_EXTENSION_UPDATE_PATHS 3084
+#define F_PG_EXTENSION_CONFIG_DUMP 3086
+#define F_GIN_EXTRACT_TSQUERY_TSQUERY_INTERNAL_INT2_INTERNAL_INTERNAL 3087
+#define F_GIN_TSQUERY_CONSISTENT_INTERNAL_INT2_TSQUERY_INT4_INTERNAL_INTERNAL 3088
+#define F_PG_ADVISORY_XACT_LOCK_INT8 3089
+#define F_PG_ADVISORY_XACT_LOCK_SHARED_INT8 3090
+#define F_PG_TRY_ADVISORY_XACT_LOCK_INT8 3091
+#define F_PG_TRY_ADVISORY_XACT_LOCK_SHARED_INT8 3092
+#define F_PG_ADVISORY_XACT_LOCK_INT4_INT4 3093
+#define F_PG_ADVISORY_XACT_LOCK_SHARED_INT4_INT4 3094
+#define F_PG_TRY_ADVISORY_XACT_LOCK_INT4_INT4 3095
+#define F_PG_TRY_ADVISORY_XACT_LOCK_SHARED_INT4_INT4 3096
+#define F_VARCHAR_SUPPORT 3097
+#define F_PG_CREATE_RESTORE_POINT 3098
+#define F_PG_STAT_GET_WAL_SENDERS 3099
+#define F_ROW_NUMBER 3100
+#define F_RANK_ 3101
+#define F_DENSE_RANK_ 3102
+#define F_PERCENT_RANK_ 3103
+#define F_CUME_DIST_ 3104
+#define F_NTILE 3105
+#define F_LAG_ANYELEMENT 3106
+#define F_LAG_ANYELEMENT_INT4 3107
+#define F_LAG_ANYCOMPATIBLE_INT4_ANYCOMPATIBLE 3108
+#define F_LEAD_ANYELEMENT 3109
+#define F_LEAD_ANYELEMENT_INT4 3110
+#define F_LEAD_ANYCOMPATIBLE_INT4_ANYCOMPATIBLE 3111
+#define F_FIRST_VALUE 3112
+#define F_LAST_VALUE 3113
+#define F_NTH_VALUE 3114
+#define F_FDW_HANDLER_IN 3116
+#define F_FDW_HANDLER_OUT 3117
+#define F_VOID_RECV 3120
+#define F_VOID_SEND 3121
+#define F_BTINT2SORTSUPPORT 3129
+#define F_BTINT4SORTSUPPORT 3130
+#define F_BTINT8SORTSUPPORT 3131
+#define F_BTFLOAT4SORTSUPPORT 3132
+#define F_BTFLOAT8SORTSUPPORT 3133
+#define F_BTOIDSORTSUPPORT 3134
+#define F_BTNAMESORTSUPPORT 3135
+#define F_DATE_SORTSUPPORT 3136
+#define F_TIMESTAMP_SORTSUPPORT 3137
+#define F_HAS_TYPE_PRIVILEGE_NAME_TEXT_TEXT 3138
+#define F_HAS_TYPE_PRIVILEGE_NAME_OID_TEXT 3139
+#define F_HAS_TYPE_PRIVILEGE_OID_TEXT_TEXT 3140
+#define F_HAS_TYPE_PRIVILEGE_OID_OID_TEXT 3141
+#define F_HAS_TYPE_PRIVILEGE_TEXT_TEXT 3142
+#define F_HAS_TYPE_PRIVILEGE_OID_TEXT 3143
+#define F_MACADDR_NOT 3144
+#define F_MACADDR_AND 3145
+#define F_MACADDR_OR 3146
+#define F_PG_STAT_GET_DB_TEMP_FILES 3150
+#define F_PG_STAT_GET_DB_TEMP_BYTES 3151
+#define F_PG_STAT_GET_DB_DEADLOCKS 3152
+#define F_ARRAY_TO_JSON_ANYARRAY 3153
+#define F_ARRAY_TO_JSON_ANYARRAY_BOOL 3154
+#define F_ROW_TO_JSON_RECORD 3155
+#define F_ROW_TO_JSON_RECORD_BOOL 3156
+#define F_NUMERIC_SUPPORT 3157
+#define F_VARBIT_SUPPORT 3158
+#define F_PG_GET_VIEWDEF_OID_INT4 3159
+#define F_PG_STAT_GET_CHECKPOINT_WRITE_TIME 3160
+#define F_PG_STAT_GET_CHECKPOINT_SYNC_TIME 3161
+#define F_PG_COLLATION_FOR 3162
+#define F_PG_TRIGGER_DEPTH 3163
+#define F_PG_WAL_LSN_DIFF 3165
+#define F_PG_SIZE_PRETTY_NUMERIC 3166
+#define F_ARRAY_REMOVE 3167
+#define F_ARRAY_REPLACE 3168
+#define F_RANGESEL 3169
+#define F_LO_LSEEK64 3170
+#define F_LO_TELL64 3171
+#define F_LO_TRUNCATE64 3172
+#define F_JSON_AGG_TRANSFN 3173
+#define F_JSON_AGG_FINALFN 3174
+#define F_JSON_AGG 3175
+#define F_TO_JSON 3176
+#define F_PG_STAT_GET_MOD_SINCE_ANALYZE 3177
+#define F_NUMERIC_SUM 3178
+#define F_CARDINALITY 3179
+#define F_JSON_OBJECT_AGG_TRANSFN 3180
+#define F_RECORD_IMAGE_EQ 3181
+#define F_RECORD_IMAGE_NE 3182
+#define F_RECORD_IMAGE_LT 3183
+#define F_RECORD_IMAGE_GT 3184
+#define F_RECORD_IMAGE_LE 3185
+#define F_RECORD_IMAGE_GE 3186
+#define F_BTRECORDIMAGECMP 3187
+#define F_PG_STAT_GET_ARCHIVER 3195
+#define F_JSON_OBJECT_AGG_FINALFN 3196
+#define F_JSON_OBJECT_AGG 3197
+#define F_JSON_BUILD_ARRAY_ANY 3198
+#define F_JSON_BUILD_ARRAY_ 3199
+#define F_JSON_BUILD_OBJECT_ANY 3200
+#define F_JSON_BUILD_OBJECT_ 3201
+#define F_JSON_OBJECT__TEXT 3202
+#define F_JSON_OBJECT__TEXT__TEXT 3203
+#define F_JSON_TO_RECORD 3204
+#define F_JSON_TO_RECORDSET 3205
+#define F_JSONB_ARRAY_LENGTH 3207
+#define F_JSONB_EACH 3208
+#define F_JSONB_POPULATE_RECORD 3209
+#define F_JSONB_TYPEOF 3210
+#define F_JSONB_OBJECT_FIELD_TEXT 3214
+#define F_JSONB_ARRAY_ELEMENT 3215
+#define F_JSONB_ARRAY_ELEMENT_TEXT 3216
+#define F_JSONB_EXTRACT_PATH 3217
+#define F_WIDTH_BUCKET_ANYCOMPATIBLE_ANYCOMPATIBLEARRAY 3218
+#define F_JSONB_ARRAY_ELEMENTS 3219
+#define F_PG_LSN_IN 3229
+#define F_PG_LSN_OUT 3230
+#define F_PG_LSN_LT 3231
+#define F_PG_LSN_LE 3232
+#define F_PG_LSN_EQ 3233
+#define F_PG_LSN_GE 3234
+#define F_PG_LSN_GT 3235
+#define F_PG_LSN_NE 3236
+#define F_PG_LSN_MI 3237
+#define F_PG_LSN_RECV 3238
+#define F_PG_LSN_SEND 3239
+#define F_PG_LSN_CMP 3251
+#define F_PG_LSN_HASH 3252
+#define F_BTTEXTSORTSUPPORT 3255
+#define F_GENERATE_SERIES_NUMERIC_NUMERIC_NUMERIC 3259
+#define F_GENERATE_SERIES_NUMERIC_NUMERIC 3260
+#define F_JSON_STRIP_NULLS 3261
+#define F_JSONB_STRIP_NULLS 3262
+#define F_JSONB_OBJECT__TEXT 3263
+#define F_JSONB_OBJECT__TEXT__TEXT 3264
+#define F_JSONB_AGG_TRANSFN 3265
+#define F_JSONB_AGG_FINALFN 3266
+#define F_JSONB_AGG 3267
+#define F_JSONB_OBJECT_AGG_TRANSFN 3268
+#define F_JSONB_OBJECT_AGG_FINALFN 3269
+#define F_JSONB_OBJECT_AGG 3270
+#define F_JSONB_BUILD_ARRAY_ANY 3271
+#define F_JSONB_BUILD_ARRAY_ 3272
+#define F_JSONB_BUILD_OBJECT_ANY 3273
+#define F_JSONB_BUILD_OBJECT_ 3274
+#define F_DIST_PPOLY 3275
+#define F_ARRAY_POSITION_ANYCOMPATIBLEARRAY_ANYCOMPATIBLE 3277
+#define F_ARRAY_POSITION_ANYCOMPATIBLEARRAY_ANYCOMPATIBLE_INT4 3278
+#define F_ARRAY_POSITIONS 3279
+#define F_GIST_CIRCLE_DISTANCE 3280
+#define F_SCALE 3281
+#define F_GIST_POINT_FETCH 3282
+#define F_NUMERIC_SORTSUPPORT 3283
+#define F_GIST_POLY_DISTANCE 3288
+#define F_DIST_CPOINT 3290
+#define F_DIST_POLYP 3292
+#define F_PG_READ_FILE_TEXT_INT8_INT8_BOOL 3293
+#define F_CURRENT_SETTING_TEXT_BOOL 3294
+#define F_PG_READ_BINARY_FILE_TEXT_INT8_INT8_BOOL 3295
+#define F_PG_NOTIFICATION_QUEUE_USAGE 3296
+#define F_PG_LS_DIR_TEXT_BOOL_BOOL 3297
+#define F_ROW_SECURITY_ACTIVE_OID 3298
+#define F_ROW_SECURITY_ACTIVE_TEXT 3299
+#define F_UUID_SORTSUPPORT 3300
+#define F_JSONB_CONCAT 3301
+#define F_JSONB_DELETE_JSONB_TEXT 3302
+#define F_JSONB_DELETE_JSONB_INT4 3303
+#define F_JSONB_DELETE_PATH 3304
+#define F_JSONB_SET 3305
+#define F_JSONB_PRETTY 3306
+#define F_PG_STAT_FILE_TEXT_BOOL 3307
+#define F_XIDNEQ 3308
+#define F_XIDNEQINT4 3309
+#define F_TSM_HANDLER_IN 3311
+#define F_TSM_HANDLER_OUT 3312
+#define F_BERNOULLI 3313
+#define F_SYSTEM 3314
+#define F_PG_STAT_GET_WAL_RECEIVER 3317
+#define F_PG_STAT_GET_PROGRESS_INFO 3318
+#define F_TS_FILTER 3319
+#define F_SETWEIGHT_TSVECTOR_CHAR__TEXT 3320
+#define F_TS_DELETE_TSVECTOR_TEXT 3321
+#define F_UNNEST_TSVECTOR 3322
+#define F_TS_DELETE_TSVECTOR__TEXT 3323
+#define F_INT4_AVG_COMBINE 3324
+#define F_INTERVAL_COMBINE 3325
+#define F_TSVECTOR_TO_ARRAY 3326
+#define F_ARRAY_TO_TSVECTOR 3327
+#define F_BPCHAR_SORTSUPPORT 3328
+#define F_PG_SHOW_ALL_FILE_SETTINGS 3329
+#define F_PG_CURRENT_WAL_FLUSH_LSN 3330
+#define F_BYTEA_SORTSUPPORT 3331
+#define F_BTTEXT_PATTERN_SORTSUPPORT 3332
+#define F_BTBPCHAR_PATTERN_SORTSUPPORT 3333
+#define F_PG_SIZE_BYTES 3334
+#define F_NUMERIC_SERIALIZE 3335
+#define F_NUMERIC_DESERIALIZE 3336
+#define F_NUMERIC_AVG_COMBINE 3337
+#define F_NUMERIC_POLY_COMBINE 3338
+#define F_NUMERIC_POLY_SERIALIZE 3339
+#define F_NUMERIC_POLY_DESERIALIZE 3340
+#define F_NUMERIC_COMBINE 3341
+#define F_FLOAT8_REGR_COMBINE 3342
+#define F_JSONB_DELETE_JSONB__TEXT 3343
+#define F_CASH_MUL_INT8 3344
+#define F_CASH_DIV_INT8 3345
+#define F_TXID_CURRENT_IF_ASSIGNED 3348
+#define F_PG_GET_PARTKEYDEF 3352
+#define F_PG_LS_LOGDIR 3353
+#define F_PG_LS_WALDIR 3354
+#define F_PG_NDISTINCT_IN 3355
+#define F_PG_NDISTINCT_OUT 3356
+#define F_PG_NDISTINCT_RECV 3357
+#define F_PG_NDISTINCT_SEND 3358
+#define F_MACADDR_SORTSUPPORT 3359
+#define F_TXID_STATUS 3360
+#define F_PG_SAFE_SNAPSHOT_BLOCKING_PIDS 3376
+#define F_PG_ISOLATION_TEST_SESSION_IS_BLOCKED 3378
+#define F_PG_IDENTIFY_OBJECT_AS_ADDRESS 3382
+#define F_BRIN_MINMAX_OPCINFO 3383
+#define F_BRIN_MINMAX_ADD_VALUE 3384
+#define F_BRIN_MINMAX_CONSISTENT 3385
+#define F_BRIN_MINMAX_UNION 3386
+#define F_INT8_AVG_ACCUM_INV 3387
+#define F_NUMERIC_POLY_SUM 3388
+#define F_NUMERIC_POLY_AVG 3389
+#define F_NUMERIC_POLY_VAR_POP 3390
+#define F_NUMERIC_POLY_VAR_SAMP 3391
+#define F_NUMERIC_POLY_STDDEV_POP 3392
+#define F_NUMERIC_POLY_STDDEV_SAMP 3393
+#define F_REGEXP_MATCH_TEXT_TEXT 3396
+#define F_REGEXP_MATCH_TEXT_TEXT_TEXT 3397
+#define F_INT8_MUL_CASH 3399
+#define F_PG_CONFIG 3400
+#define F_PG_HBA_FILE_RULES 3401
+#define F_PG_STATISTICS_OBJ_IS_VISIBLE 3403
+#define F_PG_DEPENDENCIES_IN 3404
+#define F_PG_DEPENDENCIES_OUT 3405
+#define F_PG_DEPENDENCIES_RECV 3406
+#define F_PG_DEPENDENCIES_SEND 3407
+#define F_PG_GET_PARTITION_CONSTRAINTDEF 3408
+#define F_TIME_HASH_EXTENDED 3409
+#define F_TIMETZ_HASH_EXTENDED 3410
+#define F_TIMESTAMP_HASH_EXTENDED 3411
+#define F_UUID_HASH_EXTENDED 3412
+#define F_PG_LSN_HASH_EXTENDED 3413
+#define F_HASHENUMEXTENDED 3414
+#define F_PG_GET_STATISTICSOBJDEF 3415
+#define F_JSONB_HASH_EXTENDED 3416
+#define F_HASH_RANGE_EXTENDED 3417
+#define F_INTERVAL_HASH_EXTENDED 3418
+#define F_SHA224 3419
+#define F_SHA256 3420
+#define F_SHA384 3421
+#define F_SHA512 3422
+#define F_PG_PARTITION_TREE 3423
+#define F_PG_PARTITION_ROOT 3424
+#define F_PG_PARTITION_ANCESTORS 3425
+#define F_PG_STAT_GET_DB_CHECKSUM_FAILURES 3426
+#define F_PG_MCV_LIST_ITEMS 3427
+#define F_PG_STAT_GET_DB_CHECKSUM_LAST_FAILURE 3428
+#define F_GEN_RANDOM_UUID 3432
+#define F_GTSVECTOR_OPTIONS 3434
+#define F_GIST_POINT_SORTSUPPORT 3435
+#define F_PG_PROMOTE 3436
+#define F_PREFIXSEL 3437
+#define F_PREFIXJOINSEL 3438
+#define F_PG_CONTROL_SYSTEM 3441
+#define F_PG_CONTROL_CHECKPOINT 3442
+#define F_PG_CONTROL_RECOVERY 3443
+#define F_PG_CONTROL_INIT 3444
+#define F_PG_IMPORT_SYSTEM_COLLATIONS 3445
+#define F_MACADDR8_RECV 3446
+#define F_MACADDR8_SEND 3447
+#define F_PG_COLLATION_ACTUAL_VERSION 3448
+#define F_NUMERIC_JSONB 3449
+#define F_INT2_JSONB 3450
+#define F_INT4_JSONB 3451
+#define F_INT8_JSONB 3452
+#define F_FLOAT4_JSONB 3453
+#define F_PG_FILENODE_RELATION 3454
+#define F_LO_FROM_BYTEA 3457
+#define F_LO_GET_OID 3458
+#define F_LO_GET_OID_INT8_INT4 3459
+#define F_LO_PUT 3460
+#define F_MAKE_TIMESTAMP 3461
+#define F_MAKE_TIMESTAMPTZ_INT4_INT4_INT4_INT4_INT4_FLOAT8 3462
+#define F_MAKE_TIMESTAMPTZ_INT4_INT4_INT4_INT4_INT4_FLOAT8_TEXT 3463
+#define F_MAKE_INTERVAL 3464
+#define F_JSONB_ARRAY_ELEMENTS_TEXT 3465
+#define F_SPG_RANGE_QUAD_CONFIG 3469
+#define F_SPG_RANGE_QUAD_CHOOSE 3470
+#define F_SPG_RANGE_QUAD_PICKSPLIT 3471
+#define F_SPG_RANGE_QUAD_INNER_CONSISTENT 3472
+#define F_SPG_RANGE_QUAD_LEAF_CONSISTENT 3473
+#define F_JSONB_POPULATE_RECORDSET 3475
+#define F_TO_REGOPERATOR 3476
+#define F_JSONB_OBJECT_FIELD 3478
+#define F_TO_REGPROCEDURE 3479
+#define F_GIN_COMPARE_JSONB 3480
+#define F_GIN_EXTRACT_JSONB 3482
+#define F_GIN_EXTRACT_JSONB_QUERY 3483
+#define F_GIN_CONSISTENT_JSONB 3484
+#define F_GIN_EXTRACT_JSONB_PATH 3485
+#define F_GIN_EXTRACT_JSONB_QUERY_PATH 3486
+#define F_GIN_CONSISTENT_JSONB_PATH 3487
+#define F_GIN_TRICONSISTENT_JSONB 3488
+#define F_GIN_TRICONSISTENT_JSONB_PATH 3489
+#define F_JSONB_TO_RECORD 3490
+#define F_JSONB_TO_RECORDSET 3491
+#define F_TO_REGOPER 3492
+#define F_TO_REGTYPE 3493
+#define F_TO_REGPROC 3494
+#define F_TO_REGCLASS 3495
+#define F_BOOL_ACCUM 3496
+#define F_BOOL_ACCUM_INV 3497
+#define F_BOOL_ALLTRUE 3498
+#define F_BOOL_ANYTRUE 3499
+#define F_ANYENUM_IN 3504
+#define F_ANYENUM_OUT 3505
+#define F_ENUM_IN 3506
+#define F_ENUM_OUT 3507
+#define F_ENUM_EQ 3508
+#define F_ENUM_NE 3509
+#define F_ENUM_LT 3510
+#define F_ENUM_GT 3511
+#define F_ENUM_LE 3512
+#define F_ENUM_GE 3513
+#define F_ENUM_CMP 3514
+#define F_HASHENUM 3515
+#define F_ENUM_SMALLER 3524
+#define F_ENUM_LARGER 3525
+#define F_MAX_ANYENUM 3526
+#define F_MIN_ANYENUM 3527
+#define F_ENUM_FIRST 3528
+#define F_ENUM_LAST 3529
+#define F_ENUM_RANGE_ANYENUM_ANYENUM 3530
+#define F_ENUM_RANGE_ANYENUM 3531
+#define F_ENUM_RECV 3532
+#define F_ENUM_SEND 3533
+#define F_STRING_AGG_TRANSFN 3535
+#define F_STRING_AGG_FINALFN 3536
+#define F_PG_DESCRIBE_OBJECT 3537
+#define F_STRING_AGG_TEXT_TEXT 3538
+#define F_FORMAT_TEXT_ANY 3539
+#define F_FORMAT_TEXT 3540
+#define F_BYTEA_STRING_AGG_TRANSFN 3543
+#define F_BYTEA_STRING_AGG_FINALFN 3544
+#define F_STRING_AGG_BYTEA_BYTEA 3545
+#define F_INT8DEC 3546
+#define F_INT8DEC_ANY 3547
+#define F_NUMERIC_ACCUM_INV 3548
+#define F_INTERVAL_ACCUM_INV 3549
+#define F_NETWORK_OVERLAP 3551
+#define F_INET_GIST_CONSISTENT 3553
+#define F_INET_GIST_UNION 3554
+#define F_INET_GIST_COMPRESS 3555
+#define F_BOOL_JSONB 3556
+#define F_INET_GIST_PENALTY 3557
+#define F_INET_GIST_PICKSPLIT 3558
+#define F_INET_GIST_SAME 3559
+#define F_NETWORKSEL 3560
+#define F_NETWORKJOINSEL 3561
+#define F_NETWORK_LARGER 3562
+#define F_NETWORK_SMALLER 3563
+#define F_MAX_INET 3564
+#define F_MIN_INET 3565
+#define F_PG_EVENT_TRIGGER_DROPPED_OBJECTS 3566
+#define F_INT2_ACCUM_INV 3567
+#define F_INT4_ACCUM_INV 3568
+#define F_INT8_ACCUM_INV 3569
+#define F_INT2_AVG_ACCUM_INV 3570
+#define F_INT4_AVG_ACCUM_INV 3571
+#define F_INT2INT4_SUM 3572
+#define F_INET_GIST_FETCH 3573
+#define F_PG_LOGICAL_EMIT_MESSAGE_BOOL_TEXT_TEXT 3577
+#define F_PG_LOGICAL_EMIT_MESSAGE_BOOL_TEXT_BYTEA 3578
+#define F_JSONB_INSERT 3579
+#define F_PG_XACT_COMMIT_TIMESTAMP 3581
+#define F_BINARY_UPGRADE_SET_NEXT_PG_TYPE_OID 3582
+#define F_PG_LAST_COMMITTED_XACT 3583
+#define F_BINARY_UPGRADE_SET_NEXT_ARRAY_PG_TYPE_OID 3584
+#define F_BINARY_UPGRADE_SET_NEXT_HEAP_PG_CLASS_OID 3586
+#define F_BINARY_UPGRADE_SET_NEXT_INDEX_PG_CLASS_OID 3587
+#define F_BINARY_UPGRADE_SET_NEXT_TOAST_PG_CLASS_OID 3588
+#define F_BINARY_UPGRADE_SET_NEXT_PG_ENUM_OID 3589
+#define F_BINARY_UPGRADE_SET_NEXT_PG_AUTHID_OID 3590
+#define F_BINARY_UPGRADE_CREATE_EMPTY_EXTENSION 3591
+#define F_EVENT_TRIGGER_IN 3594
+#define F_EVENT_TRIGGER_OUT 3595
+#define F_TSVECTORIN 3610
+#define F_TSVECTOROUT 3611
+#define F_TSQUERYIN 3612
+#define F_TSQUERYOUT 3613
+#define F_TSVECTOR_LT 3616
+#define F_TSVECTOR_LE 3617
+#define F_TSVECTOR_EQ 3618
+#define F_TSVECTOR_NE 3619
+#define F_TSVECTOR_GE 3620
+#define F_TSVECTOR_GT 3621
+#define F_TSVECTOR_CMP 3622
+#define F_STRIP 3623
+#define F_SETWEIGHT_TSVECTOR_CHAR 3624
+#define F_TSVECTOR_CONCAT 3625
+#define F_TS_MATCH_VQ 3634
+#define F_TS_MATCH_QV 3635
+#define F_TSVECTORSEND 3638
+#define F_TSVECTORRECV 3639
+#define F_TSQUERYSEND 3640
+#define F_TSQUERYRECV 3641
+#define F_GTSVECTORIN 3646
+#define F_GTSVECTOROUT 3647
+#define F_GTSVECTOR_COMPRESS 3648
+#define F_GTSVECTOR_DECOMPRESS 3649
+#define F_GTSVECTOR_PICKSPLIT 3650
+#define F_GTSVECTOR_UNION 3651
+#define F_GTSVECTOR_SAME 3652
+#define F_GTSVECTOR_PENALTY 3653
+#define F_GTSVECTOR_CONSISTENT_INTERNAL_TSVECTOR_INT2_OID_INTERNAL 3654
+#define F_GIN_EXTRACT_TSVECTOR_TSVECTOR_INTERNAL_INTERNAL 3656
+#define F_GIN_EXTRACT_TSQUERY_TSVECTOR_INTERNAL_INT2_INTERNAL_INTERNAL_INTERNAL_INTERNAL 3657
+#define F_GIN_TSQUERY_CONSISTENT_INTERNAL_INT2_TSVECTOR_INT4_INTERNAL_INTERNAL_INTERNAL_INTERNAL 3658
+#define F_TSQUERY_LT 3662
+#define F_TSQUERY_LE 3663
+#define F_TSQUERY_EQ 3664
+#define F_TSQUERY_NE 3665
+#define F_TSQUERY_GE 3666
+#define F_TSQUERY_GT 3667
+#define F_TSQUERY_CMP 3668
+#define F_TSQUERY_AND 3669
+#define F_TSQUERY_OR 3670
+#define F_TSQUERY_NOT 3671
+#define F_NUMNODE 3672
+#define F_QUERYTREE 3673
+#define F_TS_REWRITE_TSQUERY_TSQUERY_TSQUERY 3684
+#define F_TS_REWRITE_TSQUERY_TEXT 3685
+#define F_TSMATCHSEL 3686
+#define F_TSMATCHJOINSEL 3687
+#define F_TS_TYPANALYZE 3688
+#define F_TS_STAT_TEXT 3689
+#define F_TS_STAT_TEXT_TEXT 3690
+#define F_TSQ_MCONTAINS 3691
+#define F_TSQ_MCONTAINED 3692
+#define F_GTSQUERY_COMPRESS 3695
+#define F_STARTS_WITH 3696
+#define F_GTSQUERY_PICKSPLIT 3697
+#define F_GTSQUERY_UNION 3698
+#define F_GTSQUERY_SAME 3699
+#define F_GTSQUERY_PENALTY 3700
+#define F_GTSQUERY_CONSISTENT_INTERNAL_TSQUERY_INT2_OID_INTERNAL 3701
+#define F_TS_RANK__FLOAT4_TSVECTOR_TSQUERY_INT4 3703
+#define F_TS_RANK__FLOAT4_TSVECTOR_TSQUERY 3704
+#define F_TS_RANK_TSVECTOR_TSQUERY_INT4 3705
+#define F_TS_RANK_TSVECTOR_TSQUERY 3706
+#define F_TS_RANK_CD__FLOAT4_TSVECTOR_TSQUERY_INT4 3707
+#define F_TS_RANK_CD__FLOAT4_TSVECTOR_TSQUERY 3708
+#define F_TS_RANK_CD_TSVECTOR_TSQUERY_INT4 3709
+#define F_TS_RANK_CD_TSVECTOR_TSQUERY 3710
+#define F_LENGTH_TSVECTOR 3711
+#define F_TS_TOKEN_TYPE_OID 3713
+#define F_TS_TOKEN_TYPE_TEXT 3714
+#define F_TS_PARSE_OID_TEXT 3715
+#define F_TS_PARSE_TEXT_TEXT 3716
+#define F_PRSD_START 3717
+#define F_PRSD_NEXTTOKEN 3718
+#define F_PRSD_END 3719
+#define F_PRSD_HEADLINE 3720
+#define F_PRSD_LEXTYPE 3721
+#define F_TS_LEXIZE 3723
+#define F_GIN_CMP_TSLEXEME 3724
+#define F_DSIMPLE_INIT 3725
+#define F_DSIMPLE_LEXIZE 3726
+#define F_DSYNONYM_INIT 3728
+#define F_DSYNONYM_LEXIZE 3729
+#define F_DISPELL_INIT 3731
+#define F_DISPELL_LEXIZE 3732
+#define F_REGCONFIGIN 3736
+#define F_REGCONFIGOUT 3737
+#define F_REGCONFIGRECV 3738
+#define F_REGCONFIGSEND 3739
+#define F_THESAURUS_INIT 3740
+#define F_THESAURUS_LEXIZE 3741
+#define F_TS_HEADLINE_REGCONFIG_TEXT_TSQUERY_TEXT 3743
+#define F_TS_HEADLINE_REGCONFIG_TEXT_TSQUERY 3744
+#define F_TO_TSVECTOR_REGCONFIG_TEXT 3745
+#define F_TO_TSQUERY_REGCONFIG_TEXT 3746
+#define F_PLAINTO_TSQUERY_REGCONFIG_TEXT 3747
+#define F_TO_TSVECTOR_TEXT 3749
+#define F_TO_TSQUERY_TEXT 3750
+#define F_PLAINTO_TSQUERY_TEXT 3751
+#define F_TSVECTOR_UPDATE_TRIGGER 3752
+#define F_TSVECTOR_UPDATE_TRIGGER_COLUMN 3753
+#define F_TS_HEADLINE_TEXT_TSQUERY_TEXT 3754
+#define F_TS_HEADLINE_TEXT_TSQUERY 3755
+#define F_PG_TS_PARSER_IS_VISIBLE 3756
+#define F_PG_TS_DICT_IS_VISIBLE 3757
+#define F_PG_TS_CONFIG_IS_VISIBLE 3758
+#define F_GET_CURRENT_TS_CONFIG 3759
+#define F_TS_MATCH_TT 3760
+#define F_TS_MATCH_TQ 3761
+#define F_PG_TS_TEMPLATE_IS_VISIBLE 3768
+#define F_REGDICTIONARYIN 3771
+#define F_REGDICTIONARYOUT 3772
+#define F_REGDICTIONARYRECV 3773
+#define F_REGDICTIONARYSEND 3774
+#define F_PG_STAT_RESET_SHARED 3775
+#define F_PG_STAT_RESET_SINGLE_TABLE_COUNTERS 3776
+#define F_PG_STAT_RESET_SINGLE_FUNCTION_COUNTERS 3777
+#define F_PG_TABLESPACE_LOCATION 3778
+#define F_PG_CREATE_PHYSICAL_REPLICATION_SLOT 3779
+#define F_PG_DROP_REPLICATION_SLOT 3780
+#define F_PG_GET_REPLICATION_SLOTS 3781
+#define F_PG_LOGICAL_SLOT_GET_CHANGES 3782
+#define F_PG_LOGICAL_SLOT_GET_BINARY_CHANGES 3783
+#define F_PG_LOGICAL_SLOT_PEEK_CHANGES 3784
+#define F_PG_LOGICAL_SLOT_PEEK_BINARY_CHANGES 3785
+#define F_PG_CREATE_LOGICAL_REPLICATION_SLOT 3786
+#define F_TO_JSONB 3787
+#define F_PG_STAT_GET_SNAPSHOT_TIMESTAMP 3788
+#define F_GIN_CLEAN_PENDING_LIST 3789
+#define F_GTSVECTOR_CONSISTENT_INTERNAL_GTSVECTOR_INT4_OID_INTERNAL 3790
+#define F_GIN_EXTRACT_TSQUERY_TSQUERY_INTERNAL_INT2_INTERNAL_INTERNAL_INTERNAL_INTERNAL 3791
+#define F_GIN_TSQUERY_CONSISTENT_INTERNAL_INT2_TSQUERY_INT4_INTERNAL_INTERNAL_INTERNAL_INTERNAL 3792
+#define F_GTSQUERY_CONSISTENT_INTERNAL_INTERNAL_INT4_OID_INTERNAL 3793
+#define F_INET_SPG_CONFIG 3795
+#define F_INET_SPG_CHOOSE 3796
+#define F_INET_SPG_PICKSPLIT 3797
+#define F_INET_SPG_INNER_CONSISTENT 3798
+#define F_INET_SPG_LEAF_CONSISTENT 3799
+#define F_PG_CURRENT_LOGFILE_ 3800
+#define F_PG_CURRENT_LOGFILE_TEXT 3801
+#define F_JSONB_SEND 3803
+#define F_JSONB_OUT 3804
+#define F_JSONB_RECV 3805
+#define F_JSONB_IN 3806
+#define F_PG_GET_FUNCTION_ARG_DEFAULT 3808
+#define F_PG_EXPORT_SNAPSHOT 3809
+#define F_PG_IS_IN_RECOVERY 3810
+#define F_MONEY_INT4 3811
+#define F_MONEY_INT8 3812
+#define F_PG_COLLATION_IS_VISIBLE 3815
+#define F_ARRAY_TYPANALYZE 3816
+#define F_ARRAYCONTSEL 3817
+#define F_ARRAYCONTJOINSEL 3818
+#define F_PG_GET_MULTIXACT_MEMBERS 3819
+#define F_PG_LAST_WAL_RECEIVE_LSN 3820
+#define F_PG_LAST_WAL_REPLAY_LSN 3821
+#define F_CASH_DIV_CASH 3822
+#define F_NUMERIC_MONEY 3823
+#define F_MONEY_NUMERIC 3824
+#define F_PG_READ_FILE_TEXT 3826
+#define F_PG_READ_BINARY_FILE_TEXT_INT8_INT8 3827
+#define F_PG_READ_BINARY_FILE_TEXT 3828
+#define F_PG_OPFAMILY_IS_VISIBLE 3829
+#define F_PG_LAST_XACT_REPLAY_TIMESTAMP 3830
+#define F_ANYRANGE_IN 3832
+#define F_ANYRANGE_OUT 3833
+#define F_RANGE_IN 3834
+#define F_RANGE_OUT 3835
+#define F_RANGE_RECV 3836
+#define F_RANGE_SEND 3837
+#define F_PG_IDENTIFY_OBJECT 3839
+#define F_INT4RANGE_INT4_INT4 3840
+#define F_INT4RANGE_INT4_INT4_TEXT 3841
+#define F_PG_RELATION_IS_UPDATABLE 3842
+#define F_PG_COLUMN_IS_UPDATABLE 3843
+#define F_NUMRANGE_NUMERIC_NUMERIC 3844
+#define F_NUMRANGE_NUMERIC_NUMERIC_TEXT 3845
+#define F_MAKE_DATE 3846
+#define F_MAKE_TIME 3847
+#define F_LOWER_ANYRANGE 3848
+#define F_UPPER_ANYRANGE 3849
+#define F_ISEMPTY_ANYRANGE 3850
+#define F_LOWER_INC_ANYRANGE 3851
+#define F_UPPER_INC_ANYRANGE 3852
+#define F_LOWER_INF_ANYRANGE 3853
+#define F_UPPER_INF_ANYRANGE 3854
+#define F_RANGE_EQ 3855
+#define F_RANGE_NE 3856
+#define F_RANGE_OVERLAPS 3857
+#define F_RANGE_CONTAINS_ELEM 3858
+#define F_RANGE_CONTAINS 3859
+#define F_ELEM_CONTAINED_BY_RANGE 3860
+#define F_RANGE_CONTAINED_BY 3861
+#define F_RANGE_ADJACENT 3862
+#define F_RANGE_BEFORE 3863
+#define F_RANGE_AFTER 3864
+#define F_RANGE_OVERLEFT 3865
+#define F_RANGE_OVERRIGHT 3866
+#define F_RANGE_UNION 3867
+#define F_RANGE_INTERSECT 3868
+#define F_RANGE_MINUS 3869
+#define F_RANGE_CMP 3870
+#define F_RANGE_LT 3871
+#define F_RANGE_LE 3872
+#define F_RANGE_GE 3873
+#define F_RANGE_GT 3874
+#define F_RANGE_GIST_CONSISTENT 3875
+#define F_RANGE_GIST_UNION 3876
+#define F_PG_REPLICATION_SLOT_ADVANCE 3878
+#define F_RANGE_GIST_PENALTY 3879
+#define F_RANGE_GIST_PICKSPLIT 3880
+#define F_RANGE_GIST_SAME 3881
+#define F_HASH_RANGE 3902
+#define F_INT4RANGE_CANONICAL 3914
+#define F_DATERANGE_CANONICAL 3915
+#define F_RANGE_TYPANALYZE 3916
+#define F_TIMESTAMP_SUPPORT 3917
+#define F_INTERVAL_SUPPORT 3918
+#define F_GINARRAYTRICONSISTENT 3920
+#define F_GIN_TSQUERY_TRICONSISTENT 3921
+#define F_INT4RANGE_SUBDIFF 3922
+#define F_INT8RANGE_SUBDIFF 3923
+#define F_NUMRANGE_SUBDIFF 3924
+#define F_DATERANGE_SUBDIFF 3925
+#define F_INT8RANGE_CANONICAL 3928
+#define F_TSRANGE_SUBDIFF 3929
+#define F_TSTZRANGE_SUBDIFF 3930
+#define F_JSONB_OBJECT_KEYS 3931
+#define F_JSONB_EACH_TEXT 3932
+#define F_TSRANGE_TIMESTAMP_TIMESTAMP 3933
+#define F_TSRANGE_TIMESTAMP_TIMESTAMP_TEXT 3934
+#define F_PG_SLEEP_FOR 3935
+#define F_PG_SLEEP_UNTIL 3936
+#define F_TSTZRANGE_TIMESTAMPTZ_TIMESTAMPTZ 3937
+#define F_TSTZRANGE_TIMESTAMPTZ_TIMESTAMPTZ_TEXT 3938
+#define F_MXID_AGE 3939
+#define F_JSONB_EXTRACT_PATH_TEXT 3940
+#define F_DATERANGE_DATE_DATE 3941
+#define F_DATERANGE_DATE_DATE_TEXT 3942
+#define F_ACLDEFAULT 3943
+#define F_TIME_SUPPORT 3944
+#define F_INT8RANGE_INT8_INT8 3945
+#define F_INT8RANGE_INT8_INT8_TEXT 3946
+#define F_JSON_OBJECT_FIELD 3947
+#define F_JSON_OBJECT_FIELD_TEXT 3948
+#define F_JSON_ARRAY_ELEMENT 3949
+#define F_JSON_ARRAY_ELEMENT_TEXT 3950
+#define F_JSON_EXTRACT_PATH 3951
+#define F_BRIN_SUMMARIZE_NEW_VALUES 3952
+#define F_JSON_EXTRACT_PATH_TEXT 3953
+#define F_PG_GET_OBJECT_ADDRESS 3954
+#define F_JSON_ARRAY_ELEMENTS 3955
+#define F_JSON_ARRAY_LENGTH 3956
+#define F_JSON_OBJECT_KEYS 3957
+#define F_JSON_EACH 3958
+#define F_JSON_EACH_TEXT 3959
+#define F_JSON_POPULATE_RECORD 3960
+#define F_JSON_POPULATE_RECORDSET 3961
+#define F_JSON_TYPEOF 3968
+#define F_JSON_ARRAY_ELEMENTS_TEXT 3969
+#define F_ORDERED_SET_TRANSITION 3970
+#define F_ORDERED_SET_TRANSITION_MULTI 3971
+#define F_PERCENTILE_DISC_FLOAT8_ANYELEMENT 3972
+#define F_PERCENTILE_DISC_FINAL 3973
+#define F_PERCENTILE_CONT_FLOAT8_FLOAT8 3974
+#define F_PERCENTILE_CONT_FLOAT8_FINAL 3975
+#define F_PERCENTILE_CONT_FLOAT8_INTERVAL 3976
+#define F_PERCENTILE_CONT_INTERVAL_FINAL 3977
+#define F_PERCENTILE_DISC__FLOAT8_ANYELEMENT 3978
+#define F_PERCENTILE_DISC_MULTI_FINAL 3979
+#define F_PERCENTILE_CONT__FLOAT8_FLOAT8 3980
+#define F_PERCENTILE_CONT_FLOAT8_MULTI_FINAL 3981
+#define F_PERCENTILE_CONT__FLOAT8_INTERVAL 3982
+#define F_PERCENTILE_CONT_INTERVAL_MULTI_FINAL 3983
+#define F_MODE 3984
+#define F_MODE_FINAL 3985
+#define F_RANK_ANY 3986
+#define F_RANK_FINAL 3987
+#define F_PERCENT_RANK_ANY 3988
+#define F_PERCENT_RANK_FINAL 3989
+#define F_CUME_DIST_ANY 3990
+#define F_CUME_DIST_FINAL 3991
+#define F_DENSE_RANK_ANY 3992
+#define F_DENSE_RANK_FINAL 3993
+#define F_GENERATE_SERIES_INT4_SUPPORT 3994
+#define F_GENERATE_SERIES_INT8_SUPPORT 3995
+#define F_ARRAY_UNNEST_SUPPORT 3996
+#define F_GIST_BOX_DISTANCE 3998
+#define F_BRIN_SUMMARIZE_RANGE 3999
+#define F_JSONPATH_IN 4001
+#define F_JSONPATH_RECV 4002
+#define F_JSONPATH_OUT 4003
+#define F_JSONPATH_SEND 4004
+#define F_JSONB_PATH_EXISTS 4005
+#define F_JSONB_PATH_QUERY 4006
+#define F_JSONB_PATH_QUERY_ARRAY 4007
+#define F_JSONB_PATH_QUERY_FIRST 4008
+#define F_JSONB_PATH_MATCH 4009
+#define F_JSONB_PATH_EXISTS_OPR 4010
+#define F_JSONB_PATH_MATCH_OPR 4011
+#define F_BRIN_DESUMMARIZE_RANGE 4014
+#define F_SPG_QUAD_CONFIG 4018
+#define F_SPG_QUAD_CHOOSE 4019
+#define F_SPG_QUAD_PICKSPLIT 4020
+#define F_SPG_QUAD_INNER_CONSISTENT 4021
+#define F_SPG_QUAD_LEAF_CONSISTENT 4022
+#define F_SPG_KD_CONFIG 4023
+#define F_SPG_KD_CHOOSE 4024
+#define F_SPG_KD_PICKSPLIT 4025
+#define F_SPG_KD_INNER_CONSISTENT 4026
+#define F_SPG_TEXT_CONFIG 4027
+#define F_SPG_TEXT_CHOOSE 4028
+#define F_SPG_TEXT_PICKSPLIT 4029
+#define F_SPG_TEXT_INNER_CONSISTENT 4030
+#define F_SPG_TEXT_LEAF_CONSISTENT 4031
+#define F_PG_SEQUENCE_LAST_VALUE 4032
+#define F_JSONB_NE 4038
+#define F_JSONB_LT 4039
+#define F_JSONB_GT 4040
+#define F_JSONB_LE 4041
+#define F_JSONB_GE 4042
+#define F_JSONB_EQ 4043
+#define F_JSONB_CMP 4044
+#define F_JSONB_HASH 4045
+#define F_JSONB_CONTAINS 4046
+#define F_JSONB_EXISTS 4047
+#define F_JSONB_EXISTS_ANY 4048
+#define F_JSONB_EXISTS_ALL 4049
+#define F_JSONB_CONTAINED 4050
+#define F_ARRAY_AGG_ARRAY_TRANSFN 4051
+#define F_ARRAY_AGG_ARRAY_FINALFN 4052
+#define F_ARRAY_AGG_ANYARRAY 4053
+#define F_RANGE_MERGE_ANYRANGE_ANYRANGE 4057
+#define F_INET_MERGE 4063
+#define F_BOUND_BOX 4067
+#define F_INET_SAME_FAMILY 4071
+#define F_BINARY_UPGRADE_SET_RECORD_INIT_PRIVS 4083
+#define F_REGNAMESPACEIN 4084
+#define F_REGNAMESPACEOUT 4085
+#define F_TO_REGNAMESPACE 4086
+#define F_REGNAMESPACERECV 4087
+#define F_REGNAMESPACESEND 4088
+#define F_BOX_POINT 4091
+#define F_REGROLEOUT 4092
+#define F_TO_REGROLE 4093
+#define F_REGROLERECV 4094
+#define F_REGROLESEND 4095
+#define F_REGROLEIN 4098
+#define F_PG_ROTATE_LOGFILE_OLD 4099
+#define F_PG_READ_FILE_OLD 4100
+#define F_BINARY_UPGRADE_SET_MISSING_VALUE 4101
+#define F_BRIN_INCLUSION_OPCINFO 4105
+#define F_BRIN_INCLUSION_ADD_VALUE 4106
+#define F_BRIN_INCLUSION_CONSISTENT 4107
+#define F_BRIN_INCLUSION_UNION 4108
+#define F_MACADDR8_IN 4110
+#define F_MACADDR8_OUT 4111
+#define F_TRUNC_MACADDR8 4112
+#define F_MACADDR8_EQ 4113
+#define F_MACADDR8_LT 4114
+#define F_MACADDR8_LE 4115
+#define F_MACADDR8_GT 4116
+#define F_MACADDR8_GE 4117
+#define F_MACADDR8_NE 4118
+#define F_MACADDR8_CMP 4119
+#define F_MACADDR8_NOT 4120
+#define F_MACADDR8_AND 4121
+#define F_MACADDR8_OR 4122
+#define F_MACADDR8 4123
+#define F_MACADDR 4124
+#define F_MACADDR8_SET7BIT 4125
+#define F_IN_RANGE_INT8_INT8_INT8_BOOL_BOOL 4126
+#define F_IN_RANGE_INT4_INT4_INT8_BOOL_BOOL 4127
+#define F_IN_RANGE_INT4_INT4_INT4_BOOL_BOOL 4128
+#define F_IN_RANGE_INT4_INT4_INT2_BOOL_BOOL 4129
+#define F_IN_RANGE_INT2_INT2_INT8_BOOL_BOOL 4130
+#define F_IN_RANGE_INT2_INT2_INT4_BOOL_BOOL 4131
+#define F_IN_RANGE_INT2_INT2_INT2_BOOL_BOOL 4132
+#define F_IN_RANGE_DATE_DATE_INTERVAL_BOOL_BOOL 4133
+#define F_IN_RANGE_TIMESTAMP_TIMESTAMP_INTERVAL_BOOL_BOOL 4134
+#define F_IN_RANGE_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL_BOOL_BOOL 4135
+#define F_IN_RANGE_INTERVAL_INTERVAL_INTERVAL_BOOL_BOOL 4136
+#define F_IN_RANGE_TIME_TIME_INTERVAL_BOOL_BOOL 4137
+#define F_IN_RANGE_TIMETZ_TIMETZ_INTERVAL_BOOL_BOOL 4138
+#define F_IN_RANGE_FLOAT8_FLOAT8_FLOAT8_BOOL_BOOL 4139
+#define F_IN_RANGE_FLOAT4_FLOAT4_FLOAT8_BOOL_BOOL 4140
+#define F_IN_RANGE_NUMERIC_NUMERIC_NUMERIC_BOOL_BOOL 4141
+#define F_PG_LSN_LARGER 4187
+#define F_PG_LSN_SMALLER 4188
+#define F_MAX_PG_LSN 4189
+#define F_MIN_PG_LSN 4190
+#define F_REGCOLLATIONIN 4193
+#define F_REGCOLLATIONOUT 4194
+#define F_TO_REGCOLLATION 4195
+#define F_REGCOLLATIONRECV 4196
+#define F_REGCOLLATIONSEND 4197
+#define F_TS_HEADLINE_REGCONFIG_JSONB_TSQUERY_TEXT 4201
+#define F_TS_HEADLINE_REGCONFIG_JSONB_TSQUERY 4202
+#define F_TS_HEADLINE_JSONB_TSQUERY_TEXT 4203
+#define F_TS_HEADLINE_JSONB_TSQUERY 4204
+#define F_TS_HEADLINE_REGCONFIG_JSON_TSQUERY_TEXT 4205
+#define F_TS_HEADLINE_REGCONFIG_JSON_TSQUERY 4206
+#define F_TS_HEADLINE_JSON_TSQUERY_TEXT 4207
+#define F_TS_HEADLINE_JSON_TSQUERY 4208
+#define F_TO_TSVECTOR_JSONB 4209
+#define F_TO_TSVECTOR_JSON 4210
+#define F_TO_TSVECTOR_REGCONFIG_JSONB 4211
+#define F_TO_TSVECTOR_REGCONFIG_JSON 4212
+#define F_JSONB_TO_TSVECTOR_JSONB_JSONB 4213
+#define F_JSONB_TO_TSVECTOR_REGCONFIG_JSONB_JSONB 4214
+#define F_JSON_TO_TSVECTOR_JSON_JSONB 4215
+#define F_JSON_TO_TSVECTOR_REGCONFIG_JSON_JSONB 4216
+#define F_PG_COPY_PHYSICAL_REPLICATION_SLOT_NAME_NAME_BOOL 4220
+#define F_PG_COPY_PHYSICAL_REPLICATION_SLOT_NAME_NAME 4221
+#define F_PG_COPY_LOGICAL_REPLICATION_SLOT_NAME_NAME_BOOL_NAME 4222
+#define F_PG_COPY_LOGICAL_REPLICATION_SLOT_NAME_NAME_BOOL 4223
+#define F_PG_COPY_LOGICAL_REPLICATION_SLOT_NAME_NAME 4224
+#define F_ANYCOMPATIBLEMULTIRANGE_IN 4226
+#define F_ANYCOMPATIBLEMULTIRANGE_OUT 4227
+#define F_RANGE_MERGE_ANYMULTIRANGE 4228
+#define F_ANYMULTIRANGE_IN 4229
+#define F_ANYMULTIRANGE_OUT 4230
+#define F_MULTIRANGE_IN 4231
+#define F_MULTIRANGE_OUT 4232
+#define F_MULTIRANGE_RECV 4233
+#define F_MULTIRANGE_SEND 4234
+#define F_LOWER_ANYMULTIRANGE 4235
+#define F_UPPER_ANYMULTIRANGE 4236
+#define F_ISEMPTY_ANYMULTIRANGE 4237
+#define F_LOWER_INC_ANYMULTIRANGE 4238
+#define F_UPPER_INC_ANYMULTIRANGE 4239
+#define F_LOWER_INF_ANYMULTIRANGE 4240
+#define F_UPPER_INF_ANYMULTIRANGE 4241
+#define F_MULTIRANGE_TYPANALYZE 4242
+#define F_MULTIRANGESEL 4243
+#define F_MULTIRANGE_EQ 4244
+#define F_MULTIRANGE_NE 4245
+#define F_RANGE_OVERLAPS_MULTIRANGE 4246
+#define F_MULTIRANGE_OVERLAPS_RANGE 4247
+#define F_MULTIRANGE_OVERLAPS_MULTIRANGE 4248
+#define F_MULTIRANGE_CONTAINS_ELEM 4249
+#define F_MULTIRANGE_CONTAINS_RANGE 4250
+#define F_MULTIRANGE_CONTAINS_MULTIRANGE 4251
+#define F_ELEM_CONTAINED_BY_MULTIRANGE 4252
+#define F_RANGE_CONTAINED_BY_MULTIRANGE 4253
+#define F_MULTIRANGE_CONTAINED_BY_MULTIRANGE 4254
+#define F_RANGE_ADJACENT_MULTIRANGE 4255
+#define F_MULTIRANGE_ADJACENT_MULTIRANGE 4256
+#define F_MULTIRANGE_ADJACENT_RANGE 4257
+#define F_RANGE_BEFORE_MULTIRANGE 4258
+#define F_MULTIRANGE_BEFORE_RANGE 4259
+#define F_MULTIRANGE_BEFORE_MULTIRANGE 4260
+#define F_RANGE_AFTER_MULTIRANGE 4261
+#define F_MULTIRANGE_AFTER_RANGE 4262
+#define F_MULTIRANGE_AFTER_MULTIRANGE 4263
+#define F_RANGE_OVERLEFT_MULTIRANGE 4264
+#define F_MULTIRANGE_OVERLEFT_RANGE 4265
+#define F_MULTIRANGE_OVERLEFT_MULTIRANGE 4266
+#define F_RANGE_OVERRIGHT_MULTIRANGE 4267
+#define F_MULTIRANGE_OVERRIGHT_RANGE 4268
+#define F_MULTIRANGE_OVERRIGHT_MULTIRANGE 4269
+#define F_MULTIRANGE_UNION 4270
+#define F_MULTIRANGE_MINUS 4271
+#define F_MULTIRANGE_INTERSECT 4272
+#define F_MULTIRANGE_CMP 4273
+#define F_MULTIRANGE_LT 4274
+#define F_MULTIRANGE_LE 4275
+#define F_MULTIRANGE_GE 4276
+#define F_MULTIRANGE_GT 4277
+#define F_HASH_MULTIRANGE 4278
+#define F_HASH_MULTIRANGE_EXTENDED 4279
+#define F_INT4MULTIRANGE_ 4280
+#define F_INT4MULTIRANGE_INT4RANGE 4281
+#define F_INT4MULTIRANGE__INT4RANGE 4282
+#define F_NUMMULTIRANGE_ 4283
+#define F_NUMMULTIRANGE_NUMRANGE 4284
+#define F_NUMMULTIRANGE__NUMRANGE 4285
+#define F_TSMULTIRANGE_ 4286
+#define F_TSMULTIRANGE_TSRANGE 4287
+#define F_TSMULTIRANGE__TSRANGE 4288
+#define F_TSTZMULTIRANGE_ 4289
+#define F_TSTZMULTIRANGE_TSTZRANGE 4290
+#define F_TSTZMULTIRANGE__TSTZRANGE 4291
+#define F_DATEMULTIRANGE_ 4292
+#define F_DATEMULTIRANGE_DATERANGE 4293
+#define F_DATEMULTIRANGE__DATERANGE 4294
+#define F_INT8MULTIRANGE_ 4295
+#define F_INT8MULTIRANGE_INT8RANGE 4296
+#define F_INT8MULTIRANGE__INT8RANGE 4297
+#define F_MULTIRANGE 4298
+#define F_RANGE_AGG_TRANSFN 4299
+#define F_RANGE_AGG_FINALFN 4300
+#define F_RANGE_AGG_ANYRANGE 4301
+#define F_KOI8R_TO_MIC 4302
+#define F_MIC_TO_KOI8R 4303
+#define F_ISO_TO_MIC 4304
+#define F_MIC_TO_ISO 4305
+#define F_WIN1251_TO_MIC 4306
+#define F_MIC_TO_WIN1251 4307
+#define F_WIN866_TO_MIC 4308
+#define F_MIC_TO_WIN866 4309
+#define F_KOI8R_TO_WIN1251 4310
+#define F_WIN1251_TO_KOI8R 4311
+#define F_KOI8R_TO_WIN866 4312
+#define F_WIN866_TO_KOI8R 4313
+#define F_WIN866_TO_WIN1251 4314
+#define F_WIN1251_TO_WIN866 4315
+#define F_ISO_TO_KOI8R 4316
+#define F_KOI8R_TO_ISO 4317
+#define F_ISO_TO_WIN1251 4318
+#define F_WIN1251_TO_ISO 4319
+#define F_ISO_TO_WIN866 4320
+#define F_WIN866_TO_ISO 4321
+#define F_EUC_CN_TO_MIC 4322
+#define F_MIC_TO_EUC_CN 4323
+#define F_EUC_JP_TO_SJIS 4324
+#define F_SJIS_TO_EUC_JP 4325
+#define F_EUC_JP_TO_MIC 4326
+#define F_SJIS_TO_MIC 4327
+#define F_MIC_TO_EUC_JP 4328
+#define F_MIC_TO_SJIS 4329
+#define F_EUC_KR_TO_MIC 4330
+#define F_MIC_TO_EUC_KR 4331
+#define F_EUC_TW_TO_BIG5 4332
+#define F_BIG5_TO_EUC_TW 4333
+#define F_EUC_TW_TO_MIC 4334
+#define F_BIG5_TO_MIC 4335
+#define F_MIC_TO_EUC_TW 4336
+#define F_MIC_TO_BIG5 4337
+#define F_LATIN2_TO_MIC 4338
+#define F_MIC_TO_LATIN2 4339
+#define F_WIN1250_TO_MIC 4340
+#define F_MIC_TO_WIN1250 4341
+#define F_LATIN2_TO_WIN1250 4342
+#define F_WIN1250_TO_LATIN2 4343
+#define F_LATIN1_TO_MIC 4344
+#define F_MIC_TO_LATIN1 4345
+#define F_LATIN3_TO_MIC 4346
+#define F_MIC_TO_LATIN3 4347
+#define F_LATIN4_TO_MIC 4348
+#define F_MIC_TO_LATIN4 4349
+#define F_NORMALIZE 4350
+#define F_IS_NORMALIZED 4351
+#define F_BIG5_TO_UTF8 4352
+#define F_UTF8_TO_BIG5 4353
+#define F_UTF8_TO_KOI8R 4354
+#define F_KOI8R_TO_UTF8 4355
+#define F_UTF8_TO_KOI8U 4356
+#define F_KOI8U_TO_UTF8 4357
+#define F_UTF8_TO_WIN 4358
+#define F_WIN_TO_UTF8 4359
+#define F_EUC_CN_TO_UTF8 4360
+#define F_UTF8_TO_EUC_CN 4361
+#define F_EUC_JP_TO_UTF8 4362
+#define F_UTF8_TO_EUC_JP 4363
+#define F_EUC_KR_TO_UTF8 4364
+#define F_UTF8_TO_EUC_KR 4365
+#define F_EUC_TW_TO_UTF8 4366
+#define F_UTF8_TO_EUC_TW 4367
+#define F_GB18030_TO_UTF8 4368
+#define F_UTF8_TO_GB18030 4369
+#define F_GBK_TO_UTF8 4370
+#define F_UTF8_TO_GBK 4371
+#define F_UTF8_TO_ISO8859 4372
+#define F_ISO8859_TO_UTF8 4373
+#define F_ISO8859_1_TO_UTF8 4374
+#define F_UTF8_TO_ISO8859_1 4375
+#define F_JOHAB_TO_UTF8 4376
+#define F_UTF8_TO_JOHAB 4377
+#define F_SJIS_TO_UTF8 4378
+#define F_UTF8_TO_SJIS 4379
+#define F_UHC_TO_UTF8 4380
+#define F_UTF8_TO_UHC 4381
+#define F_EUC_JIS_2004_TO_UTF8 4382
+#define F_UTF8_TO_EUC_JIS_2004 4383
+#define F_SHIFT_JIS_2004_TO_UTF8 4384
+#define F_UTF8_TO_SHIFT_JIS_2004 4385
+#define F_EUC_JIS_2004_TO_SHIFT_JIS_2004 4386
+#define F_SHIFT_JIS_2004_TO_EUC_JIS_2004 4387
+#define F_MULTIRANGE_INTERSECT_AGG_TRANSFN 4388
+#define F_RANGE_INTERSECT_AGG_ANYMULTIRANGE 4389
+#define F_BINARY_UPGRADE_SET_NEXT_MULTIRANGE_PG_TYPE_OID 4390
+#define F_BINARY_UPGRADE_SET_NEXT_MULTIRANGE_ARRAY_PG_TYPE_OID 4391
+#define F_RANGE_INTERSECT_AGG_TRANSFN 4401
+#define F_RANGE_INTERSECT_AGG_ANYRANGE 4450
+#define F_RANGE_CONTAINS_MULTIRANGE 4541
+#define F_MULTIRANGE_CONTAINED_BY_RANGE 4542
+#define F_PG_LOG_BACKEND_MEMORY_CONTEXTS 4543
+#define F_BINARY_UPGRADE_SET_NEXT_HEAP_RELFILENODE 4545
+#define F_BINARY_UPGRADE_SET_NEXT_INDEX_RELFILENODE 4546
+#define F_BINARY_UPGRADE_SET_NEXT_TOAST_RELFILENODE 4547
+#define F_BINARY_UPGRADE_SET_NEXT_PG_TABLESPACE_OID 4548
+#define F_PG_EVENT_TRIGGER_TABLE_REWRITE_OID 4566
+#define F_PG_EVENT_TRIGGER_TABLE_REWRITE_REASON 4567
+#define F_PG_EVENT_TRIGGER_DDL_COMMANDS 4568
+#define F_BRIN_BLOOM_OPCINFO 4591
+#define F_BRIN_BLOOM_ADD_VALUE 4592
+#define F_BRIN_BLOOM_CONSISTENT 4593
+#define F_BRIN_BLOOM_UNION 4594
+#define F_BRIN_BLOOM_OPTIONS 4595
+#define F_BRIN_BLOOM_SUMMARY_IN 4596
+#define F_BRIN_BLOOM_SUMMARY_OUT 4597
+#define F_BRIN_BLOOM_SUMMARY_RECV 4598
+#define F_BRIN_BLOOM_SUMMARY_SEND 4599
+#define F_BRIN_MINMAX_MULTI_OPCINFO 4616
+#define F_BRIN_MINMAX_MULTI_ADD_VALUE 4617
+#define F_BRIN_MINMAX_MULTI_CONSISTENT 4618
+#define F_BRIN_MINMAX_MULTI_UNION 4619
+#define F_BRIN_MINMAX_MULTI_OPTIONS 4620
+#define F_BRIN_MINMAX_MULTI_DISTANCE_INT2 4621
+#define F_BRIN_MINMAX_MULTI_DISTANCE_INT4 4622
+#define F_BRIN_MINMAX_MULTI_DISTANCE_INT8 4623
+#define F_BRIN_MINMAX_MULTI_DISTANCE_FLOAT4 4624
+#define F_BRIN_MINMAX_MULTI_DISTANCE_FLOAT8 4625
+#define F_BRIN_MINMAX_MULTI_DISTANCE_NUMERIC 4626
+#define F_BRIN_MINMAX_MULTI_DISTANCE_TID 4627
+#define F_BRIN_MINMAX_MULTI_DISTANCE_UUID 4628
+#define F_BRIN_MINMAX_MULTI_DISTANCE_DATE 4629
+#define F_BRIN_MINMAX_MULTI_DISTANCE_TIME 4630
+#define F_BRIN_MINMAX_MULTI_DISTANCE_INTERVAL 4631
+#define F_BRIN_MINMAX_MULTI_DISTANCE_TIMETZ 4632
+#define F_BRIN_MINMAX_MULTI_DISTANCE_PG_LSN 4633
+#define F_BRIN_MINMAX_MULTI_DISTANCE_MACADDR 4634
+#define F_BRIN_MINMAX_MULTI_DISTANCE_MACADDR8 4635
+#define F_BRIN_MINMAX_MULTI_DISTANCE_INET 4636
+#define F_BRIN_MINMAX_MULTI_DISTANCE_TIMESTAMP 4637
+#define F_BRIN_MINMAX_MULTI_SUMMARY_IN 4638
+#define F_BRIN_MINMAX_MULTI_SUMMARY_OUT 4639
+#define F_BRIN_MINMAX_MULTI_SUMMARY_RECV 4640
+#define F_BRIN_MINMAX_MULTI_SUMMARY_SEND 4641
+#define F_PHRASETO_TSQUERY_TEXT 5001
+#define F_TSQUERY_PHRASE_TSQUERY_TSQUERY 5003
+#define F_TSQUERY_PHRASE_TSQUERY_TSQUERY_INT4 5004
+#define F_PHRASETO_TSQUERY_REGCONFIG_TEXT 5006
+#define F_WEBSEARCH_TO_TSQUERY_REGCONFIG_TEXT 5007
+#define F_WEBSEARCH_TO_TSQUERY_TEXT 5009
+#define F_SPG_BBOX_QUAD_CONFIG 5010
+#define F_SPG_POLY_QUAD_COMPRESS 5011
+#define F_SPG_BOX_QUAD_CONFIG 5012
+#define F_SPG_BOX_QUAD_CHOOSE 5013
+#define F_SPG_BOX_QUAD_PICKSPLIT 5014
+#define F_SPG_BOX_QUAD_INNER_CONSISTENT 5015
+#define F_SPG_BOX_QUAD_LEAF_CONSISTENT 5016
+#define F_PG_MCV_LIST_IN 5018
+#define F_PG_MCV_LIST_OUT 5019
+#define F_PG_MCV_LIST_RECV 5020
+#define F_PG_MCV_LIST_SEND 5021
+#define F_PG_LSN_PLI 5022
+#define F_NUMERIC_PL_PG_LSN 5023
+#define F_PG_LSN_MII 5024
+#define F_SATISFIES_HASH_PARTITION 5028
+#define F_PG_LS_TMPDIR_ 5029
+#define F_PG_LS_TMPDIR_OID 5030
+#define F_PG_LS_ARCHIVE_STATUSDIR 5031
+#define F_NETWORK_SORTSUPPORT 5033
+#define F_XID8LT 5034
+#define F_XID8GT 5035
+#define F_XID8LE 5036
+#define F_XID8GE 5037
+#define F_MATCHINGSEL 5040
+#define F_MATCHINGJOINSEL 5041
+#define F_MIN_SCALE 5042
+#define F_TRIM_SCALE 5043
+#define F_GCD_INT4_INT4 5044
+#define F_GCD_INT8_INT8 5045
+#define F_LCM_INT4_INT4 5046
+#define F_LCM_INT8_INT8 5047
+#define F_GCD_NUMERIC_NUMERIC 5048
+#define F_LCM_NUMERIC_NUMERIC 5049
+#define F_BTVARSTREQUALIMAGE 5050
+#define F_BTEQUALIMAGE 5051
+#define F_PG_GET_SHMEM_ALLOCATIONS 5052
+#define F_PG_STAT_GET_INS_SINCE_VACUUM 5053
+#define F_JSONB_SET_LAX 5054
+#define F_PG_SNAPSHOT_IN 5055
+#define F_PG_SNAPSHOT_OUT 5056
+#define F_PG_SNAPSHOT_RECV 5057
+#define F_PG_SNAPSHOT_SEND 5058
+#define F_PG_CURRENT_XACT_ID 5059
+#define F_PG_CURRENT_XACT_ID_IF_ASSIGNED 5060
+#define F_PG_CURRENT_SNAPSHOT 5061
+#define F_PG_SNAPSHOT_XMIN 5062
+#define F_PG_SNAPSHOT_XMAX 5063
+#define F_PG_SNAPSHOT_XIP 5064
+#define F_PG_VISIBLE_IN_SNAPSHOT 5065
+#define F_PG_XACT_STATUS 5066
+#define F_XID8IN 5070
+#define F_XID 5071
+#define F_XID8OUT 5081
+#define F_XID8RECV 5082
+#define F_XID8SEND 5083
+#define F_XID8EQ 5084
+#define F_XID8NE 5085
+#define F_ANYCOMPATIBLE_IN 5086
+#define F_ANYCOMPATIBLE_OUT 5087
+#define F_ANYCOMPATIBLEARRAY_IN 5088
+#define F_ANYCOMPATIBLEARRAY_OUT 5089
+#define F_ANYCOMPATIBLEARRAY_RECV 5090
+#define F_ANYCOMPATIBLEARRAY_SEND 5091
+#define F_ANYCOMPATIBLENONARRAY_IN 5092
+#define F_ANYCOMPATIBLENONARRAY_OUT 5093
+#define F_ANYCOMPATIBLERANGE_IN 5094
+#define F_ANYCOMPATIBLERANGE_OUT 5095
+#define F_XID8CMP 5096
+#define F_XID8_LARGER 5097
+#define F_XID8_SMALLER 5098
+#define F_MAX_XID8 5099
+#define F_MIN_XID8 5100
+#define F_PG_REPLICATION_ORIGIN_CREATE 6003
+#define F_PG_REPLICATION_ORIGIN_DROP 6004
+#define F_PG_REPLICATION_ORIGIN_OID 6005
+#define F_PG_REPLICATION_ORIGIN_SESSION_SETUP 6006
+#define F_PG_REPLICATION_ORIGIN_SESSION_RESET 6007
+#define F_PG_REPLICATION_ORIGIN_SESSION_IS_SETUP 6008
+#define F_PG_REPLICATION_ORIGIN_SESSION_PROGRESS 6009
+#define F_PG_REPLICATION_ORIGIN_XACT_SETUP 6010
+#define F_PG_REPLICATION_ORIGIN_XACT_RESET 6011
+#define F_PG_REPLICATION_ORIGIN_ADVANCE 6012
+#define F_PG_REPLICATION_ORIGIN_PROGRESS 6013
+#define F_PG_SHOW_REPLICATION_ORIGIN_STATUS 6014
+#define F_JSONB_SUBSCRIPT_HANDLER 6098
+#define F_PG_LSN 6103
+#define F_PG_STAT_GET_BACKEND_SUBXACT 6107
+#define F_PG_STAT_GET_SUBSCRIPTION 6118
+#define F_PG_GET_PUBLICATION_TABLES 6119
+#define F_PG_GET_REPLICA_IDENTITY_INDEX 6120
+#define F_PG_RELATION_IS_PUBLISHABLE 6121
+#define F_MULTIRANGE_GIST_CONSISTENT 6154
+#define F_MULTIRANGE_GIST_COMPRESS 6156
+#define F_PG_GET_CATALOG_FOREIGN_KEYS 6159
+#define F_STRING_TO_TABLE_TEXT_TEXT 6160
+#define F_STRING_TO_TABLE_TEXT_TEXT_TEXT 6161
+#define F_BIT_COUNT_BIT 6162
+#define F_BIT_COUNT_BYTEA 6163
+#define F_BIT_XOR_INT2 6164
+#define F_BIT_XOR_INT4 6165
+#define F_BIT_XOR_INT8 6166
+#define F_BIT_XOR_BIT 6167
+#define F_PG_XACT_COMMIT_TIMESTAMP_ORIGIN 6168
+#define F_PG_STAT_GET_REPLICATION_SLOT 6169
+#define F_PG_STAT_RESET_REPLICATION_SLOT 6170
+#define F_TRIM_ARRAY 6172
+#define F_PG_GET_STATISTICSOBJDEF_EXPRESSIONS 6173
+#define F_PG_GET_STATISTICSOBJDEF_COLUMNS 6174
+#define F_DATE_BIN_INTERVAL_TIMESTAMP_TIMESTAMP 6177
+#define F_DATE_BIN_INTERVAL_TIMESTAMPTZ_TIMESTAMPTZ 6178
+#define F_ARRAY_SUBSCRIPT_HANDLER 6179
+#define F_RAW_ARRAY_SUBSCRIPT_HANDLER 6180
+#define F_TS_DEBUG_REGCONFIG_TEXT 6183
+#define F_TS_DEBUG_TEXT 6184
+#define F_PG_STAT_GET_DB_SESSION_TIME 6185
+#define F_PG_STAT_GET_DB_ACTIVE_TIME 6186
+#define F_PG_STAT_GET_DB_IDLE_IN_TRANSACTION_TIME 6187
+#define F_PG_STAT_GET_DB_SESSIONS 6188
+#define F_PG_STAT_GET_DB_SESSIONS_ABANDONED 6189
+#define F_PG_STAT_GET_DB_SESSIONS_FATAL 6190
+#define F_PG_STAT_GET_DB_SESSIONS_KILLED 6191
+#define F_HASH_RECORD 6192
+#define F_HASH_RECORD_EXTENDED 6193
+#define F_LTRIM_BYTEA_BYTEA 6195
+#define F_RTRIM_BYTEA_BYTEA 6196
+#define F_PG_GET_FUNCTION_SQLBODY 6197
+#define F_UNISTR 6198
+#define F_EXTRACT_TEXT_DATE 6199
+#define F_EXTRACT_TEXT_TIME 6200
+#define F_EXTRACT_TEXT_TIMETZ 6201
+#define F_EXTRACT_TEXT_TIMESTAMP 6202
+#define F_EXTRACT_TEXT_TIMESTAMPTZ 6203
+#define F_EXTRACT_TEXT_INTERVAL 6204
+#define F_HAS_PARAMETER_PRIVILEGE_NAME_TEXT_TEXT 6205
+#define F_HAS_PARAMETER_PRIVILEGE_OID_TEXT_TEXT 6206
+#define F_HAS_PARAMETER_PRIVILEGE_TEXT_TEXT 6207
+#define F_PG_READ_FILE_TEXT_BOOL 6208
+#define F_PG_READ_BINARY_FILE_TEXT_BOOL 6209
+#define F_PG_INPUT_IS_VALID 6210
+#define F_PG_INPUT_ERROR_INFO 6211
+#define F_RANDOM_NORMAL 6212
+#define F_PG_SPLIT_WALFILE_NAME 6213
+#define F_PG_STAT_GET_IO 6214
+#define F_ARRAY_SHUFFLE 6215
+#define F_ARRAY_SAMPLE 6216
+#define F_PG_STAT_GET_TUPLES_NEWPAGE_UPDATED 6217
+#define F_PG_STAT_GET_XACT_TUPLES_NEWPAGE_UPDATED 6218
+#define F_ERF 6219
+#define F_ERFC 6220
+#define F_DATE_ADD_TIMESTAMPTZ_INTERVAL 6221
+#define F_DATE_ADD_TIMESTAMPTZ_INTERVAL_TEXT 6222
+#define F_DATE_SUBTRACT_TIMESTAMPTZ_INTERVAL 6223
+#define F_PG_GET_WAL_RESOURCE_MANAGERS 6224
+#define F_MULTIRANGE_AGG_TRANSFN 6225
+#define F_MULTIRANGE_AGG_FINALFN 6226
+#define F_RANGE_AGG_ANYMULTIRANGE 6227
+#define F_PG_STAT_HAVE_STATS 6230
+#define F_PG_STAT_GET_SUBSCRIPTION_STATS 6231
+#define F_PG_STAT_RESET_SUBSCRIPTION_STATS 6232
+#define F_WINDOW_ROW_NUMBER_SUPPORT 6233
+#define F_WINDOW_RANK_SUPPORT 6234
+#define F_WINDOW_DENSE_RANK_SUPPORT 6235
+#define F_INT8INC_SUPPORT 6236
+#define F_PG_SETTINGS_GET_FLAGS 6240
+#define F_PG_STOP_MAKING_PINNED_OBJECTS 6241
+#define F_TEXT_STARTS_WITH_SUPPORT 6242
+#define F_PG_STAT_GET_RECOVERY_PREFETCH 6248
+#define F_PG_DATABASE_COLLATION_ACTUAL_VERSION 6249
+#define F_PG_IDENT_FILE_MAPPINGS 6250
+#define F_REGEXP_REPLACE_TEXT_TEXT_TEXT_INT4_INT4_TEXT 6251
+#define F_REGEXP_REPLACE_TEXT_TEXT_TEXT_INT4_INT4 6252
+#define F_REGEXP_REPLACE_TEXT_TEXT_TEXT_INT4 6253
+#define F_REGEXP_COUNT_TEXT_TEXT 6254
+#define F_REGEXP_COUNT_TEXT_TEXT_INT4 6255
+#define F_REGEXP_COUNT_TEXT_TEXT_INT4_TEXT 6256
+#define F_REGEXP_INSTR_TEXT_TEXT 6257
+#define F_REGEXP_INSTR_TEXT_TEXT_INT4 6258
+#define F_REGEXP_INSTR_TEXT_TEXT_INT4_INT4 6259
+#define F_REGEXP_INSTR_TEXT_TEXT_INT4_INT4_INT4 6260
+#define F_REGEXP_INSTR_TEXT_TEXT_INT4_INT4_INT4_TEXT 6261
+#define F_REGEXP_INSTR_TEXT_TEXT_INT4_INT4_INT4_TEXT_INT4 6262
+#define F_REGEXP_LIKE_TEXT_TEXT 6263
+#define F_REGEXP_LIKE_TEXT_TEXT_TEXT 6264
+#define F_REGEXP_SUBSTR_TEXT_TEXT 6265
+#define F_REGEXP_SUBSTR_TEXT_TEXT_INT4 6266
+#define F_REGEXP_SUBSTR_TEXT_TEXT_INT4_INT4 6267
+#define F_REGEXP_SUBSTR_TEXT_TEXT_INT4_INT4_TEXT 6268
+#define F_REGEXP_SUBSTR_TEXT_TEXT_INT4_INT4_TEXT_INT4 6269
+#define F_PG_LS_LOGICALSNAPDIR 6270
+#define F_PG_LS_LOGICALMAPDIR 6271
+#define F_PG_LS_REPLSLOTDIR 6272
+#define F_DATE_SUBTRACT_TIMESTAMPTZ_INTERVAL_TEXT 6273
+#define F_GENERATE_SERIES_TIMESTAMPTZ_TIMESTAMPTZ_INTERVAL_TEXT 6274
+#define F_JSON_AGG_STRICT_TRANSFN 6275
+#define F_JSON_AGG_STRICT 6276
+#define F_JSON_OBJECT_AGG_STRICT_TRANSFN 6277
+#define F_JSON_OBJECT_AGG_UNIQUE_TRANSFN 6278
+#define F_JSON_OBJECT_AGG_UNIQUE_STRICT_TRANSFN 6279
+#define F_JSON_OBJECT_AGG_STRICT 6280
+#define F_JSON_OBJECT_AGG_UNIQUE 6281
+#define F_JSON_OBJECT_AGG_UNIQUE_STRICT 6282
+#define F_JSONB_AGG_STRICT_TRANSFN 6283
+#define F_JSONB_AGG_STRICT 6284
+#define F_JSONB_OBJECT_AGG_STRICT_TRANSFN 6285
+#define F_JSONB_OBJECT_AGG_UNIQUE_TRANSFN 6286
+#define F_JSONB_OBJECT_AGG_UNIQUE_STRICT_TRANSFN 6287
+#define F_JSONB_OBJECT_AGG_STRICT 6288
+#define F_JSONB_OBJECT_AGG_UNIQUE 6289
+#define F_JSONB_OBJECT_AGG_UNIQUE_STRICT 6290
+#define F_ANY_VALUE 6291
+#define F_ANY_VALUE_TRANSFN 6292
+#define F_ARRAY_AGG_COMBINE 6293
+#define F_ARRAY_AGG_SERIALIZE 6294
+#define F_ARRAY_AGG_DESERIALIZE 6295
+#define F_ARRAY_AGG_ARRAY_COMBINE 6296
+#define F_ARRAY_AGG_ARRAY_SERIALIZE 6297
+#define F_ARRAY_AGG_ARRAY_DESERIALIZE 6298
+#define F_STRING_AGG_COMBINE 6299
+#define F_STRING_AGG_SERIALIZE 6300
+#define F_STRING_AGG_DESERIALIZE 6301
+#define F_PG_LOG_STANDBY_SNAPSHOT 6305
+#define F_WINDOW_PERCENT_RANK_SUPPORT 6306
+#define F_WINDOW_CUME_DIST_SUPPORT 6307
+#define F_WINDOW_NTILE_SUPPORT 6308
+#define F_PG_STAT_GET_DB_CONFLICT_LOGICALSLOT 6309
+#define F_PG_STAT_GET_LASTSCAN 6310
+#define F_SYSTEM_USER 6311
+
+#endif /* FMGROIDS_H */
diff --git a/pgsql/include/server/utils/fmgrprotos.h b/pgsql/include/server/utils/fmgrprotos.h
new file mode 100644
index 0000000000000000000000000000000000000000..5e5f55f63a58cc199366485907fc962bfc8e0700
--- /dev/null
+++ b/pgsql/include/server/utils/fmgrprotos.h
@@ -0,0 +1,2871 @@
+/*-------------------------------------------------------------------------
+ *
+ * fmgrprotos.h
+ * Prototypes for built-in functions.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES
+ * ******************************
+ * *** DO NOT EDIT THIS FILE! ***
+ * ******************************
+ *
+ * It has been GENERATED by src/backend/utils/Gen_fmgrtab.pl
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef FMGRPROTOS_H
+#define FMGRPROTOS_H
+
+#include "fmgr.h"
+
+extern Datum heap_tableam_handler(PG_FUNCTION_ARGS);
+extern Datum byteaout(PG_FUNCTION_ARGS);
+extern Datum charout(PG_FUNCTION_ARGS);
+extern Datum namein(PG_FUNCTION_ARGS);
+extern Datum nameout(PG_FUNCTION_ARGS);
+extern Datum int2in(PG_FUNCTION_ARGS);
+extern Datum int2out(PG_FUNCTION_ARGS);
+extern Datum int2vectorin(PG_FUNCTION_ARGS);
+extern Datum int2vectorout(PG_FUNCTION_ARGS);
+extern Datum int4in(PG_FUNCTION_ARGS);
+extern Datum int4out(PG_FUNCTION_ARGS);
+extern Datum regprocin(PG_FUNCTION_ARGS);
+extern Datum regprocout(PG_FUNCTION_ARGS);
+extern Datum textin(PG_FUNCTION_ARGS);
+extern Datum textout(PG_FUNCTION_ARGS);
+extern Datum tidin(PG_FUNCTION_ARGS);
+extern Datum tidout(PG_FUNCTION_ARGS);
+extern Datum xidin(PG_FUNCTION_ARGS);
+extern Datum xidout(PG_FUNCTION_ARGS);
+extern Datum cidin(PG_FUNCTION_ARGS);
+extern Datum cidout(PG_FUNCTION_ARGS);
+extern Datum oidvectorin(PG_FUNCTION_ARGS);
+extern Datum oidvectorout(PG_FUNCTION_ARGS);
+extern Datum boollt(PG_FUNCTION_ARGS);
+extern Datum boolgt(PG_FUNCTION_ARGS);
+extern Datum booleq(PG_FUNCTION_ARGS);
+extern Datum chareq(PG_FUNCTION_ARGS);
+extern Datum nameeq(PG_FUNCTION_ARGS);
+extern Datum int2eq(PG_FUNCTION_ARGS);
+extern Datum int2lt(PG_FUNCTION_ARGS);
+extern Datum int4eq(PG_FUNCTION_ARGS);
+extern Datum int4lt(PG_FUNCTION_ARGS);
+extern Datum texteq(PG_FUNCTION_ARGS);
+extern Datum xideq(PG_FUNCTION_ARGS);
+extern Datum cideq(PG_FUNCTION_ARGS);
+extern Datum charne(PG_FUNCTION_ARGS);
+extern Datum charle(PG_FUNCTION_ARGS);
+extern Datum chargt(PG_FUNCTION_ARGS);
+extern Datum charge(PG_FUNCTION_ARGS);
+extern Datum chartoi4(PG_FUNCTION_ARGS);
+extern Datum i4tochar(PG_FUNCTION_ARGS);
+extern Datum nameregexeq(PG_FUNCTION_ARGS);
+extern Datum boolne(PG_FUNCTION_ARGS);
+extern Datum pg_ddl_command_in(PG_FUNCTION_ARGS);
+extern Datum pg_ddl_command_out(PG_FUNCTION_ARGS);
+extern Datum pg_ddl_command_recv(PG_FUNCTION_ARGS);
+extern Datum pgsql_version(PG_FUNCTION_ARGS);
+extern Datum pg_ddl_command_send(PG_FUNCTION_ARGS);
+extern Datum eqsel(PG_FUNCTION_ARGS);
+extern Datum neqsel(PG_FUNCTION_ARGS);
+extern Datum scalarltsel(PG_FUNCTION_ARGS);
+extern Datum scalargtsel(PG_FUNCTION_ARGS);
+extern Datum eqjoinsel(PG_FUNCTION_ARGS);
+extern Datum neqjoinsel(PG_FUNCTION_ARGS);
+extern Datum scalarltjoinsel(PG_FUNCTION_ARGS);
+extern Datum scalargtjoinsel(PG_FUNCTION_ARGS);
+extern Datum unknownin(PG_FUNCTION_ARGS);
+extern Datum unknownout(PG_FUNCTION_ARGS);
+extern Datum box_above_eq(PG_FUNCTION_ARGS);
+extern Datum box_below_eq(PG_FUNCTION_ARGS);
+extern Datum point_in(PG_FUNCTION_ARGS);
+extern Datum point_out(PG_FUNCTION_ARGS);
+extern Datum lseg_in(PG_FUNCTION_ARGS);
+extern Datum lseg_out(PG_FUNCTION_ARGS);
+extern Datum path_in(PG_FUNCTION_ARGS);
+extern Datum path_out(PG_FUNCTION_ARGS);
+extern Datum box_in(PG_FUNCTION_ARGS);
+extern Datum box_out(PG_FUNCTION_ARGS);
+extern Datum box_overlap(PG_FUNCTION_ARGS);
+extern Datum box_ge(PG_FUNCTION_ARGS);
+extern Datum box_gt(PG_FUNCTION_ARGS);
+extern Datum box_eq(PG_FUNCTION_ARGS);
+extern Datum box_lt(PG_FUNCTION_ARGS);
+extern Datum box_le(PG_FUNCTION_ARGS);
+extern Datum point_above(PG_FUNCTION_ARGS);
+extern Datum point_left(PG_FUNCTION_ARGS);
+extern Datum point_right(PG_FUNCTION_ARGS);
+extern Datum point_below(PG_FUNCTION_ARGS);
+extern Datum point_eq(PG_FUNCTION_ARGS);
+extern Datum on_pb(PG_FUNCTION_ARGS);
+extern Datum on_ppath(PG_FUNCTION_ARGS);
+extern Datum box_center(PG_FUNCTION_ARGS);
+extern Datum areasel(PG_FUNCTION_ARGS);
+extern Datum areajoinsel(PG_FUNCTION_ARGS);
+extern Datum int4mul(PG_FUNCTION_ARGS);
+extern Datum int4ne(PG_FUNCTION_ARGS);
+extern Datum int2ne(PG_FUNCTION_ARGS);
+extern Datum int2gt(PG_FUNCTION_ARGS);
+extern Datum int4gt(PG_FUNCTION_ARGS);
+extern Datum int2le(PG_FUNCTION_ARGS);
+extern Datum int4le(PG_FUNCTION_ARGS);
+extern Datum int4ge(PG_FUNCTION_ARGS);
+extern Datum int2ge(PG_FUNCTION_ARGS);
+extern Datum int2mul(PG_FUNCTION_ARGS);
+extern Datum int2div(PG_FUNCTION_ARGS);
+extern Datum int4div(PG_FUNCTION_ARGS);
+extern Datum int2mod(PG_FUNCTION_ARGS);
+extern Datum int4mod(PG_FUNCTION_ARGS);
+extern Datum textne(PG_FUNCTION_ARGS);
+extern Datum int24eq(PG_FUNCTION_ARGS);
+extern Datum int42eq(PG_FUNCTION_ARGS);
+extern Datum int24lt(PG_FUNCTION_ARGS);
+extern Datum int42lt(PG_FUNCTION_ARGS);
+extern Datum int24gt(PG_FUNCTION_ARGS);
+extern Datum int42gt(PG_FUNCTION_ARGS);
+extern Datum int24ne(PG_FUNCTION_ARGS);
+extern Datum int42ne(PG_FUNCTION_ARGS);
+extern Datum int24le(PG_FUNCTION_ARGS);
+extern Datum int42le(PG_FUNCTION_ARGS);
+extern Datum int24ge(PG_FUNCTION_ARGS);
+extern Datum int42ge(PG_FUNCTION_ARGS);
+extern Datum int24mul(PG_FUNCTION_ARGS);
+extern Datum int42mul(PG_FUNCTION_ARGS);
+extern Datum int24div(PG_FUNCTION_ARGS);
+extern Datum int42div(PG_FUNCTION_ARGS);
+extern Datum int2pl(PG_FUNCTION_ARGS);
+extern Datum int4pl(PG_FUNCTION_ARGS);
+extern Datum int24pl(PG_FUNCTION_ARGS);
+extern Datum int42pl(PG_FUNCTION_ARGS);
+extern Datum int2mi(PG_FUNCTION_ARGS);
+extern Datum int4mi(PG_FUNCTION_ARGS);
+extern Datum int24mi(PG_FUNCTION_ARGS);
+extern Datum int42mi(PG_FUNCTION_ARGS);
+extern Datum oideq(PG_FUNCTION_ARGS);
+extern Datum oidne(PG_FUNCTION_ARGS);
+extern Datum box_same(PG_FUNCTION_ARGS);
+extern Datum box_contain(PG_FUNCTION_ARGS);
+extern Datum box_left(PG_FUNCTION_ARGS);
+extern Datum box_overleft(PG_FUNCTION_ARGS);
+extern Datum box_overright(PG_FUNCTION_ARGS);
+extern Datum box_right(PG_FUNCTION_ARGS);
+extern Datum box_contained(PG_FUNCTION_ARGS);
+extern Datum box_contain_pt(PG_FUNCTION_ARGS);
+extern Datum pg_node_tree_in(PG_FUNCTION_ARGS);
+extern Datum pg_node_tree_out(PG_FUNCTION_ARGS);
+extern Datum pg_node_tree_recv(PG_FUNCTION_ARGS);
+extern Datum pg_node_tree_send(PG_FUNCTION_ARGS);
+extern Datum float4in(PG_FUNCTION_ARGS);
+extern Datum float4out(PG_FUNCTION_ARGS);
+extern Datum float4mul(PG_FUNCTION_ARGS);
+extern Datum float4div(PG_FUNCTION_ARGS);
+extern Datum float4pl(PG_FUNCTION_ARGS);
+extern Datum float4mi(PG_FUNCTION_ARGS);
+extern Datum float4um(PG_FUNCTION_ARGS);
+extern Datum float4abs(PG_FUNCTION_ARGS);
+extern Datum float4_accum(PG_FUNCTION_ARGS);
+extern Datum float4larger(PG_FUNCTION_ARGS);
+extern Datum float4smaller(PG_FUNCTION_ARGS);
+extern Datum int4um(PG_FUNCTION_ARGS);
+extern Datum int2um(PG_FUNCTION_ARGS);
+extern Datum float8in(PG_FUNCTION_ARGS);
+extern Datum float8out(PG_FUNCTION_ARGS);
+extern Datum float8mul(PG_FUNCTION_ARGS);
+extern Datum float8div(PG_FUNCTION_ARGS);
+extern Datum float8pl(PG_FUNCTION_ARGS);
+extern Datum float8mi(PG_FUNCTION_ARGS);
+extern Datum float8um(PG_FUNCTION_ARGS);
+extern Datum float8abs(PG_FUNCTION_ARGS);
+extern Datum float8_accum(PG_FUNCTION_ARGS);
+extern Datum float8larger(PG_FUNCTION_ARGS);
+extern Datum float8smaller(PG_FUNCTION_ARGS);
+extern Datum lseg_center(PG_FUNCTION_ARGS);
+extern Datum poly_center(PG_FUNCTION_ARGS);
+extern Datum dround(PG_FUNCTION_ARGS);
+extern Datum dtrunc(PG_FUNCTION_ARGS);
+extern Datum dsqrt(PG_FUNCTION_ARGS);
+extern Datum dcbrt(PG_FUNCTION_ARGS);
+extern Datum dpow(PG_FUNCTION_ARGS);
+extern Datum dexp(PG_FUNCTION_ARGS);
+extern Datum dlog1(PG_FUNCTION_ARGS);
+extern Datum i2tod(PG_FUNCTION_ARGS);
+extern Datum i2tof(PG_FUNCTION_ARGS);
+extern Datum dtoi2(PG_FUNCTION_ARGS);
+extern Datum ftoi2(PG_FUNCTION_ARGS);
+extern Datum line_distance(PG_FUNCTION_ARGS);
+extern Datum nameeqtext(PG_FUNCTION_ARGS);
+extern Datum namelttext(PG_FUNCTION_ARGS);
+extern Datum nameletext(PG_FUNCTION_ARGS);
+extern Datum namegetext(PG_FUNCTION_ARGS);
+extern Datum namegttext(PG_FUNCTION_ARGS);
+extern Datum namenetext(PG_FUNCTION_ARGS);
+extern Datum btnametextcmp(PG_FUNCTION_ARGS);
+extern Datum texteqname(PG_FUNCTION_ARGS);
+extern Datum textltname(PG_FUNCTION_ARGS);
+extern Datum textlename(PG_FUNCTION_ARGS);
+extern Datum textgename(PG_FUNCTION_ARGS);
+extern Datum textgtname(PG_FUNCTION_ARGS);
+extern Datum textnename(PG_FUNCTION_ARGS);
+extern Datum bttextnamecmp(PG_FUNCTION_ARGS);
+extern Datum nameconcatoid(PG_FUNCTION_ARGS);
+extern Datum table_am_handler_in(PG_FUNCTION_ARGS);
+extern Datum table_am_handler_out(PG_FUNCTION_ARGS);
+extern Datum timeofday(PG_FUNCTION_ARGS);
+extern Datum pg_nextoid(PG_FUNCTION_ARGS);
+extern Datum float8_combine(PG_FUNCTION_ARGS);
+extern Datum inter_sl(PG_FUNCTION_ARGS);
+extern Datum inter_lb(PG_FUNCTION_ARGS);
+extern Datum float48mul(PG_FUNCTION_ARGS);
+extern Datum float48div(PG_FUNCTION_ARGS);
+extern Datum float48pl(PG_FUNCTION_ARGS);
+extern Datum float48mi(PG_FUNCTION_ARGS);
+extern Datum float84mul(PG_FUNCTION_ARGS);
+extern Datum float84div(PG_FUNCTION_ARGS);
+extern Datum float84pl(PG_FUNCTION_ARGS);
+extern Datum float84mi(PG_FUNCTION_ARGS);
+extern Datum float4eq(PG_FUNCTION_ARGS);
+extern Datum float4ne(PG_FUNCTION_ARGS);
+extern Datum float4lt(PG_FUNCTION_ARGS);
+extern Datum float4le(PG_FUNCTION_ARGS);
+extern Datum float4gt(PG_FUNCTION_ARGS);
+extern Datum float4ge(PG_FUNCTION_ARGS);
+extern Datum float8eq(PG_FUNCTION_ARGS);
+extern Datum float8ne(PG_FUNCTION_ARGS);
+extern Datum float8lt(PG_FUNCTION_ARGS);
+extern Datum float8le(PG_FUNCTION_ARGS);
+extern Datum float8gt(PG_FUNCTION_ARGS);
+extern Datum float8ge(PG_FUNCTION_ARGS);
+extern Datum float48eq(PG_FUNCTION_ARGS);
+extern Datum float48ne(PG_FUNCTION_ARGS);
+extern Datum float48lt(PG_FUNCTION_ARGS);
+extern Datum float48le(PG_FUNCTION_ARGS);
+extern Datum float48gt(PG_FUNCTION_ARGS);
+extern Datum float48ge(PG_FUNCTION_ARGS);
+extern Datum float84eq(PG_FUNCTION_ARGS);
+extern Datum float84ne(PG_FUNCTION_ARGS);
+extern Datum float84lt(PG_FUNCTION_ARGS);
+extern Datum float84le(PG_FUNCTION_ARGS);
+extern Datum float84gt(PG_FUNCTION_ARGS);
+extern Datum float84ge(PG_FUNCTION_ARGS);
+extern Datum ftod(PG_FUNCTION_ARGS);
+extern Datum dtof(PG_FUNCTION_ARGS);
+extern Datum i2toi4(PG_FUNCTION_ARGS);
+extern Datum i4toi2(PG_FUNCTION_ARGS);
+extern Datum pg_jit_available(PG_FUNCTION_ARGS);
+extern Datum i4tod(PG_FUNCTION_ARGS);
+extern Datum dtoi4(PG_FUNCTION_ARGS);
+extern Datum i4tof(PG_FUNCTION_ARGS);
+extern Datum ftoi4(PG_FUNCTION_ARGS);
+extern Datum width_bucket_float8(PG_FUNCTION_ARGS);
+extern Datum json_in(PG_FUNCTION_ARGS);
+extern Datum json_out(PG_FUNCTION_ARGS);
+extern Datum json_recv(PG_FUNCTION_ARGS);
+extern Datum json_send(PG_FUNCTION_ARGS);
+extern Datum index_am_handler_in(PG_FUNCTION_ARGS);
+extern Datum index_am_handler_out(PG_FUNCTION_ARGS);
+extern Datum hashmacaddr8(PG_FUNCTION_ARGS);
+extern Datum hash_aclitem(PG_FUNCTION_ARGS);
+extern Datum bthandler(PG_FUNCTION_ARGS);
+extern Datum hashhandler(PG_FUNCTION_ARGS);
+extern Datum gisthandler(PG_FUNCTION_ARGS);
+extern Datum ginhandler(PG_FUNCTION_ARGS);
+extern Datum spghandler(PG_FUNCTION_ARGS);
+extern Datum brinhandler(PG_FUNCTION_ARGS);
+extern Datum scalarlesel(PG_FUNCTION_ARGS);
+extern Datum scalargesel(PG_FUNCTION_ARGS);
+extern Datum amvalidate(PG_FUNCTION_ARGS);
+extern Datum poly_same(PG_FUNCTION_ARGS);
+extern Datum poly_contain(PG_FUNCTION_ARGS);
+extern Datum poly_left(PG_FUNCTION_ARGS);
+extern Datum poly_overleft(PG_FUNCTION_ARGS);
+extern Datum poly_overright(PG_FUNCTION_ARGS);
+extern Datum poly_right(PG_FUNCTION_ARGS);
+extern Datum poly_contained(PG_FUNCTION_ARGS);
+extern Datum poly_overlap(PG_FUNCTION_ARGS);
+extern Datum poly_in(PG_FUNCTION_ARGS);
+extern Datum poly_out(PG_FUNCTION_ARGS);
+extern Datum btint2cmp(PG_FUNCTION_ARGS);
+extern Datum btint4cmp(PG_FUNCTION_ARGS);
+extern Datum btfloat4cmp(PG_FUNCTION_ARGS);
+extern Datum btfloat8cmp(PG_FUNCTION_ARGS);
+extern Datum btoidcmp(PG_FUNCTION_ARGS);
+extern Datum dist_bp(PG_FUNCTION_ARGS);
+extern Datum btcharcmp(PG_FUNCTION_ARGS);
+extern Datum btnamecmp(PG_FUNCTION_ARGS);
+extern Datum bttextcmp(PG_FUNCTION_ARGS);
+extern Datum lseg_distance(PG_FUNCTION_ARGS);
+extern Datum lseg_interpt(PG_FUNCTION_ARGS);
+extern Datum dist_ps(PG_FUNCTION_ARGS);
+extern Datum dist_pb(PG_FUNCTION_ARGS);
+extern Datum dist_sb(PG_FUNCTION_ARGS);
+extern Datum close_ps(PG_FUNCTION_ARGS);
+extern Datum close_pb(PG_FUNCTION_ARGS);
+extern Datum close_sb(PG_FUNCTION_ARGS);
+extern Datum on_ps(PG_FUNCTION_ARGS);
+extern Datum path_distance(PG_FUNCTION_ARGS);
+extern Datum dist_ppath(PG_FUNCTION_ARGS);
+extern Datum on_sb(PG_FUNCTION_ARGS);
+extern Datum inter_sb(PG_FUNCTION_ARGS);
+extern Datum text_to_array_null(PG_FUNCTION_ARGS);
+extern Datum cash_cmp(PG_FUNCTION_ARGS);
+extern Datum array_append(PG_FUNCTION_ARGS);
+extern Datum array_prepend(PG_FUNCTION_ARGS);
+extern Datum dist_sp(PG_FUNCTION_ARGS);
+extern Datum dist_bs(PG_FUNCTION_ARGS);
+extern Datum btarraycmp(PG_FUNCTION_ARGS);
+extern Datum array_cat(PG_FUNCTION_ARGS);
+extern Datum array_to_text_null(PG_FUNCTION_ARGS);
+extern Datum scalarlejoinsel(PG_FUNCTION_ARGS);
+extern Datum array_ne(PG_FUNCTION_ARGS);
+extern Datum array_lt(PG_FUNCTION_ARGS);
+extern Datum array_gt(PG_FUNCTION_ARGS);
+extern Datum array_le(PG_FUNCTION_ARGS);
+extern Datum text_to_array(PG_FUNCTION_ARGS);
+extern Datum array_to_text(PG_FUNCTION_ARGS);
+extern Datum array_ge(PG_FUNCTION_ARGS);
+extern Datum scalargejoinsel(PG_FUNCTION_ARGS);
+extern Datum hashmacaddr(PG_FUNCTION_ARGS);
+extern Datum hashtext(PG_FUNCTION_ARGS);
+extern Datum rtrim1(PG_FUNCTION_ARGS);
+extern Datum btoidvectorcmp(PG_FUNCTION_ARGS);
+extern Datum name_text(PG_FUNCTION_ARGS);
+extern Datum text_name(PG_FUNCTION_ARGS);
+extern Datum name_bpchar(PG_FUNCTION_ARGS);
+extern Datum bpchar_name(PG_FUNCTION_ARGS);
+extern Datum dist_pathp(PG_FUNCTION_ARGS);
+extern Datum hashinet(PG_FUNCTION_ARGS);
+extern Datum hashint4extended(PG_FUNCTION_ARGS);
+extern Datum hash_numeric(PG_FUNCTION_ARGS);
+extern Datum macaddr_in(PG_FUNCTION_ARGS);
+extern Datum macaddr_out(PG_FUNCTION_ARGS);
+extern Datum pg_num_nulls(PG_FUNCTION_ARGS);
+extern Datum pg_num_nonnulls(PG_FUNCTION_ARGS);
+extern Datum hashint2extended(PG_FUNCTION_ARGS);
+extern Datum hashint8extended(PG_FUNCTION_ARGS);
+extern Datum hashfloat4extended(PG_FUNCTION_ARGS);
+extern Datum hashfloat8extended(PG_FUNCTION_ARGS);
+extern Datum hashoidextended(PG_FUNCTION_ARGS);
+extern Datum hashcharextended(PG_FUNCTION_ARGS);
+extern Datum hashnameextended(PG_FUNCTION_ARGS);
+extern Datum hashtextextended(PG_FUNCTION_ARGS);
+extern Datum hashint2(PG_FUNCTION_ARGS);
+extern Datum hashint4(PG_FUNCTION_ARGS);
+extern Datum hashfloat4(PG_FUNCTION_ARGS);
+extern Datum hashfloat8(PG_FUNCTION_ARGS);
+extern Datum hashoid(PG_FUNCTION_ARGS);
+extern Datum hashchar(PG_FUNCTION_ARGS);
+extern Datum hashname(PG_FUNCTION_ARGS);
+extern Datum hashvarlena(PG_FUNCTION_ARGS);
+extern Datum hashoidvector(PG_FUNCTION_ARGS);
+extern Datum text_larger(PG_FUNCTION_ARGS);
+extern Datum text_smaller(PG_FUNCTION_ARGS);
+extern Datum int8in(PG_FUNCTION_ARGS);
+extern Datum int8out(PG_FUNCTION_ARGS);
+extern Datum int8um(PG_FUNCTION_ARGS);
+extern Datum int8pl(PG_FUNCTION_ARGS);
+extern Datum int8mi(PG_FUNCTION_ARGS);
+extern Datum int8mul(PG_FUNCTION_ARGS);
+extern Datum int8div(PG_FUNCTION_ARGS);
+extern Datum int8eq(PG_FUNCTION_ARGS);
+extern Datum int8ne(PG_FUNCTION_ARGS);
+extern Datum int8lt(PG_FUNCTION_ARGS);
+extern Datum int8gt(PG_FUNCTION_ARGS);
+extern Datum int8le(PG_FUNCTION_ARGS);
+extern Datum int8ge(PG_FUNCTION_ARGS);
+extern Datum int84eq(PG_FUNCTION_ARGS);
+extern Datum int84ne(PG_FUNCTION_ARGS);
+extern Datum int84lt(PG_FUNCTION_ARGS);
+extern Datum int84gt(PG_FUNCTION_ARGS);
+extern Datum int84le(PG_FUNCTION_ARGS);
+extern Datum int84ge(PG_FUNCTION_ARGS);
+extern Datum int84(PG_FUNCTION_ARGS);
+extern Datum int48(PG_FUNCTION_ARGS);
+extern Datum i8tod(PG_FUNCTION_ARGS);
+extern Datum dtoi8(PG_FUNCTION_ARGS);
+extern Datum array_larger(PG_FUNCTION_ARGS);
+extern Datum array_smaller(PG_FUNCTION_ARGS);
+extern Datum inet_abbrev(PG_FUNCTION_ARGS);
+extern Datum cidr_abbrev(PG_FUNCTION_ARGS);
+extern Datum inet_set_masklen(PG_FUNCTION_ARGS);
+extern Datum oidvectorne(PG_FUNCTION_ARGS);
+extern Datum hash_array(PG_FUNCTION_ARGS);
+extern Datum cidr_set_masklen(PG_FUNCTION_ARGS);
+extern Datum pg_indexam_has_property(PG_FUNCTION_ARGS);
+extern Datum pg_index_has_property(PG_FUNCTION_ARGS);
+extern Datum pg_index_column_has_property(PG_FUNCTION_ARGS);
+extern Datum i8tof(PG_FUNCTION_ARGS);
+extern Datum ftoi8(PG_FUNCTION_ARGS);
+extern Datum namelt(PG_FUNCTION_ARGS);
+extern Datum namele(PG_FUNCTION_ARGS);
+extern Datum namegt(PG_FUNCTION_ARGS);
+extern Datum namege(PG_FUNCTION_ARGS);
+extern Datum namene(PG_FUNCTION_ARGS);
+extern Datum bpchar(PG_FUNCTION_ARGS);
+extern Datum varchar(PG_FUNCTION_ARGS);
+extern Datum pg_indexam_progress_phasename(PG_FUNCTION_ARGS);
+extern Datum oidvectorlt(PG_FUNCTION_ARGS);
+extern Datum oidvectorle(PG_FUNCTION_ARGS);
+extern Datum oidvectoreq(PG_FUNCTION_ARGS);
+extern Datum oidvectorge(PG_FUNCTION_ARGS);
+extern Datum oidvectorgt(PG_FUNCTION_ARGS);
+extern Datum network_network(PG_FUNCTION_ARGS);
+extern Datum network_netmask(PG_FUNCTION_ARGS);
+extern Datum network_masklen(PG_FUNCTION_ARGS);
+extern Datum network_broadcast(PG_FUNCTION_ARGS);
+extern Datum network_host(PG_FUNCTION_ARGS);
+extern Datum dist_lp(PG_FUNCTION_ARGS);
+extern Datum dist_ls(PG_FUNCTION_ARGS);
+extern Datum current_user(PG_FUNCTION_ARGS);
+extern Datum network_family(PG_FUNCTION_ARGS);
+extern Datum int82(PG_FUNCTION_ARGS);
+extern Datum be_lo_create(PG_FUNCTION_ARGS);
+extern Datum oidlt(PG_FUNCTION_ARGS);
+extern Datum oidle(PG_FUNCTION_ARGS);
+extern Datum byteaoctetlen(PG_FUNCTION_ARGS);
+extern Datum byteaGetByte(PG_FUNCTION_ARGS);
+extern Datum byteaSetByte(PG_FUNCTION_ARGS);
+extern Datum byteaGetBit(PG_FUNCTION_ARGS);
+extern Datum byteaSetBit(PG_FUNCTION_ARGS);
+extern Datum dist_pl(PG_FUNCTION_ARGS);
+extern Datum dist_sl(PG_FUNCTION_ARGS);
+extern Datum dist_cpoly(PG_FUNCTION_ARGS);
+extern Datum poly_distance(PG_FUNCTION_ARGS);
+extern Datum network_show(PG_FUNCTION_ARGS);
+extern Datum text_lt(PG_FUNCTION_ARGS);
+extern Datum text_le(PG_FUNCTION_ARGS);
+extern Datum text_gt(PG_FUNCTION_ARGS);
+extern Datum text_ge(PG_FUNCTION_ARGS);
+extern Datum array_eq(PG_FUNCTION_ARGS);
+extern Datum session_user(PG_FUNCTION_ARGS);
+extern Datum array_dims(PG_FUNCTION_ARGS);
+extern Datum array_ndims(PG_FUNCTION_ARGS);
+extern Datum byteaoverlay(PG_FUNCTION_ARGS);
+extern Datum array_in(PG_FUNCTION_ARGS);
+extern Datum array_out(PG_FUNCTION_ARGS);
+extern Datum byteaoverlay_no_len(PG_FUNCTION_ARGS);
+extern Datum macaddr_trunc(PG_FUNCTION_ARGS);
+extern Datum int28(PG_FUNCTION_ARGS);
+extern Datum be_lo_import(PG_FUNCTION_ARGS);
+extern Datum be_lo_export(PG_FUNCTION_ARGS);
+extern Datum int4inc(PG_FUNCTION_ARGS);
+extern Datum be_lo_import_with_oid(PG_FUNCTION_ARGS);
+extern Datum int4larger(PG_FUNCTION_ARGS);
+extern Datum int4smaller(PG_FUNCTION_ARGS);
+extern Datum int2larger(PG_FUNCTION_ARGS);
+extern Datum int2smaller(PG_FUNCTION_ARGS);
+extern Datum hashvarlenaextended(PG_FUNCTION_ARGS);
+extern Datum hashoidvectorextended(PG_FUNCTION_ARGS);
+extern Datum hash_aclitem_extended(PG_FUNCTION_ARGS);
+extern Datum hashmacaddrextended(PG_FUNCTION_ARGS);
+extern Datum hashinetextended(PG_FUNCTION_ARGS);
+extern Datum hash_numeric_extended(PG_FUNCTION_ARGS);
+extern Datum hashmacaddr8extended(PG_FUNCTION_ARGS);
+extern Datum hash_array_extended(PG_FUNCTION_ARGS);
+extern Datum dist_polyc(PG_FUNCTION_ARGS);
+extern Datum pg_client_encoding(PG_FUNCTION_ARGS);
+extern Datum current_query(PG_FUNCTION_ARGS);
+extern Datum macaddr_eq(PG_FUNCTION_ARGS);
+extern Datum macaddr_lt(PG_FUNCTION_ARGS);
+extern Datum macaddr_le(PG_FUNCTION_ARGS);
+extern Datum macaddr_gt(PG_FUNCTION_ARGS);
+extern Datum macaddr_ge(PG_FUNCTION_ARGS);
+extern Datum macaddr_ne(PG_FUNCTION_ARGS);
+extern Datum macaddr_cmp(PG_FUNCTION_ARGS);
+extern Datum int82pl(PG_FUNCTION_ARGS);
+extern Datum int82mi(PG_FUNCTION_ARGS);
+extern Datum int82mul(PG_FUNCTION_ARGS);
+extern Datum int82div(PG_FUNCTION_ARGS);
+extern Datum int28pl(PG_FUNCTION_ARGS);
+extern Datum btint8cmp(PG_FUNCTION_ARGS);
+extern Datum cash_mul_flt4(PG_FUNCTION_ARGS);
+extern Datum cash_div_flt4(PG_FUNCTION_ARGS);
+extern Datum flt4_mul_cash(PG_FUNCTION_ARGS);
+extern Datum textpos(PG_FUNCTION_ARGS);
+extern Datum textlike(PG_FUNCTION_ARGS);
+extern Datum textnlike(PG_FUNCTION_ARGS);
+extern Datum int48eq(PG_FUNCTION_ARGS);
+extern Datum int48ne(PG_FUNCTION_ARGS);
+extern Datum int48lt(PG_FUNCTION_ARGS);
+extern Datum int48gt(PG_FUNCTION_ARGS);
+extern Datum int48le(PG_FUNCTION_ARGS);
+extern Datum int48ge(PG_FUNCTION_ARGS);
+extern Datum namelike(PG_FUNCTION_ARGS);
+extern Datum namenlike(PG_FUNCTION_ARGS);
+extern Datum char_bpchar(PG_FUNCTION_ARGS);
+extern Datum current_database(PG_FUNCTION_ARGS);
+extern Datum int4_mul_cash(PG_FUNCTION_ARGS);
+extern Datum int2_mul_cash(PG_FUNCTION_ARGS);
+extern Datum cash_mul_int4(PG_FUNCTION_ARGS);
+extern Datum cash_div_int4(PG_FUNCTION_ARGS);
+extern Datum cash_mul_int2(PG_FUNCTION_ARGS);
+extern Datum cash_div_int2(PG_FUNCTION_ARGS);
+extern Datum lower(PG_FUNCTION_ARGS);
+extern Datum upper(PG_FUNCTION_ARGS);
+extern Datum initcap(PG_FUNCTION_ARGS);
+extern Datum lpad(PG_FUNCTION_ARGS);
+extern Datum rpad(PG_FUNCTION_ARGS);
+extern Datum ltrim(PG_FUNCTION_ARGS);
+extern Datum rtrim(PG_FUNCTION_ARGS);
+extern Datum text_substr(PG_FUNCTION_ARGS);
+extern Datum translate(PG_FUNCTION_ARGS);
+extern Datum ltrim1(PG_FUNCTION_ARGS);
+extern Datum text_substr_no_len(PG_FUNCTION_ARGS);
+extern Datum btrim(PG_FUNCTION_ARGS);
+extern Datum btrim1(PG_FUNCTION_ARGS);
+extern Datum cash_in(PG_FUNCTION_ARGS);
+extern Datum cash_out(PG_FUNCTION_ARGS);
+extern Datum cash_eq(PG_FUNCTION_ARGS);
+extern Datum cash_ne(PG_FUNCTION_ARGS);
+extern Datum cash_lt(PG_FUNCTION_ARGS);
+extern Datum cash_le(PG_FUNCTION_ARGS);
+extern Datum cash_gt(PG_FUNCTION_ARGS);
+extern Datum cash_ge(PG_FUNCTION_ARGS);
+extern Datum cash_pl(PG_FUNCTION_ARGS);
+extern Datum cash_mi(PG_FUNCTION_ARGS);
+extern Datum cash_mul_flt8(PG_FUNCTION_ARGS);
+extern Datum cash_div_flt8(PG_FUNCTION_ARGS);
+extern Datum cashlarger(PG_FUNCTION_ARGS);
+extern Datum cashsmaller(PG_FUNCTION_ARGS);
+extern Datum inet_in(PG_FUNCTION_ARGS);
+extern Datum inet_out(PG_FUNCTION_ARGS);
+extern Datum flt8_mul_cash(PG_FUNCTION_ARGS);
+extern Datum network_eq(PG_FUNCTION_ARGS);
+extern Datum network_lt(PG_FUNCTION_ARGS);
+extern Datum network_le(PG_FUNCTION_ARGS);
+extern Datum network_gt(PG_FUNCTION_ARGS);
+extern Datum network_ge(PG_FUNCTION_ARGS);
+extern Datum network_ne(PG_FUNCTION_ARGS);
+extern Datum network_cmp(PG_FUNCTION_ARGS);
+extern Datum network_sub(PG_FUNCTION_ARGS);
+extern Datum network_subeq(PG_FUNCTION_ARGS);
+extern Datum network_sup(PG_FUNCTION_ARGS);
+extern Datum network_supeq(PG_FUNCTION_ARGS);
+extern Datum cash_words(PG_FUNCTION_ARGS);
+extern Datum generate_series_timestamp(PG_FUNCTION_ARGS);
+extern Datum generate_series_timestamptz(PG_FUNCTION_ARGS);
+extern Datum int28mi(PG_FUNCTION_ARGS);
+extern Datum int28mul(PG_FUNCTION_ARGS);
+extern Datum text_char(PG_FUNCTION_ARGS);
+extern Datum int8mod(PG_FUNCTION_ARGS);
+extern Datum char_text(PG_FUNCTION_ARGS);
+extern Datum int28div(PG_FUNCTION_ARGS);
+extern Datum hashint8(PG_FUNCTION_ARGS);
+extern Datum be_lo_open(PG_FUNCTION_ARGS);
+extern Datum be_lo_close(PG_FUNCTION_ARGS);
+extern Datum be_loread(PG_FUNCTION_ARGS);
+extern Datum be_lowrite(PG_FUNCTION_ARGS);
+extern Datum be_lo_lseek(PG_FUNCTION_ARGS);
+extern Datum be_lo_creat(PG_FUNCTION_ARGS);
+extern Datum be_lo_tell(PG_FUNCTION_ARGS);
+extern Datum on_pl(PG_FUNCTION_ARGS);
+extern Datum on_sl(PG_FUNCTION_ARGS);
+extern Datum close_pl(PG_FUNCTION_ARGS);
+extern Datum be_lo_unlink(PG_FUNCTION_ARGS);
+extern Datum hashbpcharextended(PG_FUNCTION_ARGS);
+extern Datum path_inter(PG_FUNCTION_ARGS);
+extern Datum box_area(PG_FUNCTION_ARGS);
+extern Datum box_width(PG_FUNCTION_ARGS);
+extern Datum box_height(PG_FUNCTION_ARGS);
+extern Datum box_distance(PG_FUNCTION_ARGS);
+extern Datum path_area(PG_FUNCTION_ARGS);
+extern Datum box_intersect(PG_FUNCTION_ARGS);
+extern Datum box_diagonal(PG_FUNCTION_ARGS);
+extern Datum path_n_lt(PG_FUNCTION_ARGS);
+extern Datum path_n_gt(PG_FUNCTION_ARGS);
+extern Datum path_n_eq(PG_FUNCTION_ARGS);
+extern Datum path_n_le(PG_FUNCTION_ARGS);
+extern Datum path_n_ge(PG_FUNCTION_ARGS);
+extern Datum path_length(PG_FUNCTION_ARGS);
+extern Datum point_ne(PG_FUNCTION_ARGS);
+extern Datum point_vert(PG_FUNCTION_ARGS);
+extern Datum point_horiz(PG_FUNCTION_ARGS);
+extern Datum point_distance(PG_FUNCTION_ARGS);
+extern Datum point_slope(PG_FUNCTION_ARGS);
+extern Datum lseg_construct(PG_FUNCTION_ARGS);
+extern Datum lseg_intersect(PG_FUNCTION_ARGS);
+extern Datum lseg_parallel(PG_FUNCTION_ARGS);
+extern Datum lseg_perp(PG_FUNCTION_ARGS);
+extern Datum lseg_vertical(PG_FUNCTION_ARGS);
+extern Datum lseg_horizontal(PG_FUNCTION_ARGS);
+extern Datum lseg_eq(PG_FUNCTION_ARGS);
+extern Datum be_lo_truncate(PG_FUNCTION_ARGS);
+extern Datum textlike_support(PG_FUNCTION_ARGS);
+extern Datum texticregexeq_support(PG_FUNCTION_ARGS);
+extern Datum texticlike_support(PG_FUNCTION_ARGS);
+extern Datum timestamptz_izone(PG_FUNCTION_ARGS);
+extern Datum gist_point_compress(PG_FUNCTION_ARGS);
+extern Datum aclitemin(PG_FUNCTION_ARGS);
+extern Datum aclitemout(PG_FUNCTION_ARGS);
+extern Datum aclinsert(PG_FUNCTION_ARGS);
+extern Datum aclremove(PG_FUNCTION_ARGS);
+extern Datum aclcontains(PG_FUNCTION_ARGS);
+extern Datum getdatabaseencoding(PG_FUNCTION_ARGS);
+extern Datum bpcharin(PG_FUNCTION_ARGS);
+extern Datum bpcharout(PG_FUNCTION_ARGS);
+extern Datum varcharin(PG_FUNCTION_ARGS);
+extern Datum varcharout(PG_FUNCTION_ARGS);
+extern Datum bpchareq(PG_FUNCTION_ARGS);
+extern Datum bpcharlt(PG_FUNCTION_ARGS);
+extern Datum bpcharle(PG_FUNCTION_ARGS);
+extern Datum bpchargt(PG_FUNCTION_ARGS);
+extern Datum bpcharge(PG_FUNCTION_ARGS);
+extern Datum bpcharne(PG_FUNCTION_ARGS);
+extern Datum aclitem_eq(PG_FUNCTION_ARGS);
+extern Datum bpchar_larger(PG_FUNCTION_ARGS);
+extern Datum bpchar_smaller(PG_FUNCTION_ARGS);
+extern Datum pg_prepared_xact(PG_FUNCTION_ARGS);
+extern Datum generate_series_step_int4(PG_FUNCTION_ARGS);
+extern Datum generate_series_int4(PG_FUNCTION_ARGS);
+extern Datum generate_series_step_int8(PG_FUNCTION_ARGS);
+extern Datum generate_series_int8(PG_FUNCTION_ARGS);
+extern Datum bpcharcmp(PG_FUNCTION_ARGS);
+extern Datum text_regclass(PG_FUNCTION_ARGS);
+extern Datum hashbpchar(PG_FUNCTION_ARGS);
+extern Datum format_type(PG_FUNCTION_ARGS);
+extern Datum date_in(PG_FUNCTION_ARGS);
+extern Datum date_out(PG_FUNCTION_ARGS);
+extern Datum date_eq(PG_FUNCTION_ARGS);
+extern Datum date_lt(PG_FUNCTION_ARGS);
+extern Datum date_le(PG_FUNCTION_ARGS);
+extern Datum date_gt(PG_FUNCTION_ARGS);
+extern Datum date_ge(PG_FUNCTION_ARGS);
+extern Datum date_ne(PG_FUNCTION_ARGS);
+extern Datum date_cmp(PG_FUNCTION_ARGS);
+extern Datum time_lt(PG_FUNCTION_ARGS);
+extern Datum time_le(PG_FUNCTION_ARGS);
+extern Datum time_gt(PG_FUNCTION_ARGS);
+extern Datum time_ge(PG_FUNCTION_ARGS);
+extern Datum time_ne(PG_FUNCTION_ARGS);
+extern Datum time_cmp(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_wal(PG_FUNCTION_ARGS);
+extern Datum pg_get_wal_replay_pause_state(PG_FUNCTION_ARGS);
+extern Datum date_larger(PG_FUNCTION_ARGS);
+extern Datum date_smaller(PG_FUNCTION_ARGS);
+extern Datum date_mi(PG_FUNCTION_ARGS);
+extern Datum date_pli(PG_FUNCTION_ARGS);
+extern Datum date_mii(PG_FUNCTION_ARGS);
+extern Datum time_in(PG_FUNCTION_ARGS);
+extern Datum time_out(PG_FUNCTION_ARGS);
+extern Datum time_eq(PG_FUNCTION_ARGS);
+extern Datum circle_add_pt(PG_FUNCTION_ARGS);
+extern Datum circle_sub_pt(PG_FUNCTION_ARGS);
+extern Datum circle_mul_pt(PG_FUNCTION_ARGS);
+extern Datum circle_div_pt(PG_FUNCTION_ARGS);
+extern Datum timestamptz_in(PG_FUNCTION_ARGS);
+extern Datum timestamptz_out(PG_FUNCTION_ARGS);
+extern Datum timestamp_eq(PG_FUNCTION_ARGS);
+extern Datum timestamp_ne(PG_FUNCTION_ARGS);
+extern Datum timestamp_lt(PG_FUNCTION_ARGS);
+extern Datum timestamp_le(PG_FUNCTION_ARGS);
+extern Datum timestamp_ge(PG_FUNCTION_ARGS);
+extern Datum timestamp_gt(PG_FUNCTION_ARGS);
+extern Datum float8_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamptz_zone(PG_FUNCTION_ARGS);
+extern Datum interval_in(PG_FUNCTION_ARGS);
+extern Datum interval_out(PG_FUNCTION_ARGS);
+extern Datum interval_eq(PG_FUNCTION_ARGS);
+extern Datum interval_ne(PG_FUNCTION_ARGS);
+extern Datum interval_lt(PG_FUNCTION_ARGS);
+extern Datum interval_le(PG_FUNCTION_ARGS);
+extern Datum interval_ge(PG_FUNCTION_ARGS);
+extern Datum interval_gt(PG_FUNCTION_ARGS);
+extern Datum interval_um(PG_FUNCTION_ARGS);
+extern Datum interval_pl(PG_FUNCTION_ARGS);
+extern Datum interval_mi(PG_FUNCTION_ARGS);
+extern Datum timestamptz_part(PG_FUNCTION_ARGS);
+extern Datum interval_part(PG_FUNCTION_ARGS);
+extern Datum network_subset_support(PG_FUNCTION_ARGS);
+extern Datum date_timestamptz(PG_FUNCTION_ARGS);
+extern Datum interval_justify_hours(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_exists_tz(PG_FUNCTION_ARGS);
+extern Datum timestamptz_date(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_query_tz(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_query_array_tz(PG_FUNCTION_ARGS);
+extern Datum xid_age(PG_FUNCTION_ARGS);
+extern Datum timestamp_mi(PG_FUNCTION_ARGS);
+extern Datum timestamptz_pl_interval(PG_FUNCTION_ARGS);
+extern Datum timestamptz_mi_interval(PG_FUNCTION_ARGS);
+extern Datum generate_subscripts(PG_FUNCTION_ARGS);
+extern Datum generate_subscripts_nodir(PG_FUNCTION_ARGS);
+extern Datum array_fill(PG_FUNCTION_ARGS);
+extern Datum dlog10(PG_FUNCTION_ARGS);
+extern Datum timestamp_smaller(PG_FUNCTION_ARGS);
+extern Datum timestamp_larger(PG_FUNCTION_ARGS);
+extern Datum interval_smaller(PG_FUNCTION_ARGS);
+extern Datum interval_larger(PG_FUNCTION_ARGS);
+extern Datum timestamptz_age(PG_FUNCTION_ARGS);
+extern Datum interval_scale(PG_FUNCTION_ARGS);
+extern Datum timestamptz_trunc(PG_FUNCTION_ARGS);
+extern Datum interval_trunc(PG_FUNCTION_ARGS);
+extern Datum int8inc(PG_FUNCTION_ARGS);
+extern Datum int8abs(PG_FUNCTION_ARGS);
+extern Datum int8larger(PG_FUNCTION_ARGS);
+extern Datum int8smaller(PG_FUNCTION_ARGS);
+extern Datum texticregexeq(PG_FUNCTION_ARGS);
+extern Datum texticregexne(PG_FUNCTION_ARGS);
+extern Datum nameicregexeq(PG_FUNCTION_ARGS);
+extern Datum nameicregexne(PG_FUNCTION_ARGS);
+extern Datum boolin(PG_FUNCTION_ARGS);
+extern Datum boolout(PG_FUNCTION_ARGS);
+extern Datum byteain(PG_FUNCTION_ARGS);
+extern Datum charin(PG_FUNCTION_ARGS);
+extern Datum charlt(PG_FUNCTION_ARGS);
+extern Datum unique_key_recheck(PG_FUNCTION_ARGS);
+extern Datum int4abs(PG_FUNCTION_ARGS);
+extern Datum nameregexne(PG_FUNCTION_ARGS);
+extern Datum int2abs(PG_FUNCTION_ARGS);
+extern Datum textregexeq(PG_FUNCTION_ARGS);
+extern Datum textregexne(PG_FUNCTION_ARGS);
+extern Datum textlen(PG_FUNCTION_ARGS);
+extern Datum textcat(PG_FUNCTION_ARGS);
+extern Datum PG_char_to_encoding(PG_FUNCTION_ARGS);
+extern Datum tidne(PG_FUNCTION_ARGS);
+extern Datum cidr_in(PG_FUNCTION_ARGS);
+extern Datum parse_ident(PG_FUNCTION_ARGS);
+extern Datum pg_column_size(PG_FUNCTION_ARGS);
+extern Datum overlaps_timetz(PG_FUNCTION_ARGS);
+extern Datum datetime_timestamp(PG_FUNCTION_ARGS);
+extern Datum timetz_part(PG_FUNCTION_ARGS);
+extern Datum int84pl(PG_FUNCTION_ARGS);
+extern Datum int84mi(PG_FUNCTION_ARGS);
+extern Datum int84mul(PG_FUNCTION_ARGS);
+extern Datum int84div(PG_FUNCTION_ARGS);
+extern Datum int48pl(PG_FUNCTION_ARGS);
+extern Datum int48mi(PG_FUNCTION_ARGS);
+extern Datum int48mul(PG_FUNCTION_ARGS);
+extern Datum int48div(PG_FUNCTION_ARGS);
+extern Datum quote_ident(PG_FUNCTION_ARGS);
+extern Datum quote_literal(PG_FUNCTION_ARGS);
+extern Datum timestamptz_trunc_zone(PG_FUNCTION_ARGS);
+extern Datum array_fill_with_lower_bounds(PG_FUNCTION_ARGS);
+extern Datum i8tooid(PG_FUNCTION_ARGS);
+extern Datum oidtoi8(PG_FUNCTION_ARGS);
+extern Datum quote_nullable(PG_FUNCTION_ARGS);
+extern Datum suppress_redundant_updates_trigger(PG_FUNCTION_ARGS);
+extern Datum tideq(PG_FUNCTION_ARGS);
+extern Datum multirange_unnest(PG_FUNCTION_ARGS);
+extern Datum currtid_byrelname(PG_FUNCTION_ARGS);
+extern Datum interval_justify_days(PG_FUNCTION_ARGS);
+extern Datum datetimetz_timestamptz(PG_FUNCTION_ARGS);
+extern Datum now(PG_FUNCTION_ARGS);
+extern Datum positionsel(PG_FUNCTION_ARGS);
+extern Datum positionjoinsel(PG_FUNCTION_ARGS);
+extern Datum contsel(PG_FUNCTION_ARGS);
+extern Datum contjoinsel(PG_FUNCTION_ARGS);
+extern Datum overlaps_timestamp(PG_FUNCTION_ARGS);
+extern Datum overlaps_time(PG_FUNCTION_ARGS);
+extern Datum timestamp_in(PG_FUNCTION_ARGS);
+extern Datum timestamp_out(PG_FUNCTION_ARGS);
+extern Datum timestamp_cmp(PG_FUNCTION_ARGS);
+extern Datum interval_cmp(PG_FUNCTION_ARGS);
+extern Datum timestamp_time(PG_FUNCTION_ARGS);
+extern Datum bpcharlen(PG_FUNCTION_ARGS);
+extern Datum interval_div(PG_FUNCTION_ARGS);
+extern Datum oidvectortypes(PG_FUNCTION_ARGS);
+extern Datum timetz_in(PG_FUNCTION_ARGS);
+extern Datum timetz_out(PG_FUNCTION_ARGS);
+extern Datum timetz_eq(PG_FUNCTION_ARGS);
+extern Datum timetz_ne(PG_FUNCTION_ARGS);
+extern Datum timetz_lt(PG_FUNCTION_ARGS);
+extern Datum timetz_le(PG_FUNCTION_ARGS);
+extern Datum timetz_ge(PG_FUNCTION_ARGS);
+extern Datum timetz_gt(PG_FUNCTION_ARGS);
+extern Datum timetz_cmp(PG_FUNCTION_ARGS);
+extern Datum network_hostmask(PG_FUNCTION_ARGS);
+extern Datum textregexeq_support(PG_FUNCTION_ARGS);
+extern Datum makeaclitem(PG_FUNCTION_ARGS);
+extern Datum time_interval(PG_FUNCTION_ARGS);
+extern Datum pg_lock_status(PG_FUNCTION_ARGS);
+extern Datum date_finite(PG_FUNCTION_ARGS);
+extern Datum textoctetlen(PG_FUNCTION_ARGS);
+extern Datum bpcharoctetlen(PG_FUNCTION_ARGS);
+extern Datum numeric_fac(PG_FUNCTION_ARGS);
+extern Datum time_larger(PG_FUNCTION_ARGS);
+extern Datum time_smaller(PG_FUNCTION_ARGS);
+extern Datum timetz_larger(PG_FUNCTION_ARGS);
+extern Datum timetz_smaller(PG_FUNCTION_ARGS);
+extern Datum time_part(PG_FUNCTION_ARGS);
+extern Datum pg_get_constraintdef(PG_FUNCTION_ARGS);
+extern Datum timestamptz_timetz(PG_FUNCTION_ARGS);
+extern Datum timestamp_finite(PG_FUNCTION_ARGS);
+extern Datum interval_finite(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_start(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_client_addr(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_client_port(PG_FUNCTION_ARGS);
+extern Datum current_schema(PG_FUNCTION_ARGS);
+extern Datum current_schemas(PG_FUNCTION_ARGS);
+extern Datum textoverlay(PG_FUNCTION_ARGS);
+extern Datum textoverlay_no_len(PG_FUNCTION_ARGS);
+extern Datum line_parallel(PG_FUNCTION_ARGS);
+extern Datum line_perp(PG_FUNCTION_ARGS);
+extern Datum line_vertical(PG_FUNCTION_ARGS);
+extern Datum line_horizontal(PG_FUNCTION_ARGS);
+extern Datum circle_center(PG_FUNCTION_ARGS);
+extern Datum interval_time(PG_FUNCTION_ARGS);
+extern Datum points_box(PG_FUNCTION_ARGS);
+extern Datum box_add(PG_FUNCTION_ARGS);
+extern Datum box_sub(PG_FUNCTION_ARGS);
+extern Datum box_mul(PG_FUNCTION_ARGS);
+extern Datum box_div(PG_FUNCTION_ARGS);
+extern Datum cidr_out(PG_FUNCTION_ARGS);
+extern Datum poly_contain_pt(PG_FUNCTION_ARGS);
+extern Datum pt_contained_poly(PG_FUNCTION_ARGS);
+extern Datum path_isclosed(PG_FUNCTION_ARGS);
+extern Datum path_isopen(PG_FUNCTION_ARGS);
+extern Datum path_npoints(PG_FUNCTION_ARGS);
+extern Datum path_close(PG_FUNCTION_ARGS);
+extern Datum path_open(PG_FUNCTION_ARGS);
+extern Datum path_add(PG_FUNCTION_ARGS);
+extern Datum path_add_pt(PG_FUNCTION_ARGS);
+extern Datum path_sub_pt(PG_FUNCTION_ARGS);
+extern Datum path_mul_pt(PG_FUNCTION_ARGS);
+extern Datum path_div_pt(PG_FUNCTION_ARGS);
+extern Datum construct_point(PG_FUNCTION_ARGS);
+extern Datum point_add(PG_FUNCTION_ARGS);
+extern Datum point_sub(PG_FUNCTION_ARGS);
+extern Datum point_mul(PG_FUNCTION_ARGS);
+extern Datum point_div(PG_FUNCTION_ARGS);
+extern Datum poly_npoints(PG_FUNCTION_ARGS);
+extern Datum poly_box(PG_FUNCTION_ARGS);
+extern Datum poly_path(PG_FUNCTION_ARGS);
+extern Datum box_poly(PG_FUNCTION_ARGS);
+extern Datum path_poly(PG_FUNCTION_ARGS);
+extern Datum circle_in(PG_FUNCTION_ARGS);
+extern Datum circle_out(PG_FUNCTION_ARGS);
+extern Datum circle_same(PG_FUNCTION_ARGS);
+extern Datum circle_contain(PG_FUNCTION_ARGS);
+extern Datum circle_left(PG_FUNCTION_ARGS);
+extern Datum circle_overleft(PG_FUNCTION_ARGS);
+extern Datum circle_overright(PG_FUNCTION_ARGS);
+extern Datum circle_right(PG_FUNCTION_ARGS);
+extern Datum circle_contained(PG_FUNCTION_ARGS);
+extern Datum circle_overlap(PG_FUNCTION_ARGS);
+extern Datum circle_below(PG_FUNCTION_ARGS);
+extern Datum circle_above(PG_FUNCTION_ARGS);
+extern Datum circle_eq(PG_FUNCTION_ARGS);
+extern Datum circle_ne(PG_FUNCTION_ARGS);
+extern Datum circle_lt(PG_FUNCTION_ARGS);
+extern Datum circle_gt(PG_FUNCTION_ARGS);
+extern Datum circle_le(PG_FUNCTION_ARGS);
+extern Datum circle_ge(PG_FUNCTION_ARGS);
+extern Datum circle_area(PG_FUNCTION_ARGS);
+extern Datum circle_diameter(PG_FUNCTION_ARGS);
+extern Datum circle_radius(PG_FUNCTION_ARGS);
+extern Datum circle_distance(PG_FUNCTION_ARGS);
+extern Datum cr_circle(PG_FUNCTION_ARGS);
+extern Datum poly_circle(PG_FUNCTION_ARGS);
+extern Datum circle_poly(PG_FUNCTION_ARGS);
+extern Datum dist_pc(PG_FUNCTION_ARGS);
+extern Datum circle_contain_pt(PG_FUNCTION_ARGS);
+extern Datum pt_contained_circle(PG_FUNCTION_ARGS);
+extern Datum box_circle(PG_FUNCTION_ARGS);
+extern Datum circle_box(PG_FUNCTION_ARGS);
+extern Datum lseg_ne(PG_FUNCTION_ARGS);
+extern Datum lseg_lt(PG_FUNCTION_ARGS);
+extern Datum lseg_le(PG_FUNCTION_ARGS);
+extern Datum lseg_gt(PG_FUNCTION_ARGS);
+extern Datum lseg_ge(PG_FUNCTION_ARGS);
+extern Datum lseg_length(PG_FUNCTION_ARGS);
+extern Datum close_ls(PG_FUNCTION_ARGS);
+extern Datum close_lseg(PG_FUNCTION_ARGS);
+extern Datum line_in(PG_FUNCTION_ARGS);
+extern Datum line_out(PG_FUNCTION_ARGS);
+extern Datum line_eq(PG_FUNCTION_ARGS);
+extern Datum line_construct_pp(PG_FUNCTION_ARGS);
+extern Datum line_interpt(PG_FUNCTION_ARGS);
+extern Datum line_intersect(PG_FUNCTION_ARGS);
+extern Datum bit_in(PG_FUNCTION_ARGS);
+extern Datum bit_out(PG_FUNCTION_ARGS);
+extern Datum pg_get_ruledef(PG_FUNCTION_ARGS);
+extern Datum nextval_oid(PG_FUNCTION_ARGS);
+extern Datum currval_oid(PG_FUNCTION_ARGS);
+extern Datum setval_oid(PG_FUNCTION_ARGS);
+extern Datum varbit_in(PG_FUNCTION_ARGS);
+extern Datum varbit_out(PG_FUNCTION_ARGS);
+extern Datum biteq(PG_FUNCTION_ARGS);
+extern Datum bitne(PG_FUNCTION_ARGS);
+extern Datum bitge(PG_FUNCTION_ARGS);
+extern Datum bitgt(PG_FUNCTION_ARGS);
+extern Datum bitle(PG_FUNCTION_ARGS);
+extern Datum bitlt(PG_FUNCTION_ARGS);
+extern Datum bitcmp(PG_FUNCTION_ARGS);
+extern Datum PG_encoding_to_char(PG_FUNCTION_ARGS);
+extern Datum drandom(PG_FUNCTION_ARGS);
+extern Datum setseed(PG_FUNCTION_ARGS);
+extern Datum dasin(PG_FUNCTION_ARGS);
+extern Datum dacos(PG_FUNCTION_ARGS);
+extern Datum datan(PG_FUNCTION_ARGS);
+extern Datum datan2(PG_FUNCTION_ARGS);
+extern Datum dsin(PG_FUNCTION_ARGS);
+extern Datum dcos(PG_FUNCTION_ARGS);
+extern Datum dtan(PG_FUNCTION_ARGS);
+extern Datum dcot(PG_FUNCTION_ARGS);
+extern Datum degrees(PG_FUNCTION_ARGS);
+extern Datum radians(PG_FUNCTION_ARGS);
+extern Datum dpi(PG_FUNCTION_ARGS);
+extern Datum interval_mul(PG_FUNCTION_ARGS);
+extern Datum pg_typeof(PG_FUNCTION_ARGS);
+extern Datum ascii(PG_FUNCTION_ARGS);
+extern Datum chr(PG_FUNCTION_ARGS);
+extern Datum repeat(PG_FUNCTION_ARGS);
+extern Datum similar_escape(PG_FUNCTION_ARGS);
+extern Datum mul_d_interval(PG_FUNCTION_ARGS);
+extern Datum texticlike(PG_FUNCTION_ARGS);
+extern Datum texticnlike(PG_FUNCTION_ARGS);
+extern Datum nameiclike(PG_FUNCTION_ARGS);
+extern Datum nameicnlike(PG_FUNCTION_ARGS);
+extern Datum like_escape(PG_FUNCTION_ARGS);
+extern Datum oidgt(PG_FUNCTION_ARGS);
+extern Datum oidge(PG_FUNCTION_ARGS);
+extern Datum pg_get_viewdef_name(PG_FUNCTION_ARGS);
+extern Datum pg_get_viewdef(PG_FUNCTION_ARGS);
+extern Datum pg_get_userbyid(PG_FUNCTION_ARGS);
+extern Datum pg_get_indexdef(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_check_ins(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_check_upd(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_cascade_del(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_cascade_upd(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_restrict_del(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_restrict_upd(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_setnull_del(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_setnull_upd(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_setdefault_del(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_setdefault_upd(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_noaction_del(PG_FUNCTION_ARGS);
+extern Datum RI_FKey_noaction_upd(PG_FUNCTION_ARGS);
+extern Datum pg_get_triggerdef(PG_FUNCTION_ARGS);
+extern Datum pg_get_serial_sequence(PG_FUNCTION_ARGS);
+extern Datum bit_and(PG_FUNCTION_ARGS);
+extern Datum bit_or(PG_FUNCTION_ARGS);
+extern Datum bitxor(PG_FUNCTION_ARGS);
+extern Datum bitnot(PG_FUNCTION_ARGS);
+extern Datum bitshiftleft(PG_FUNCTION_ARGS);
+extern Datum bitshiftright(PG_FUNCTION_ARGS);
+extern Datum bitcat(PG_FUNCTION_ARGS);
+extern Datum bitsubstr(PG_FUNCTION_ARGS);
+extern Datum bitlength(PG_FUNCTION_ARGS);
+extern Datum bitoctetlength(PG_FUNCTION_ARGS);
+extern Datum bitfromint4(PG_FUNCTION_ARGS);
+extern Datum bittoint4(PG_FUNCTION_ARGS);
+extern Datum bit(PG_FUNCTION_ARGS);
+extern Datum pg_get_keywords(PG_FUNCTION_ARGS);
+extern Datum varbit(PG_FUNCTION_ARGS);
+extern Datum time_hash(PG_FUNCTION_ARGS);
+extern Datum aclexplode(PG_FUNCTION_ARGS);
+extern Datum time_mi_time(PG_FUNCTION_ARGS);
+extern Datum boolle(PG_FUNCTION_ARGS);
+extern Datum boolge(PG_FUNCTION_ARGS);
+extern Datum btboolcmp(PG_FUNCTION_ARGS);
+extern Datum timetz_hash(PG_FUNCTION_ARGS);
+extern Datum interval_hash(PG_FUNCTION_ARGS);
+extern Datum bitposition(PG_FUNCTION_ARGS);
+extern Datum bitsubstr_no_len(PG_FUNCTION_ARGS);
+extern Datum numeric_in(PG_FUNCTION_ARGS);
+extern Datum numeric_out(PG_FUNCTION_ARGS);
+extern Datum numeric(PG_FUNCTION_ARGS);
+extern Datum numeric_abs(PG_FUNCTION_ARGS);
+extern Datum numeric_sign(PG_FUNCTION_ARGS);
+extern Datum numeric_round(PG_FUNCTION_ARGS);
+extern Datum numeric_trunc(PG_FUNCTION_ARGS);
+extern Datum numeric_ceil(PG_FUNCTION_ARGS);
+extern Datum numeric_floor(PG_FUNCTION_ARGS);
+extern Datum length_in_encoding(PG_FUNCTION_ARGS);
+extern Datum pg_convert_from(PG_FUNCTION_ARGS);
+extern Datum inet_to_cidr(PG_FUNCTION_ARGS);
+extern Datum pg_get_expr(PG_FUNCTION_ARGS);
+extern Datum pg_convert_to(PG_FUNCTION_ARGS);
+extern Datum numeric_eq(PG_FUNCTION_ARGS);
+extern Datum numeric_ne(PG_FUNCTION_ARGS);
+extern Datum numeric_gt(PG_FUNCTION_ARGS);
+extern Datum numeric_ge(PG_FUNCTION_ARGS);
+extern Datum numeric_lt(PG_FUNCTION_ARGS);
+extern Datum numeric_le(PG_FUNCTION_ARGS);
+extern Datum numeric_add(PG_FUNCTION_ARGS);
+extern Datum numeric_sub(PG_FUNCTION_ARGS);
+extern Datum numeric_mul(PG_FUNCTION_ARGS);
+extern Datum numeric_div(PG_FUNCTION_ARGS);
+extern Datum numeric_mod(PG_FUNCTION_ARGS);
+extern Datum numeric_sqrt(PG_FUNCTION_ARGS);
+extern Datum numeric_exp(PG_FUNCTION_ARGS);
+extern Datum numeric_ln(PG_FUNCTION_ARGS);
+extern Datum numeric_log(PG_FUNCTION_ARGS);
+extern Datum numeric_power(PG_FUNCTION_ARGS);
+extern Datum int4_numeric(PG_FUNCTION_ARGS);
+extern Datum float4_numeric(PG_FUNCTION_ARGS);
+extern Datum float8_numeric(PG_FUNCTION_ARGS);
+extern Datum numeric_int4(PG_FUNCTION_ARGS);
+extern Datum numeric_float4(PG_FUNCTION_ARGS);
+extern Datum numeric_float8(PG_FUNCTION_ARGS);
+extern Datum time_pl_interval(PG_FUNCTION_ARGS);
+extern Datum time_mi_interval(PG_FUNCTION_ARGS);
+extern Datum timetz_pl_interval(PG_FUNCTION_ARGS);
+extern Datum timetz_mi_interval(PG_FUNCTION_ARGS);
+extern Datum numeric_inc(PG_FUNCTION_ARGS);
+extern Datum setval3_oid(PG_FUNCTION_ARGS);
+extern Datum numeric_smaller(PG_FUNCTION_ARGS);
+extern Datum numeric_larger(PG_FUNCTION_ARGS);
+extern Datum interval_to_char(PG_FUNCTION_ARGS);
+extern Datum numeric_cmp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_to_char(PG_FUNCTION_ARGS);
+extern Datum numeric_uminus(PG_FUNCTION_ARGS);
+extern Datum numeric_to_char(PG_FUNCTION_ARGS);
+extern Datum int4_to_char(PG_FUNCTION_ARGS);
+extern Datum int8_to_char(PG_FUNCTION_ARGS);
+extern Datum float4_to_char(PG_FUNCTION_ARGS);
+extern Datum float8_to_char(PG_FUNCTION_ARGS);
+extern Datum numeric_to_number(PG_FUNCTION_ARGS);
+extern Datum to_timestamp(PG_FUNCTION_ARGS);
+extern Datum numeric_int8(PG_FUNCTION_ARGS);
+extern Datum to_date(PG_FUNCTION_ARGS);
+extern Datum int8_numeric(PG_FUNCTION_ARGS);
+extern Datum int2_numeric(PG_FUNCTION_ARGS);
+extern Datum numeric_int2(PG_FUNCTION_ARGS);
+extern Datum oidin(PG_FUNCTION_ARGS);
+extern Datum oidout(PG_FUNCTION_ARGS);
+extern Datum pg_convert(PG_FUNCTION_ARGS);
+extern Datum iclikesel(PG_FUNCTION_ARGS);
+extern Datum icnlikesel(PG_FUNCTION_ARGS);
+extern Datum iclikejoinsel(PG_FUNCTION_ARGS);
+extern Datum icnlikejoinsel(PG_FUNCTION_ARGS);
+extern Datum regexeqsel(PG_FUNCTION_ARGS);
+extern Datum likesel(PG_FUNCTION_ARGS);
+extern Datum icregexeqsel(PG_FUNCTION_ARGS);
+extern Datum regexnesel(PG_FUNCTION_ARGS);
+extern Datum nlikesel(PG_FUNCTION_ARGS);
+extern Datum icregexnesel(PG_FUNCTION_ARGS);
+extern Datum regexeqjoinsel(PG_FUNCTION_ARGS);
+extern Datum likejoinsel(PG_FUNCTION_ARGS);
+extern Datum icregexeqjoinsel(PG_FUNCTION_ARGS);
+extern Datum regexnejoinsel(PG_FUNCTION_ARGS);
+extern Datum nlikejoinsel(PG_FUNCTION_ARGS);
+extern Datum icregexnejoinsel(PG_FUNCTION_ARGS);
+extern Datum float8_avg(PG_FUNCTION_ARGS);
+extern Datum float8_var_samp(PG_FUNCTION_ARGS);
+extern Datum float8_stddev_samp(PG_FUNCTION_ARGS);
+extern Datum numeric_accum(PG_FUNCTION_ARGS);
+extern Datum int2_accum(PG_FUNCTION_ARGS);
+extern Datum int4_accum(PG_FUNCTION_ARGS);
+extern Datum int8_accum(PG_FUNCTION_ARGS);
+extern Datum numeric_avg(PG_FUNCTION_ARGS);
+extern Datum numeric_var_samp(PG_FUNCTION_ARGS);
+extern Datum numeric_stddev_samp(PG_FUNCTION_ARGS);
+extern Datum int2_sum(PG_FUNCTION_ARGS);
+extern Datum int4_sum(PG_FUNCTION_ARGS);
+extern Datum int8_sum(PG_FUNCTION_ARGS);
+extern Datum interval_accum(PG_FUNCTION_ARGS);
+extern Datum interval_avg(PG_FUNCTION_ARGS);
+extern Datum to_ascii_default(PG_FUNCTION_ARGS);
+extern Datum to_ascii_enc(PG_FUNCTION_ARGS);
+extern Datum to_ascii_encname(PG_FUNCTION_ARGS);
+extern Datum int28eq(PG_FUNCTION_ARGS);
+extern Datum int28ne(PG_FUNCTION_ARGS);
+extern Datum int28lt(PG_FUNCTION_ARGS);
+extern Datum int28gt(PG_FUNCTION_ARGS);
+extern Datum int28le(PG_FUNCTION_ARGS);
+extern Datum int28ge(PG_FUNCTION_ARGS);
+extern Datum int82eq(PG_FUNCTION_ARGS);
+extern Datum int82ne(PG_FUNCTION_ARGS);
+extern Datum int82lt(PG_FUNCTION_ARGS);
+extern Datum int82gt(PG_FUNCTION_ARGS);
+extern Datum int82le(PG_FUNCTION_ARGS);
+extern Datum int82ge(PG_FUNCTION_ARGS);
+extern Datum int2and(PG_FUNCTION_ARGS);
+extern Datum int2or(PG_FUNCTION_ARGS);
+extern Datum int2xor(PG_FUNCTION_ARGS);
+extern Datum int2not(PG_FUNCTION_ARGS);
+extern Datum int2shl(PG_FUNCTION_ARGS);
+extern Datum int2shr(PG_FUNCTION_ARGS);
+extern Datum int4and(PG_FUNCTION_ARGS);
+extern Datum int4or(PG_FUNCTION_ARGS);
+extern Datum int4xor(PG_FUNCTION_ARGS);
+extern Datum int4not(PG_FUNCTION_ARGS);
+extern Datum int4shl(PG_FUNCTION_ARGS);
+extern Datum int4shr(PG_FUNCTION_ARGS);
+extern Datum int8and(PG_FUNCTION_ARGS);
+extern Datum int8or(PG_FUNCTION_ARGS);
+extern Datum int8xor(PG_FUNCTION_ARGS);
+extern Datum int8not(PG_FUNCTION_ARGS);
+extern Datum int8shl(PG_FUNCTION_ARGS);
+extern Datum int8shr(PG_FUNCTION_ARGS);
+extern Datum int8up(PG_FUNCTION_ARGS);
+extern Datum int2up(PG_FUNCTION_ARGS);
+extern Datum int4up(PG_FUNCTION_ARGS);
+extern Datum float4up(PG_FUNCTION_ARGS);
+extern Datum float8up(PG_FUNCTION_ARGS);
+extern Datum numeric_uplus(PG_FUNCTION_ARGS);
+extern Datum has_table_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_table_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_table_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_table_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_table_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_table_privilege_id(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_numscans(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_returned(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_fetched(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_inserted(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_updated(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_deleted(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_blocks_fetched(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_blocks_hit(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_idset(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_pid(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_dbid(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_userid(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_activity(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_numbackends(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_xact_commit(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_xact_rollback(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_blocks_fetched(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_blocks_hit(PG_FUNCTION_ARGS);
+extern Datum binary_encode(PG_FUNCTION_ARGS);
+extern Datum binary_decode(PG_FUNCTION_ARGS);
+extern Datum byteaeq(PG_FUNCTION_ARGS);
+extern Datum bytealt(PG_FUNCTION_ARGS);
+extern Datum byteale(PG_FUNCTION_ARGS);
+extern Datum byteagt(PG_FUNCTION_ARGS);
+extern Datum byteage(PG_FUNCTION_ARGS);
+extern Datum byteane(PG_FUNCTION_ARGS);
+extern Datum byteacmp(PG_FUNCTION_ARGS);
+extern Datum timestamp_scale(PG_FUNCTION_ARGS);
+extern Datum int2_avg_accum(PG_FUNCTION_ARGS);
+extern Datum int4_avg_accum(PG_FUNCTION_ARGS);
+extern Datum int8_avg(PG_FUNCTION_ARGS);
+extern Datum oidlarger(PG_FUNCTION_ARGS);
+extern Datum oidsmaller(PG_FUNCTION_ARGS);
+extern Datum timestamptz_scale(PG_FUNCTION_ARGS);
+extern Datum time_scale(PG_FUNCTION_ARGS);
+extern Datum timetz_scale(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_hot_updated(PG_FUNCTION_ARGS);
+extern Datum numeric_div_trunc(PG_FUNCTION_ARGS);
+extern Datum similar_to_escape_2(PG_FUNCTION_ARGS);
+extern Datum similar_to_escape_1(PG_FUNCTION_ARGS);
+extern Datum bytealike(PG_FUNCTION_ARGS);
+extern Datum byteanlike(PG_FUNCTION_ARGS);
+extern Datum like_escape_bytea(PG_FUNCTION_ARGS);
+extern Datum byteacat(PG_FUNCTION_ARGS);
+extern Datum bytea_substr(PG_FUNCTION_ARGS);
+extern Datum bytea_substr_no_len(PG_FUNCTION_ARGS);
+extern Datum byteapos(PG_FUNCTION_ARGS);
+extern Datum byteatrim(PG_FUNCTION_ARGS);
+extern Datum timestamptz_time(PG_FUNCTION_ARGS);
+extern Datum timestamp_trunc(PG_FUNCTION_ARGS);
+extern Datum timestamp_part(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_activity(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_query_first_tz(PG_FUNCTION_ARGS);
+extern Datum date_timestamp(PG_FUNCTION_ARGS);
+extern Datum pg_backend_pid(PG_FUNCTION_ARGS);
+extern Datum timestamptz_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamp_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_date(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_match_tz(PG_FUNCTION_ARGS);
+extern Datum timestamp_pl_interval(PG_FUNCTION_ARGS);
+extern Datum timestamp_mi_interval(PG_FUNCTION_ARGS);
+extern Datum pg_conf_load_time(PG_FUNCTION_ARGS);
+extern Datum timetz_zone(PG_FUNCTION_ARGS);
+extern Datum timetz_izone(PG_FUNCTION_ARGS);
+extern Datum timestamp_hash(PG_FUNCTION_ARGS);
+extern Datum timetz_time(PG_FUNCTION_ARGS);
+extern Datum time_timetz(PG_FUNCTION_ARGS);
+extern Datum timestamp_to_char(PG_FUNCTION_ARGS);
+extern Datum timestamp_age(PG_FUNCTION_ARGS);
+extern Datum timestamp_zone(PG_FUNCTION_ARGS);
+extern Datum timestamp_izone(PG_FUNCTION_ARGS);
+extern Datum date_pl_interval(PG_FUNCTION_ARGS);
+extern Datum date_mi_interval(PG_FUNCTION_ARGS);
+extern Datum textregexsubstr(PG_FUNCTION_ARGS);
+extern Datum bitfromint8(PG_FUNCTION_ARGS);
+extern Datum bittoint8(PG_FUNCTION_ARGS);
+extern Datum show_config_by_name(PG_FUNCTION_ARGS);
+extern Datum set_config_by_name(PG_FUNCTION_ARGS);
+extern Datum pg_table_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_type_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_function_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
+extern Datum show_all_settings(PG_FUNCTION_ARGS);
+extern Datum replace_text(PG_FUNCTION_ARGS);
+extern Datum split_part(PG_FUNCTION_ARGS);
+extern Datum to_hex32(PG_FUNCTION_ARGS);
+extern Datum to_hex64(PG_FUNCTION_ARGS);
+extern Datum array_lower(PG_FUNCTION_ARGS);
+extern Datum array_upper(PG_FUNCTION_ARGS);
+extern Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_activity_start(PG_FUNCTION_ARGS);
+extern Datum pg_terminate_backend(PG_FUNCTION_ARGS);
+extern Datum pg_get_functiondef(PG_FUNCTION_ARGS);
+extern Datum pg_column_compression(PG_FUNCTION_ARGS);
+extern Datum pg_stat_force_next_flush(PG_FUNCTION_ARGS);
+extern Datum text_pattern_lt(PG_FUNCTION_ARGS);
+extern Datum text_pattern_le(PG_FUNCTION_ARGS);
+extern Datum pg_get_function_arguments(PG_FUNCTION_ARGS);
+extern Datum text_pattern_ge(PG_FUNCTION_ARGS);
+extern Datum text_pattern_gt(PG_FUNCTION_ARGS);
+extern Datum pg_get_function_result(PG_FUNCTION_ARGS);
+extern Datum bttext_pattern_cmp(PG_FUNCTION_ARGS);
+extern Datum pg_database_size_name(PG_FUNCTION_ARGS);
+extern Datum width_bucket_numeric(PG_FUNCTION_ARGS);
+extern Datum pg_cancel_backend(PG_FUNCTION_ARGS);
+extern Datum pg_backup_start(PG_FUNCTION_ARGS);
+extern Datum bpchar_pattern_lt(PG_FUNCTION_ARGS);
+extern Datum bpchar_pattern_le(PG_FUNCTION_ARGS);
+extern Datum array_length(PG_FUNCTION_ARGS);
+extern Datum bpchar_pattern_ge(PG_FUNCTION_ARGS);
+extern Datum bpchar_pattern_gt(PG_FUNCTION_ARGS);
+extern Datum gist_point_consistent(PG_FUNCTION_ARGS);
+extern Datum btbpchar_pattern_cmp(PG_FUNCTION_ARGS);
+extern Datum has_sequence_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_sequence_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_sequence_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_sequence_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_sequence_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_sequence_privilege_id(PG_FUNCTION_ARGS);
+extern Datum btint48cmp(PG_FUNCTION_ARGS);
+extern Datum btint84cmp(PG_FUNCTION_ARGS);
+extern Datum btint24cmp(PG_FUNCTION_ARGS);
+extern Datum btint42cmp(PG_FUNCTION_ARGS);
+extern Datum btint28cmp(PG_FUNCTION_ARGS);
+extern Datum btint82cmp(PG_FUNCTION_ARGS);
+extern Datum btfloat48cmp(PG_FUNCTION_ARGS);
+extern Datum btfloat84cmp(PG_FUNCTION_ARGS);
+extern Datum inet_client_addr(PG_FUNCTION_ARGS);
+extern Datum inet_client_port(PG_FUNCTION_ARGS);
+extern Datum inet_server_addr(PG_FUNCTION_ARGS);
+extern Datum inet_server_port(PG_FUNCTION_ARGS);
+extern Datum regprocedurein(PG_FUNCTION_ARGS);
+extern Datum regprocedureout(PG_FUNCTION_ARGS);
+extern Datum regoperin(PG_FUNCTION_ARGS);
+extern Datum regoperout(PG_FUNCTION_ARGS);
+extern Datum regoperatorin(PG_FUNCTION_ARGS);
+extern Datum regoperatorout(PG_FUNCTION_ARGS);
+extern Datum regclassin(PG_FUNCTION_ARGS);
+extern Datum regclassout(PG_FUNCTION_ARGS);
+extern Datum regtypein(PG_FUNCTION_ARGS);
+extern Datum regtypeout(PG_FUNCTION_ARGS);
+extern Datum pg_stat_clear_snapshot(PG_FUNCTION_ARGS);
+extern Datum pg_get_function_identity_arguments(PG_FUNCTION_ARGS);
+extern Datum hashtid(PG_FUNCTION_ARGS);
+extern Datum hashtidextended(PG_FUNCTION_ARGS);
+extern Datum fmgr_internal_validator(PG_FUNCTION_ARGS);
+extern Datum fmgr_c_validator(PG_FUNCTION_ARGS);
+extern Datum fmgr_sql_validator(PG_FUNCTION_ARGS);
+extern Datum has_database_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_database_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_database_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_database_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_database_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_database_privilege_id(PG_FUNCTION_ARGS);
+extern Datum has_function_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_function_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_function_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_function_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_function_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_function_privilege_id(PG_FUNCTION_ARGS);
+extern Datum has_language_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_language_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_language_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_language_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_language_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_language_privilege_id(PG_FUNCTION_ARGS);
+extern Datum has_schema_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_schema_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_schema_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_schema_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_schema_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_schema_privilege_id(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset(PG_FUNCTION_ARGS);
+extern Datum pg_get_backend_memory_contexts(PG_FUNCTION_ARGS);
+extern Datum textregexreplace_noopt(PG_FUNCTION_ARGS);
+extern Datum textregexreplace(PG_FUNCTION_ARGS);
+extern Datum pg_total_relation_size(PG_FUNCTION_ARGS);
+extern Datum pg_size_pretty(PG_FUNCTION_ARGS);
+extern Datum pg_options_to_table(PG_FUNCTION_ARGS);
+extern Datum record_in(PG_FUNCTION_ARGS);
+extern Datum record_out(PG_FUNCTION_ARGS);
+extern Datum cstring_in(PG_FUNCTION_ARGS);
+extern Datum cstring_out(PG_FUNCTION_ARGS);
+extern Datum any_in(PG_FUNCTION_ARGS);
+extern Datum any_out(PG_FUNCTION_ARGS);
+extern Datum anyarray_in(PG_FUNCTION_ARGS);
+extern Datum anyarray_out(PG_FUNCTION_ARGS);
+extern Datum void_in(PG_FUNCTION_ARGS);
+extern Datum void_out(PG_FUNCTION_ARGS);
+extern Datum trigger_in(PG_FUNCTION_ARGS);
+extern Datum trigger_out(PG_FUNCTION_ARGS);
+extern Datum language_handler_in(PG_FUNCTION_ARGS);
+extern Datum language_handler_out(PG_FUNCTION_ARGS);
+extern Datum internal_in(PG_FUNCTION_ARGS);
+extern Datum internal_out(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_slru(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset_slru(PG_FUNCTION_ARGS);
+extern Datum dceil(PG_FUNCTION_ARGS);
+extern Datum dfloor(PG_FUNCTION_ARGS);
+extern Datum dsign(PG_FUNCTION_ARGS);
+extern Datum md5_text(PG_FUNCTION_ARGS);
+extern Datum anyelement_in(PG_FUNCTION_ARGS);
+extern Datum anyelement_out(PG_FUNCTION_ARGS);
+extern Datum postgresql_fdw_validator(PG_FUNCTION_ARGS);
+extern Datum pg_encoding_max_length_sql(PG_FUNCTION_ARGS);
+extern Datum md5_bytea(PG_FUNCTION_ARGS);
+extern Datum pg_tablespace_size_oid(PG_FUNCTION_ARGS);
+extern Datum pg_tablespace_size_name(PG_FUNCTION_ARGS);
+extern Datum pg_database_size_oid(PG_FUNCTION_ARGS);
+extern Datum array_unnest(PG_FUNCTION_ARGS);
+extern Datum pg_relation_size(PG_FUNCTION_ARGS);
+extern Datum array_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum array_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum date_lt_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_le_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_eq_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_gt_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_ge_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_ne_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_cmp_timestamp(PG_FUNCTION_ARGS);
+extern Datum date_lt_timestamptz(PG_FUNCTION_ARGS);
+extern Datum date_le_timestamptz(PG_FUNCTION_ARGS);
+extern Datum date_eq_timestamptz(PG_FUNCTION_ARGS);
+extern Datum date_gt_timestamptz(PG_FUNCTION_ARGS);
+extern Datum date_ge_timestamptz(PG_FUNCTION_ARGS);
+extern Datum date_ne_timestamptz(PG_FUNCTION_ARGS);
+extern Datum date_cmp_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_lt_date(PG_FUNCTION_ARGS);
+extern Datum timestamp_le_date(PG_FUNCTION_ARGS);
+extern Datum timestamp_eq_date(PG_FUNCTION_ARGS);
+extern Datum timestamp_gt_date(PG_FUNCTION_ARGS);
+extern Datum timestamp_ge_date(PG_FUNCTION_ARGS);
+extern Datum timestamp_ne_date(PG_FUNCTION_ARGS);
+extern Datum timestamp_cmp_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_lt_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_le_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_eq_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_gt_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_ge_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_ne_date(PG_FUNCTION_ARGS);
+extern Datum timestamptz_cmp_date(PG_FUNCTION_ARGS);
+extern Datum has_tablespace_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_tablespace_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_tablespace_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_tablespace_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_tablespace_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_tablespace_privilege_id(PG_FUNCTION_ARGS);
+extern Datum shell_in(PG_FUNCTION_ARGS);
+extern Datum shell_out(PG_FUNCTION_ARGS);
+extern Datum array_recv(PG_FUNCTION_ARGS);
+extern Datum array_send(PG_FUNCTION_ARGS);
+extern Datum record_recv(PG_FUNCTION_ARGS);
+extern Datum record_send(PG_FUNCTION_ARGS);
+extern Datum int2recv(PG_FUNCTION_ARGS);
+extern Datum int2send(PG_FUNCTION_ARGS);
+extern Datum int4recv(PG_FUNCTION_ARGS);
+extern Datum int4send(PG_FUNCTION_ARGS);
+extern Datum int8recv(PG_FUNCTION_ARGS);
+extern Datum int8send(PG_FUNCTION_ARGS);
+extern Datum int2vectorrecv(PG_FUNCTION_ARGS);
+extern Datum int2vectorsend(PG_FUNCTION_ARGS);
+extern Datum bytearecv(PG_FUNCTION_ARGS);
+extern Datum byteasend(PG_FUNCTION_ARGS);
+extern Datum textrecv(PG_FUNCTION_ARGS);
+extern Datum textsend(PG_FUNCTION_ARGS);
+extern Datum unknownrecv(PG_FUNCTION_ARGS);
+extern Datum unknownsend(PG_FUNCTION_ARGS);
+extern Datum oidrecv(PG_FUNCTION_ARGS);
+extern Datum oidsend(PG_FUNCTION_ARGS);
+extern Datum oidvectorrecv(PG_FUNCTION_ARGS);
+extern Datum oidvectorsend(PG_FUNCTION_ARGS);
+extern Datum namerecv(PG_FUNCTION_ARGS);
+extern Datum namesend(PG_FUNCTION_ARGS);
+extern Datum float4recv(PG_FUNCTION_ARGS);
+extern Datum float4send(PG_FUNCTION_ARGS);
+extern Datum float8recv(PG_FUNCTION_ARGS);
+extern Datum float8send(PG_FUNCTION_ARGS);
+extern Datum point_recv(PG_FUNCTION_ARGS);
+extern Datum point_send(PG_FUNCTION_ARGS);
+extern Datum bpcharrecv(PG_FUNCTION_ARGS);
+extern Datum bpcharsend(PG_FUNCTION_ARGS);
+extern Datum varcharrecv(PG_FUNCTION_ARGS);
+extern Datum varcharsend(PG_FUNCTION_ARGS);
+extern Datum charrecv(PG_FUNCTION_ARGS);
+extern Datum charsend(PG_FUNCTION_ARGS);
+extern Datum boolrecv(PG_FUNCTION_ARGS);
+extern Datum boolsend(PG_FUNCTION_ARGS);
+extern Datum tidrecv(PG_FUNCTION_ARGS);
+extern Datum tidsend(PG_FUNCTION_ARGS);
+extern Datum xidrecv(PG_FUNCTION_ARGS);
+extern Datum xidsend(PG_FUNCTION_ARGS);
+extern Datum cidrecv(PG_FUNCTION_ARGS);
+extern Datum cidsend(PG_FUNCTION_ARGS);
+extern Datum regprocrecv(PG_FUNCTION_ARGS);
+extern Datum regprocsend(PG_FUNCTION_ARGS);
+extern Datum regprocedurerecv(PG_FUNCTION_ARGS);
+extern Datum regproceduresend(PG_FUNCTION_ARGS);
+extern Datum regoperrecv(PG_FUNCTION_ARGS);
+extern Datum regopersend(PG_FUNCTION_ARGS);
+extern Datum regoperatorrecv(PG_FUNCTION_ARGS);
+extern Datum regoperatorsend(PG_FUNCTION_ARGS);
+extern Datum regclassrecv(PG_FUNCTION_ARGS);
+extern Datum regclasssend(PG_FUNCTION_ARGS);
+extern Datum regtyperecv(PG_FUNCTION_ARGS);
+extern Datum regtypesend(PG_FUNCTION_ARGS);
+extern Datum bit_recv(PG_FUNCTION_ARGS);
+extern Datum bit_send(PG_FUNCTION_ARGS);
+extern Datum varbit_recv(PG_FUNCTION_ARGS);
+extern Datum varbit_send(PG_FUNCTION_ARGS);
+extern Datum numeric_recv(PG_FUNCTION_ARGS);
+extern Datum numeric_send(PG_FUNCTION_ARGS);
+extern Datum dsinh(PG_FUNCTION_ARGS);
+extern Datum dcosh(PG_FUNCTION_ARGS);
+extern Datum dtanh(PG_FUNCTION_ARGS);
+extern Datum dasinh(PG_FUNCTION_ARGS);
+extern Datum dacosh(PG_FUNCTION_ARGS);
+extern Datum datanh(PG_FUNCTION_ARGS);
+extern Datum date_recv(PG_FUNCTION_ARGS);
+extern Datum date_send(PG_FUNCTION_ARGS);
+extern Datum time_recv(PG_FUNCTION_ARGS);
+extern Datum time_send(PG_FUNCTION_ARGS);
+extern Datum timetz_recv(PG_FUNCTION_ARGS);
+extern Datum timetz_send(PG_FUNCTION_ARGS);
+extern Datum timestamp_recv(PG_FUNCTION_ARGS);
+extern Datum timestamp_send(PG_FUNCTION_ARGS);
+extern Datum timestamptz_recv(PG_FUNCTION_ARGS);
+extern Datum timestamptz_send(PG_FUNCTION_ARGS);
+extern Datum interval_recv(PG_FUNCTION_ARGS);
+extern Datum interval_send(PG_FUNCTION_ARGS);
+extern Datum lseg_recv(PG_FUNCTION_ARGS);
+extern Datum lseg_send(PG_FUNCTION_ARGS);
+extern Datum path_recv(PG_FUNCTION_ARGS);
+extern Datum path_send(PG_FUNCTION_ARGS);
+extern Datum box_recv(PG_FUNCTION_ARGS);
+extern Datum box_send(PG_FUNCTION_ARGS);
+extern Datum poly_recv(PG_FUNCTION_ARGS);
+extern Datum poly_send(PG_FUNCTION_ARGS);
+extern Datum line_recv(PG_FUNCTION_ARGS);
+extern Datum line_send(PG_FUNCTION_ARGS);
+extern Datum circle_recv(PG_FUNCTION_ARGS);
+extern Datum circle_send(PG_FUNCTION_ARGS);
+extern Datum cash_recv(PG_FUNCTION_ARGS);
+extern Datum cash_send(PG_FUNCTION_ARGS);
+extern Datum macaddr_recv(PG_FUNCTION_ARGS);
+extern Datum macaddr_send(PG_FUNCTION_ARGS);
+extern Datum inet_recv(PG_FUNCTION_ARGS);
+extern Datum inet_send(PG_FUNCTION_ARGS);
+extern Datum cidr_recv(PG_FUNCTION_ARGS);
+extern Datum cidr_send(PG_FUNCTION_ARGS);
+extern Datum cstring_recv(PG_FUNCTION_ARGS);
+extern Datum cstring_send(PG_FUNCTION_ARGS);
+extern Datum anyarray_recv(PG_FUNCTION_ARGS);
+extern Datum anyarray_send(PG_FUNCTION_ARGS);
+extern Datum pg_get_ruledef_ext(PG_FUNCTION_ARGS);
+extern Datum pg_get_viewdef_name_ext(PG_FUNCTION_ARGS);
+extern Datum pg_get_viewdef_ext(PG_FUNCTION_ARGS);
+extern Datum pg_get_indexdef_ext(PG_FUNCTION_ARGS);
+extern Datum pg_get_constraintdef_ext(PG_FUNCTION_ARGS);
+extern Datum pg_get_expr_ext(PG_FUNCTION_ARGS);
+extern Datum pg_prepared_statement(PG_FUNCTION_ARGS);
+extern Datum pg_cursor(PG_FUNCTION_ARGS);
+extern Datum float8_var_pop(PG_FUNCTION_ARGS);
+extern Datum float8_stddev_pop(PG_FUNCTION_ARGS);
+extern Datum numeric_var_pop(PG_FUNCTION_ARGS);
+extern Datum booland_statefunc(PG_FUNCTION_ARGS);
+extern Datum boolor_statefunc(PG_FUNCTION_ARGS);
+extern Datum timestamp_lt_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_le_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_eq_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_gt_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_ge_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_ne_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamp_cmp_timestamptz(PG_FUNCTION_ARGS);
+extern Datum timestamptz_lt_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_le_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_eq_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_gt_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_ge_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_ne_timestamp(PG_FUNCTION_ARGS);
+extern Datum timestamptz_cmp_timestamp(PG_FUNCTION_ARGS);
+extern Datum pg_tablespace_databases(PG_FUNCTION_ARGS);
+extern Datum int4_bool(PG_FUNCTION_ARGS);
+extern Datum bool_int4(PG_FUNCTION_ARGS);
+extern Datum lastval(PG_FUNCTION_ARGS);
+extern Datum pg_postmaster_start_time(PG_FUNCTION_ARGS);
+extern Datum pg_blocking_pids(PG_FUNCTION_ARGS);
+extern Datum box_below(PG_FUNCTION_ARGS);
+extern Datum box_overbelow(PG_FUNCTION_ARGS);
+extern Datum box_overabove(PG_FUNCTION_ARGS);
+extern Datum box_above(PG_FUNCTION_ARGS);
+extern Datum poly_below(PG_FUNCTION_ARGS);
+extern Datum poly_overbelow(PG_FUNCTION_ARGS);
+extern Datum poly_overabove(PG_FUNCTION_ARGS);
+extern Datum poly_above(PG_FUNCTION_ARGS);
+extern Datum gist_box_consistent(PG_FUNCTION_ARGS);
+extern Datum jsonb_float8(PG_FUNCTION_ARGS);
+extern Datum gist_box_penalty(PG_FUNCTION_ARGS);
+extern Datum gist_box_picksplit(PG_FUNCTION_ARGS);
+extern Datum gist_box_union(PG_FUNCTION_ARGS);
+extern Datum gist_box_same(PG_FUNCTION_ARGS);
+extern Datum gist_poly_consistent(PG_FUNCTION_ARGS);
+extern Datum gist_poly_compress(PG_FUNCTION_ARGS);
+extern Datum circle_overbelow(PG_FUNCTION_ARGS);
+extern Datum circle_overabove(PG_FUNCTION_ARGS);
+extern Datum gist_circle_consistent(PG_FUNCTION_ARGS);
+extern Datum gist_circle_compress(PG_FUNCTION_ARGS);
+extern Datum numeric_stddev_pop(PG_FUNCTION_ARGS);
+extern Datum domain_in(PG_FUNCTION_ARGS);
+extern Datum domain_recv(PG_FUNCTION_ARGS);
+extern Datum pg_timezone_abbrevs(PG_FUNCTION_ARGS);
+extern Datum xmlexists(PG_FUNCTION_ARGS);
+extern Datum pg_reload_conf(PG_FUNCTION_ARGS);
+extern Datum pg_rotate_logfile_v2(PG_FUNCTION_ARGS);
+extern Datum pg_stat_file_1arg(PG_FUNCTION_ARGS);
+extern Datum pg_read_file_off_len(PG_FUNCTION_ARGS);
+extern Datum pg_ls_dir_1arg(PG_FUNCTION_ARGS);
+extern Datum pg_sleep(PG_FUNCTION_ARGS);
+extern Datum inetnot(PG_FUNCTION_ARGS);
+extern Datum inetand(PG_FUNCTION_ARGS);
+extern Datum inetor(PG_FUNCTION_ARGS);
+extern Datum inetpl(PG_FUNCTION_ARGS);
+extern Datum inetmi_int8(PG_FUNCTION_ARGS);
+extern Datum inetmi(PG_FUNCTION_ARGS);
+extern Datum statement_timestamp(PG_FUNCTION_ARGS);
+extern Datum clock_timestamp(PG_FUNCTION_ARGS);
+extern Datum gin_cmp_prefix(PG_FUNCTION_ARGS);
+extern Datum pg_has_role_name_name(PG_FUNCTION_ARGS);
+extern Datum pg_has_role_name_id(PG_FUNCTION_ARGS);
+extern Datum pg_has_role_id_name(PG_FUNCTION_ARGS);
+extern Datum pg_has_role_id_id(PG_FUNCTION_ARGS);
+extern Datum pg_has_role_name(PG_FUNCTION_ARGS);
+extern Datum pg_has_role_id(PG_FUNCTION_ARGS);
+extern Datum interval_justify_interval(PG_FUNCTION_ARGS);
+extern Datum pg_get_triggerdef_ext(PG_FUNCTION_ARGS);
+extern Datum dasind(PG_FUNCTION_ARGS);
+extern Datum dacosd(PG_FUNCTION_ARGS);
+extern Datum datand(PG_FUNCTION_ARGS);
+extern Datum datan2d(PG_FUNCTION_ARGS);
+extern Datum dsind(PG_FUNCTION_ARGS);
+extern Datum dcosd(PG_FUNCTION_ARGS);
+extern Datum dtand(PG_FUNCTION_ARGS);
+extern Datum dcotd(PG_FUNCTION_ARGS);
+extern Datum pg_backup_stop(PG_FUNCTION_ARGS);
+extern Datum numeric_avg_serialize(PG_FUNCTION_ARGS);
+extern Datum numeric_avg_deserialize(PG_FUNCTION_ARGS);
+extern Datum ginarrayextract(PG_FUNCTION_ARGS);
+extern Datum ginarrayconsistent(PG_FUNCTION_ARGS);
+extern Datum int8_avg_accum(PG_FUNCTION_ARGS);
+extern Datum arrayoverlap(PG_FUNCTION_ARGS);
+extern Datum arraycontains(PG_FUNCTION_ARGS);
+extern Datum arraycontained(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_tuples_returned(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_tuples_fetched(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_tuples_inserted(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_tuples_updated(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_tuples_deleted(PG_FUNCTION_ARGS);
+extern Datum regexp_matches_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_matches(PG_FUNCTION_ARGS);
+extern Datum regexp_split_to_table_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_split_to_table(PG_FUNCTION_ARGS);
+extern Datum regexp_split_to_array_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_split_to_array(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_bgwriter_timed_checkpoints(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_bgwriter_requested_checkpoints(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_bgwriter_buf_written_checkpoints(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_bgwriter_buf_written_clean(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_bgwriter_maxwritten_clean(PG_FUNCTION_ARGS);
+extern Datum ginqueryarrayextract(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_buf_written_backend(PG_FUNCTION_ARGS);
+extern Datum anynonarray_in(PG_FUNCTION_ARGS);
+extern Datum anynonarray_out(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_last_vacuum_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_last_autovacuum_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_last_analyze_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_last_autoanalyze_time(PG_FUNCTION_ARGS);
+extern Datum int8_avg_combine(PG_FUNCTION_ARGS);
+extern Datum int8_avg_serialize(PG_FUNCTION_ARGS);
+extern Datum int8_avg_deserialize(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_wait_event_type(PG_FUNCTION_ARGS);
+extern Datum tidgt(PG_FUNCTION_ARGS);
+extern Datum tidlt(PG_FUNCTION_ARGS);
+extern Datum tidge(PG_FUNCTION_ARGS);
+extern Datum tidle(PG_FUNCTION_ARGS);
+extern Datum bttidcmp(PG_FUNCTION_ARGS);
+extern Datum tidlarger(PG_FUNCTION_ARGS);
+extern Datum tidsmaller(PG_FUNCTION_ARGS);
+extern Datum int8inc_any(PG_FUNCTION_ARGS);
+extern Datum int8inc_float8_float8(PG_FUNCTION_ARGS);
+extern Datum float8_regr_accum(PG_FUNCTION_ARGS);
+extern Datum float8_regr_sxx(PG_FUNCTION_ARGS);
+extern Datum float8_regr_syy(PG_FUNCTION_ARGS);
+extern Datum float8_regr_sxy(PG_FUNCTION_ARGS);
+extern Datum float8_regr_avgx(PG_FUNCTION_ARGS);
+extern Datum float8_regr_avgy(PG_FUNCTION_ARGS);
+extern Datum float8_regr_r2(PG_FUNCTION_ARGS);
+extern Datum float8_regr_slope(PG_FUNCTION_ARGS);
+extern Datum float8_regr_intercept(PG_FUNCTION_ARGS);
+extern Datum float8_covar_pop(PG_FUNCTION_ARGS);
+extern Datum float8_covar_samp(PG_FUNCTION_ARGS);
+extern Datum float8_corr(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_blk_read_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_blk_write_time(PG_FUNCTION_ARGS);
+extern Datum pg_switch_wal(PG_FUNCTION_ARGS);
+extern Datum pg_current_wal_lsn(PG_FUNCTION_ARGS);
+extern Datum pg_walfile_name_offset(PG_FUNCTION_ARGS);
+extern Datum pg_walfile_name(PG_FUNCTION_ARGS);
+extern Datum pg_current_wal_insert_lsn(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_wait_event(PG_FUNCTION_ARGS);
+extern Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
+extern Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
+extern Datum pg_timezone_names(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_xact_start(PG_FUNCTION_ARGS);
+extern Datum numeric_avg_accum(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_buf_alloc(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_live_tuples(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_dead_tuples(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_lock_int8(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_lock_shared_int8(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_lock_int8(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_lock_shared_int8(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_unlock_int8(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_unlock_shared_int8(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_lock_int4(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_lock_shared_int4(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_lock_int4(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_lock_shared_int4(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_unlock_int4(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_unlock_shared_int4(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_unlock_all(PG_FUNCTION_ARGS);
+extern Datum xml_in(PG_FUNCTION_ARGS);
+extern Datum xml_out(PG_FUNCTION_ARGS);
+extern Datum xmlcomment(PG_FUNCTION_ARGS);
+extern Datum texttoxml(PG_FUNCTION_ARGS);
+extern Datum xmlvalidate(PG_FUNCTION_ARGS);
+extern Datum xml_recv(PG_FUNCTION_ARGS);
+extern Datum xml_send(PG_FUNCTION_ARGS);
+extern Datum xmlconcat2(PG_FUNCTION_ARGS);
+extern Datum varbittypmodin(PG_FUNCTION_ARGS);
+extern Datum intervaltypmodin(PG_FUNCTION_ARGS);
+extern Datum intervaltypmodout(PG_FUNCTION_ARGS);
+extern Datum timestamptypmodin(PG_FUNCTION_ARGS);
+extern Datum timestamptypmodout(PG_FUNCTION_ARGS);
+extern Datum timestamptztypmodin(PG_FUNCTION_ARGS);
+extern Datum timestamptztypmodout(PG_FUNCTION_ARGS);
+extern Datum timetypmodin(PG_FUNCTION_ARGS);
+extern Datum timetypmodout(PG_FUNCTION_ARGS);
+extern Datum timetztypmodin(PG_FUNCTION_ARGS);
+extern Datum timetztypmodout(PG_FUNCTION_ARGS);
+extern Datum bpchartypmodin(PG_FUNCTION_ARGS);
+extern Datum bpchartypmodout(PG_FUNCTION_ARGS);
+extern Datum varchartypmodin(PG_FUNCTION_ARGS);
+extern Datum varchartypmodout(PG_FUNCTION_ARGS);
+extern Datum numerictypmodin(PG_FUNCTION_ARGS);
+extern Datum numerictypmodout(PG_FUNCTION_ARGS);
+extern Datum bittypmodin(PG_FUNCTION_ARGS);
+extern Datum bittypmodout(PG_FUNCTION_ARGS);
+extern Datum varbittypmodout(PG_FUNCTION_ARGS);
+extern Datum xmltotext(PG_FUNCTION_ARGS);
+extern Datum table_to_xml(PG_FUNCTION_ARGS);
+extern Datum query_to_xml(PG_FUNCTION_ARGS);
+extern Datum cursor_to_xml(PG_FUNCTION_ARGS);
+extern Datum table_to_xmlschema(PG_FUNCTION_ARGS);
+extern Datum query_to_xmlschema(PG_FUNCTION_ARGS);
+extern Datum cursor_to_xmlschema(PG_FUNCTION_ARGS);
+extern Datum table_to_xml_and_xmlschema(PG_FUNCTION_ARGS);
+extern Datum query_to_xml_and_xmlschema(PG_FUNCTION_ARGS);
+extern Datum xpath(PG_FUNCTION_ARGS);
+extern Datum schema_to_xml(PG_FUNCTION_ARGS);
+extern Datum schema_to_xmlschema(PG_FUNCTION_ARGS);
+extern Datum schema_to_xml_and_xmlschema(PG_FUNCTION_ARGS);
+extern Datum database_to_xml(PG_FUNCTION_ARGS);
+extern Datum database_to_xmlschema(PG_FUNCTION_ARGS);
+extern Datum database_to_xml_and_xmlschema(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_in(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_out(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_recv(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_send(PG_FUNCTION_ARGS);
+extern Datum pg_current_xact_id(PG_FUNCTION_ARGS);
+extern Datum pg_current_snapshot(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_xmin(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_xmax(PG_FUNCTION_ARGS);
+extern Datum pg_snapshot_xip(PG_FUNCTION_ARGS);
+extern Datum pg_visible_in_snapshot(PG_FUNCTION_ARGS);
+extern Datum uuid_in(PG_FUNCTION_ARGS);
+extern Datum uuid_out(PG_FUNCTION_ARGS);
+extern Datum uuid_lt(PG_FUNCTION_ARGS);
+extern Datum uuid_le(PG_FUNCTION_ARGS);
+extern Datum uuid_eq(PG_FUNCTION_ARGS);
+extern Datum uuid_ge(PG_FUNCTION_ARGS);
+extern Datum uuid_gt(PG_FUNCTION_ARGS);
+extern Datum uuid_ne(PG_FUNCTION_ARGS);
+extern Datum uuid_cmp(PG_FUNCTION_ARGS);
+extern Datum uuid_recv(PG_FUNCTION_ARGS);
+extern Datum uuid_send(PG_FUNCTION_ARGS);
+extern Datum uuid_hash(PG_FUNCTION_ARGS);
+extern Datum booltext(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_function_calls(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_function_total_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_function_self_time(PG_FUNCTION_ARGS);
+extern Datum record_eq(PG_FUNCTION_ARGS);
+extern Datum record_ne(PG_FUNCTION_ARGS);
+extern Datum record_lt(PG_FUNCTION_ARGS);
+extern Datum record_gt(PG_FUNCTION_ARGS);
+extern Datum record_le(PG_FUNCTION_ARGS);
+extern Datum record_ge(PG_FUNCTION_ARGS);
+extern Datum btrecordcmp(PG_FUNCTION_ARGS);
+extern Datum pg_table_size(PG_FUNCTION_ARGS);
+extern Datum pg_indexes_size(PG_FUNCTION_ARGS);
+extern Datum pg_relation_filenode(PG_FUNCTION_ARGS);
+extern Datum has_foreign_data_wrapper_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_foreign_data_wrapper_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_foreign_data_wrapper_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_foreign_data_wrapper_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_foreign_data_wrapper_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_foreign_data_wrapper_privilege_id(PG_FUNCTION_ARGS);
+extern Datum has_server_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_server_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_server_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_server_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_server_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_server_privilege_id(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_name_name_name(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_name_name_attnum(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_name_id_name(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_name_id_attnum(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_id_name_name(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_id_name_attnum(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_id_id_name(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_id_id_attnum(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_name_attnum(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_column_privilege_id_attnum(PG_FUNCTION_ARGS);
+extern Datum has_any_column_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_any_column_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_any_column_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_any_column_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_any_column_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_any_column_privilege_id(PG_FUNCTION_ARGS);
+extern Datum bitoverlay(PG_FUNCTION_ARGS);
+extern Datum bitoverlay_no_len(PG_FUNCTION_ARGS);
+extern Datum bitgetbit(PG_FUNCTION_ARGS);
+extern Datum bitsetbit(PG_FUNCTION_ARGS);
+extern Datum pg_relation_filepath(PG_FUNCTION_ARGS);
+extern Datum pg_listening_channels(PG_FUNCTION_ARGS);
+extern Datum pg_notify(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_numscans(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_returned(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_fetched(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_inserted(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_updated(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_deleted(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_hot_updated(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_blocks_fetched(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_blocks_hit(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_function_calls(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_function_total_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_function_self_time(PG_FUNCTION_ARGS);
+extern Datum xpath_exists(PG_FUNCTION_ARGS);
+extern Datum xml_is_well_formed(PG_FUNCTION_ARGS);
+extern Datum xml_is_well_formed_document(PG_FUNCTION_ARGS);
+extern Datum xml_is_well_formed_content(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_vacuum_count(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_autovacuum_count(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_analyze_count(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_autoanalyze_count(PG_FUNCTION_ARGS);
+extern Datum text_concat(PG_FUNCTION_ARGS);
+extern Datum text_concat_ws(PG_FUNCTION_ARGS);
+extern Datum text_left(PG_FUNCTION_ARGS);
+extern Datum text_right(PG_FUNCTION_ARGS);
+extern Datum text_reverse(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_buf_fsync_backend(PG_FUNCTION_ARGS);
+extern Datum gist_point_distance(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_tablespace(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_lock(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_snapshot(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_bufferpin(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_startup_deadlock(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_all(PG_FUNCTION_ARGS);
+extern Datum pg_wal_replay_pause(PG_FUNCTION_ARGS);
+extern Datum pg_wal_replay_resume(PG_FUNCTION_ARGS);
+extern Datum pg_is_wal_replay_paused(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_stat_reset_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_bgwriter_stat_reset_time(PG_FUNCTION_ARGS);
+extern Datum ginarrayextract_2args(PG_FUNCTION_ARGS);
+extern Datum gin_extract_tsvector_2args(PG_FUNCTION_ARGS);
+extern Datum pg_sequence_parameters(PG_FUNCTION_ARGS);
+extern Datum pg_available_extensions(PG_FUNCTION_ARGS);
+extern Datum pg_available_extension_versions(PG_FUNCTION_ARGS);
+extern Datum pg_extension_update_paths(PG_FUNCTION_ARGS);
+extern Datum pg_extension_config_dump(PG_FUNCTION_ARGS);
+extern Datum gin_extract_tsquery_5args(PG_FUNCTION_ARGS);
+extern Datum gin_tsquery_consistent_6args(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_xact_lock_int8(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_xact_lock_shared_int8(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_xact_lock_int8(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_xact_lock_shared_int8(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_xact_lock_int4(PG_FUNCTION_ARGS);
+extern Datum pg_advisory_xact_lock_shared_int4(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_xact_lock_int4(PG_FUNCTION_ARGS);
+extern Datum pg_try_advisory_xact_lock_shared_int4(PG_FUNCTION_ARGS);
+extern Datum varchar_support(PG_FUNCTION_ARGS);
+extern Datum pg_create_restore_point(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_wal_senders(PG_FUNCTION_ARGS);
+extern Datum window_row_number(PG_FUNCTION_ARGS);
+extern Datum window_rank(PG_FUNCTION_ARGS);
+extern Datum window_dense_rank(PG_FUNCTION_ARGS);
+extern Datum window_percent_rank(PG_FUNCTION_ARGS);
+extern Datum window_cume_dist(PG_FUNCTION_ARGS);
+extern Datum window_ntile(PG_FUNCTION_ARGS);
+extern Datum window_lag(PG_FUNCTION_ARGS);
+extern Datum window_lag_with_offset(PG_FUNCTION_ARGS);
+extern Datum window_lag_with_offset_and_default(PG_FUNCTION_ARGS);
+extern Datum window_lead(PG_FUNCTION_ARGS);
+extern Datum window_lead_with_offset(PG_FUNCTION_ARGS);
+extern Datum window_lead_with_offset_and_default(PG_FUNCTION_ARGS);
+extern Datum window_first_value(PG_FUNCTION_ARGS);
+extern Datum window_last_value(PG_FUNCTION_ARGS);
+extern Datum window_nth_value(PG_FUNCTION_ARGS);
+extern Datum fdw_handler_in(PG_FUNCTION_ARGS);
+extern Datum fdw_handler_out(PG_FUNCTION_ARGS);
+extern Datum void_recv(PG_FUNCTION_ARGS);
+extern Datum void_send(PG_FUNCTION_ARGS);
+extern Datum btint2sortsupport(PG_FUNCTION_ARGS);
+extern Datum btint4sortsupport(PG_FUNCTION_ARGS);
+extern Datum btint8sortsupport(PG_FUNCTION_ARGS);
+extern Datum btfloat4sortsupport(PG_FUNCTION_ARGS);
+extern Datum btfloat8sortsupport(PG_FUNCTION_ARGS);
+extern Datum btoidsortsupport(PG_FUNCTION_ARGS);
+extern Datum btnamesortsupport(PG_FUNCTION_ARGS);
+extern Datum date_sortsupport(PG_FUNCTION_ARGS);
+extern Datum timestamp_sortsupport(PG_FUNCTION_ARGS);
+extern Datum has_type_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_type_privilege_name_id(PG_FUNCTION_ARGS);
+extern Datum has_type_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_type_privilege_id_id(PG_FUNCTION_ARGS);
+extern Datum has_type_privilege_name(PG_FUNCTION_ARGS);
+extern Datum has_type_privilege_id(PG_FUNCTION_ARGS);
+extern Datum macaddr_not(PG_FUNCTION_ARGS);
+extern Datum macaddr_and(PG_FUNCTION_ARGS);
+extern Datum macaddr_or(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_temp_files(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_temp_bytes(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_deadlocks(PG_FUNCTION_ARGS);
+extern Datum array_to_json(PG_FUNCTION_ARGS);
+extern Datum array_to_json_pretty(PG_FUNCTION_ARGS);
+extern Datum row_to_json(PG_FUNCTION_ARGS);
+extern Datum row_to_json_pretty(PG_FUNCTION_ARGS);
+extern Datum numeric_support(PG_FUNCTION_ARGS);
+extern Datum varbit_support(PG_FUNCTION_ARGS);
+extern Datum pg_get_viewdef_wrap(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_checkpoint_write_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_checkpoint_sync_time(PG_FUNCTION_ARGS);
+extern Datum pg_collation_for(PG_FUNCTION_ARGS);
+extern Datum pg_trigger_depth(PG_FUNCTION_ARGS);
+extern Datum pg_wal_lsn_diff(PG_FUNCTION_ARGS);
+extern Datum pg_size_pretty_numeric(PG_FUNCTION_ARGS);
+extern Datum array_remove(PG_FUNCTION_ARGS);
+extern Datum array_replace(PG_FUNCTION_ARGS);
+extern Datum rangesel(PG_FUNCTION_ARGS);
+extern Datum be_lo_lseek64(PG_FUNCTION_ARGS);
+extern Datum be_lo_tell64(PG_FUNCTION_ARGS);
+extern Datum be_lo_truncate64(PG_FUNCTION_ARGS);
+extern Datum json_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum json_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum to_json(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_mod_since_analyze(PG_FUNCTION_ARGS);
+extern Datum numeric_sum(PG_FUNCTION_ARGS);
+extern Datum array_cardinality(PG_FUNCTION_ARGS);
+extern Datum json_object_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum record_image_eq(PG_FUNCTION_ARGS);
+extern Datum record_image_ne(PG_FUNCTION_ARGS);
+extern Datum record_image_lt(PG_FUNCTION_ARGS);
+extern Datum record_image_gt(PG_FUNCTION_ARGS);
+extern Datum record_image_le(PG_FUNCTION_ARGS);
+extern Datum record_image_ge(PG_FUNCTION_ARGS);
+extern Datum btrecordimagecmp(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_archiver(PG_FUNCTION_ARGS);
+extern Datum json_object_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum json_build_array(PG_FUNCTION_ARGS);
+extern Datum json_build_array_noargs(PG_FUNCTION_ARGS);
+extern Datum json_build_object(PG_FUNCTION_ARGS);
+extern Datum json_build_object_noargs(PG_FUNCTION_ARGS);
+extern Datum json_object(PG_FUNCTION_ARGS);
+extern Datum json_object_two_arg(PG_FUNCTION_ARGS);
+extern Datum json_to_record(PG_FUNCTION_ARGS);
+extern Datum json_to_recordset(PG_FUNCTION_ARGS);
+extern Datum jsonb_array_length(PG_FUNCTION_ARGS);
+extern Datum jsonb_each(PG_FUNCTION_ARGS);
+extern Datum jsonb_populate_record(PG_FUNCTION_ARGS);
+extern Datum jsonb_typeof(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_field_text(PG_FUNCTION_ARGS);
+extern Datum jsonb_array_element(PG_FUNCTION_ARGS);
+extern Datum jsonb_array_element_text(PG_FUNCTION_ARGS);
+extern Datum jsonb_extract_path(PG_FUNCTION_ARGS);
+extern Datum width_bucket_array(PG_FUNCTION_ARGS);
+extern Datum jsonb_array_elements(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_in(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_out(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_lt(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_le(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_eq(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_ge(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_gt(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_ne(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_mi(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_recv(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_send(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_cmp(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_hash(PG_FUNCTION_ARGS);
+extern Datum bttextsortsupport(PG_FUNCTION_ARGS);
+extern Datum generate_series_step_numeric(PG_FUNCTION_ARGS);
+extern Datum generate_series_numeric(PG_FUNCTION_ARGS);
+extern Datum json_strip_nulls(PG_FUNCTION_ARGS);
+extern Datum jsonb_strip_nulls(PG_FUNCTION_ARGS);
+extern Datum jsonb_object(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_two_arg(PG_FUNCTION_ARGS);
+extern Datum jsonb_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_build_array(PG_FUNCTION_ARGS);
+extern Datum jsonb_build_array_noargs(PG_FUNCTION_ARGS);
+extern Datum jsonb_build_object(PG_FUNCTION_ARGS);
+extern Datum jsonb_build_object_noargs(PG_FUNCTION_ARGS);
+extern Datum dist_ppoly(PG_FUNCTION_ARGS);
+extern Datum array_position(PG_FUNCTION_ARGS);
+extern Datum array_position_start(PG_FUNCTION_ARGS);
+extern Datum array_positions(PG_FUNCTION_ARGS);
+extern Datum gist_circle_distance(PG_FUNCTION_ARGS);
+extern Datum numeric_scale(PG_FUNCTION_ARGS);
+extern Datum gist_point_fetch(PG_FUNCTION_ARGS);
+extern Datum numeric_sortsupport(PG_FUNCTION_ARGS);
+extern Datum gist_poly_distance(PG_FUNCTION_ARGS);
+extern Datum dist_cpoint(PG_FUNCTION_ARGS);
+extern Datum dist_polyp(PG_FUNCTION_ARGS);
+extern Datum pg_read_file_off_len_missing(PG_FUNCTION_ARGS);
+extern Datum show_config_by_name_missing_ok(PG_FUNCTION_ARGS);
+extern Datum pg_read_binary_file_off_len_missing(PG_FUNCTION_ARGS);
+extern Datum pg_notification_queue_usage(PG_FUNCTION_ARGS);
+extern Datum pg_ls_dir(PG_FUNCTION_ARGS);
+extern Datum row_security_active(PG_FUNCTION_ARGS);
+extern Datum row_security_active_name(PG_FUNCTION_ARGS);
+extern Datum uuid_sortsupport(PG_FUNCTION_ARGS);
+extern Datum jsonb_concat(PG_FUNCTION_ARGS);
+extern Datum jsonb_delete(PG_FUNCTION_ARGS);
+extern Datum jsonb_delete_idx(PG_FUNCTION_ARGS);
+extern Datum jsonb_delete_path(PG_FUNCTION_ARGS);
+extern Datum jsonb_set(PG_FUNCTION_ARGS);
+extern Datum jsonb_pretty(PG_FUNCTION_ARGS);
+extern Datum pg_stat_file(PG_FUNCTION_ARGS);
+extern Datum xidneq(PG_FUNCTION_ARGS);
+extern Datum tsm_handler_in(PG_FUNCTION_ARGS);
+extern Datum tsm_handler_out(PG_FUNCTION_ARGS);
+extern Datum tsm_bernoulli_handler(PG_FUNCTION_ARGS);
+extern Datum tsm_system_handler(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_wal_receiver(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_progress_info(PG_FUNCTION_ARGS);
+extern Datum tsvector_filter(PG_FUNCTION_ARGS);
+extern Datum tsvector_setweight_by_filter(PG_FUNCTION_ARGS);
+extern Datum tsvector_delete_str(PG_FUNCTION_ARGS);
+extern Datum tsvector_unnest(PG_FUNCTION_ARGS);
+extern Datum tsvector_delete_arr(PG_FUNCTION_ARGS);
+extern Datum int4_avg_combine(PG_FUNCTION_ARGS);
+extern Datum interval_combine(PG_FUNCTION_ARGS);
+extern Datum tsvector_to_array(PG_FUNCTION_ARGS);
+extern Datum array_to_tsvector(PG_FUNCTION_ARGS);
+extern Datum bpchar_sortsupport(PG_FUNCTION_ARGS);
+extern Datum show_all_file_settings(PG_FUNCTION_ARGS);
+extern Datum pg_current_wal_flush_lsn(PG_FUNCTION_ARGS);
+extern Datum bytea_sortsupport(PG_FUNCTION_ARGS);
+extern Datum bttext_pattern_sortsupport(PG_FUNCTION_ARGS);
+extern Datum btbpchar_pattern_sortsupport(PG_FUNCTION_ARGS);
+extern Datum pg_size_bytes(PG_FUNCTION_ARGS);
+extern Datum numeric_serialize(PG_FUNCTION_ARGS);
+extern Datum numeric_deserialize(PG_FUNCTION_ARGS);
+extern Datum numeric_avg_combine(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_combine(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_serialize(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_deserialize(PG_FUNCTION_ARGS);
+extern Datum numeric_combine(PG_FUNCTION_ARGS);
+extern Datum float8_regr_combine(PG_FUNCTION_ARGS);
+extern Datum jsonb_delete_array(PG_FUNCTION_ARGS);
+extern Datum cash_mul_int8(PG_FUNCTION_ARGS);
+extern Datum cash_div_int8(PG_FUNCTION_ARGS);
+extern Datum pg_current_xact_id_if_assigned(PG_FUNCTION_ARGS);
+extern Datum pg_get_partkeydef(PG_FUNCTION_ARGS);
+extern Datum pg_ls_logdir(PG_FUNCTION_ARGS);
+extern Datum pg_ls_waldir(PG_FUNCTION_ARGS);
+extern Datum pg_ndistinct_in(PG_FUNCTION_ARGS);
+extern Datum pg_ndistinct_out(PG_FUNCTION_ARGS);
+extern Datum pg_ndistinct_recv(PG_FUNCTION_ARGS);
+extern Datum pg_ndistinct_send(PG_FUNCTION_ARGS);
+extern Datum macaddr_sortsupport(PG_FUNCTION_ARGS);
+extern Datum pg_xact_status(PG_FUNCTION_ARGS);
+extern Datum pg_safe_snapshot_blocking_pids(PG_FUNCTION_ARGS);
+extern Datum pg_isolation_test_session_is_blocked(PG_FUNCTION_ARGS);
+extern Datum pg_identify_object_as_address(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_opcinfo(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_add_value(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_consistent(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_union(PG_FUNCTION_ARGS);
+extern Datum int8_avg_accum_inv(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_sum(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_avg(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_var_pop(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_var_samp(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_stddev_pop(PG_FUNCTION_ARGS);
+extern Datum numeric_poly_stddev_samp(PG_FUNCTION_ARGS);
+extern Datum regexp_match_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_match(PG_FUNCTION_ARGS);
+extern Datum int8_mul_cash(PG_FUNCTION_ARGS);
+extern Datum pg_config(PG_FUNCTION_ARGS);
+extern Datum pg_hba_file_rules(PG_FUNCTION_ARGS);
+extern Datum pg_statistics_obj_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_dependencies_in(PG_FUNCTION_ARGS);
+extern Datum pg_dependencies_out(PG_FUNCTION_ARGS);
+extern Datum pg_dependencies_recv(PG_FUNCTION_ARGS);
+extern Datum pg_dependencies_send(PG_FUNCTION_ARGS);
+extern Datum pg_get_partition_constraintdef(PG_FUNCTION_ARGS);
+extern Datum time_hash_extended(PG_FUNCTION_ARGS);
+extern Datum timetz_hash_extended(PG_FUNCTION_ARGS);
+extern Datum timestamp_hash_extended(PG_FUNCTION_ARGS);
+extern Datum uuid_hash_extended(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_hash_extended(PG_FUNCTION_ARGS);
+extern Datum hashenumextended(PG_FUNCTION_ARGS);
+extern Datum pg_get_statisticsobjdef(PG_FUNCTION_ARGS);
+extern Datum jsonb_hash_extended(PG_FUNCTION_ARGS);
+extern Datum hash_range_extended(PG_FUNCTION_ARGS);
+extern Datum interval_hash_extended(PG_FUNCTION_ARGS);
+extern Datum sha224_bytea(PG_FUNCTION_ARGS);
+extern Datum sha256_bytea(PG_FUNCTION_ARGS);
+extern Datum sha384_bytea(PG_FUNCTION_ARGS);
+extern Datum sha512_bytea(PG_FUNCTION_ARGS);
+extern Datum pg_partition_tree(PG_FUNCTION_ARGS);
+extern Datum pg_partition_root(PG_FUNCTION_ARGS);
+extern Datum pg_partition_ancestors(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_checksum_failures(PG_FUNCTION_ARGS);
+extern Datum pg_stats_ext_mcvlist_items(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_checksum_last_failure(PG_FUNCTION_ARGS);
+extern Datum gen_random_uuid(PG_FUNCTION_ARGS);
+extern Datum gtsvector_options(PG_FUNCTION_ARGS);
+extern Datum gist_point_sortsupport(PG_FUNCTION_ARGS);
+extern Datum pg_promote(PG_FUNCTION_ARGS);
+extern Datum prefixsel(PG_FUNCTION_ARGS);
+extern Datum prefixjoinsel(PG_FUNCTION_ARGS);
+extern Datum pg_control_system(PG_FUNCTION_ARGS);
+extern Datum pg_control_checkpoint(PG_FUNCTION_ARGS);
+extern Datum pg_control_recovery(PG_FUNCTION_ARGS);
+extern Datum pg_control_init(PG_FUNCTION_ARGS);
+extern Datum pg_import_system_collations(PG_FUNCTION_ARGS);
+extern Datum macaddr8_recv(PG_FUNCTION_ARGS);
+extern Datum macaddr8_send(PG_FUNCTION_ARGS);
+extern Datum pg_collation_actual_version(PG_FUNCTION_ARGS);
+extern Datum jsonb_numeric(PG_FUNCTION_ARGS);
+extern Datum jsonb_int2(PG_FUNCTION_ARGS);
+extern Datum jsonb_int4(PG_FUNCTION_ARGS);
+extern Datum jsonb_int8(PG_FUNCTION_ARGS);
+extern Datum jsonb_float4(PG_FUNCTION_ARGS);
+extern Datum pg_filenode_relation(PG_FUNCTION_ARGS);
+extern Datum be_lo_from_bytea(PG_FUNCTION_ARGS);
+extern Datum be_lo_get(PG_FUNCTION_ARGS);
+extern Datum be_lo_get_fragment(PG_FUNCTION_ARGS);
+extern Datum be_lo_put(PG_FUNCTION_ARGS);
+extern Datum make_timestamp(PG_FUNCTION_ARGS);
+extern Datum make_timestamptz(PG_FUNCTION_ARGS);
+extern Datum make_timestamptz_at_timezone(PG_FUNCTION_ARGS);
+extern Datum make_interval(PG_FUNCTION_ARGS);
+extern Datum jsonb_array_elements_text(PG_FUNCTION_ARGS);
+extern Datum spg_range_quad_config(PG_FUNCTION_ARGS);
+extern Datum spg_range_quad_choose(PG_FUNCTION_ARGS);
+extern Datum spg_range_quad_picksplit(PG_FUNCTION_ARGS);
+extern Datum spg_range_quad_inner_consistent(PG_FUNCTION_ARGS);
+extern Datum spg_range_quad_leaf_consistent(PG_FUNCTION_ARGS);
+extern Datum jsonb_populate_recordset(PG_FUNCTION_ARGS);
+extern Datum to_regoperator(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_field(PG_FUNCTION_ARGS);
+extern Datum to_regprocedure(PG_FUNCTION_ARGS);
+extern Datum gin_compare_jsonb(PG_FUNCTION_ARGS);
+extern Datum gin_extract_jsonb(PG_FUNCTION_ARGS);
+extern Datum gin_extract_jsonb_query(PG_FUNCTION_ARGS);
+extern Datum gin_consistent_jsonb(PG_FUNCTION_ARGS);
+extern Datum gin_extract_jsonb_path(PG_FUNCTION_ARGS);
+extern Datum gin_extract_jsonb_query_path(PG_FUNCTION_ARGS);
+extern Datum gin_consistent_jsonb_path(PG_FUNCTION_ARGS);
+extern Datum gin_triconsistent_jsonb(PG_FUNCTION_ARGS);
+extern Datum gin_triconsistent_jsonb_path(PG_FUNCTION_ARGS);
+extern Datum jsonb_to_record(PG_FUNCTION_ARGS);
+extern Datum jsonb_to_recordset(PG_FUNCTION_ARGS);
+extern Datum to_regoper(PG_FUNCTION_ARGS);
+extern Datum to_regtype(PG_FUNCTION_ARGS);
+extern Datum to_regproc(PG_FUNCTION_ARGS);
+extern Datum to_regclass(PG_FUNCTION_ARGS);
+extern Datum bool_accum(PG_FUNCTION_ARGS);
+extern Datum bool_accum_inv(PG_FUNCTION_ARGS);
+extern Datum bool_alltrue(PG_FUNCTION_ARGS);
+extern Datum bool_anytrue(PG_FUNCTION_ARGS);
+extern Datum anyenum_in(PG_FUNCTION_ARGS);
+extern Datum anyenum_out(PG_FUNCTION_ARGS);
+extern Datum enum_in(PG_FUNCTION_ARGS);
+extern Datum enum_out(PG_FUNCTION_ARGS);
+extern Datum enum_eq(PG_FUNCTION_ARGS);
+extern Datum enum_ne(PG_FUNCTION_ARGS);
+extern Datum enum_lt(PG_FUNCTION_ARGS);
+extern Datum enum_gt(PG_FUNCTION_ARGS);
+extern Datum enum_le(PG_FUNCTION_ARGS);
+extern Datum enum_ge(PG_FUNCTION_ARGS);
+extern Datum enum_cmp(PG_FUNCTION_ARGS);
+extern Datum hashenum(PG_FUNCTION_ARGS);
+extern Datum enum_smaller(PG_FUNCTION_ARGS);
+extern Datum enum_larger(PG_FUNCTION_ARGS);
+extern Datum enum_first(PG_FUNCTION_ARGS);
+extern Datum enum_last(PG_FUNCTION_ARGS);
+extern Datum enum_range_bounds(PG_FUNCTION_ARGS);
+extern Datum enum_range_all(PG_FUNCTION_ARGS);
+extern Datum enum_recv(PG_FUNCTION_ARGS);
+extern Datum enum_send(PG_FUNCTION_ARGS);
+extern Datum string_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum string_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum pg_describe_object(PG_FUNCTION_ARGS);
+extern Datum text_format(PG_FUNCTION_ARGS);
+extern Datum text_format_nv(PG_FUNCTION_ARGS);
+extern Datum bytea_string_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum bytea_string_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum int8dec(PG_FUNCTION_ARGS);
+extern Datum int8dec_any(PG_FUNCTION_ARGS);
+extern Datum numeric_accum_inv(PG_FUNCTION_ARGS);
+extern Datum interval_accum_inv(PG_FUNCTION_ARGS);
+extern Datum network_overlap(PG_FUNCTION_ARGS);
+extern Datum inet_gist_consistent(PG_FUNCTION_ARGS);
+extern Datum inet_gist_union(PG_FUNCTION_ARGS);
+extern Datum inet_gist_compress(PG_FUNCTION_ARGS);
+extern Datum jsonb_bool(PG_FUNCTION_ARGS);
+extern Datum inet_gist_penalty(PG_FUNCTION_ARGS);
+extern Datum inet_gist_picksplit(PG_FUNCTION_ARGS);
+extern Datum inet_gist_same(PG_FUNCTION_ARGS);
+extern Datum networksel(PG_FUNCTION_ARGS);
+extern Datum networkjoinsel(PG_FUNCTION_ARGS);
+extern Datum network_larger(PG_FUNCTION_ARGS);
+extern Datum network_smaller(PG_FUNCTION_ARGS);
+extern Datum pg_event_trigger_dropped_objects(PG_FUNCTION_ARGS);
+extern Datum int2_accum_inv(PG_FUNCTION_ARGS);
+extern Datum int4_accum_inv(PG_FUNCTION_ARGS);
+extern Datum int8_accum_inv(PG_FUNCTION_ARGS);
+extern Datum int2_avg_accum_inv(PG_FUNCTION_ARGS);
+extern Datum int4_avg_accum_inv(PG_FUNCTION_ARGS);
+extern Datum int2int4_sum(PG_FUNCTION_ARGS);
+extern Datum inet_gist_fetch(PG_FUNCTION_ARGS);
+extern Datum pg_logical_emit_message_text(PG_FUNCTION_ARGS);
+extern Datum pg_logical_emit_message_bytea(PG_FUNCTION_ARGS);
+extern Datum jsonb_insert(PG_FUNCTION_ARGS);
+extern Datum pg_xact_commit_timestamp(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_pg_type_oid(PG_FUNCTION_ARGS);
+extern Datum pg_last_committed_xact(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_array_pg_type_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_heap_pg_class_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_index_pg_class_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_toast_pg_class_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_pg_enum_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_pg_authid_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_create_empty_extension(PG_FUNCTION_ARGS);
+extern Datum event_trigger_in(PG_FUNCTION_ARGS);
+extern Datum event_trigger_out(PG_FUNCTION_ARGS);
+extern Datum tsvectorin(PG_FUNCTION_ARGS);
+extern Datum tsvectorout(PG_FUNCTION_ARGS);
+extern Datum tsqueryin(PG_FUNCTION_ARGS);
+extern Datum tsqueryout(PG_FUNCTION_ARGS);
+extern Datum tsvector_lt(PG_FUNCTION_ARGS);
+extern Datum tsvector_le(PG_FUNCTION_ARGS);
+extern Datum tsvector_eq(PG_FUNCTION_ARGS);
+extern Datum tsvector_ne(PG_FUNCTION_ARGS);
+extern Datum tsvector_ge(PG_FUNCTION_ARGS);
+extern Datum tsvector_gt(PG_FUNCTION_ARGS);
+extern Datum tsvector_cmp(PG_FUNCTION_ARGS);
+extern Datum tsvector_strip(PG_FUNCTION_ARGS);
+extern Datum tsvector_setweight(PG_FUNCTION_ARGS);
+extern Datum tsvector_concat(PG_FUNCTION_ARGS);
+extern Datum ts_match_vq(PG_FUNCTION_ARGS);
+extern Datum ts_match_qv(PG_FUNCTION_ARGS);
+extern Datum tsvectorsend(PG_FUNCTION_ARGS);
+extern Datum tsvectorrecv(PG_FUNCTION_ARGS);
+extern Datum tsquerysend(PG_FUNCTION_ARGS);
+extern Datum tsqueryrecv(PG_FUNCTION_ARGS);
+extern Datum gtsvectorin(PG_FUNCTION_ARGS);
+extern Datum gtsvectorout(PG_FUNCTION_ARGS);
+extern Datum gtsvector_compress(PG_FUNCTION_ARGS);
+extern Datum gtsvector_decompress(PG_FUNCTION_ARGS);
+extern Datum gtsvector_picksplit(PG_FUNCTION_ARGS);
+extern Datum gtsvector_union(PG_FUNCTION_ARGS);
+extern Datum gtsvector_same(PG_FUNCTION_ARGS);
+extern Datum gtsvector_penalty(PG_FUNCTION_ARGS);
+extern Datum gtsvector_consistent(PG_FUNCTION_ARGS);
+extern Datum gin_extract_tsvector(PG_FUNCTION_ARGS);
+extern Datum gin_extract_tsquery(PG_FUNCTION_ARGS);
+extern Datum gin_tsquery_consistent(PG_FUNCTION_ARGS);
+extern Datum tsquery_lt(PG_FUNCTION_ARGS);
+extern Datum tsquery_le(PG_FUNCTION_ARGS);
+extern Datum tsquery_eq(PG_FUNCTION_ARGS);
+extern Datum tsquery_ne(PG_FUNCTION_ARGS);
+extern Datum tsquery_ge(PG_FUNCTION_ARGS);
+extern Datum tsquery_gt(PG_FUNCTION_ARGS);
+extern Datum tsquery_cmp(PG_FUNCTION_ARGS);
+extern Datum tsquery_and(PG_FUNCTION_ARGS);
+extern Datum tsquery_or(PG_FUNCTION_ARGS);
+extern Datum tsquery_not(PG_FUNCTION_ARGS);
+extern Datum tsquery_numnode(PG_FUNCTION_ARGS);
+extern Datum tsquerytree(PG_FUNCTION_ARGS);
+extern Datum tsquery_rewrite(PG_FUNCTION_ARGS);
+extern Datum tsquery_rewrite_query(PG_FUNCTION_ARGS);
+extern Datum tsmatchsel(PG_FUNCTION_ARGS);
+extern Datum tsmatchjoinsel(PG_FUNCTION_ARGS);
+extern Datum ts_typanalyze(PG_FUNCTION_ARGS);
+extern Datum ts_stat1(PG_FUNCTION_ARGS);
+extern Datum ts_stat2(PG_FUNCTION_ARGS);
+extern Datum tsq_mcontains(PG_FUNCTION_ARGS);
+extern Datum tsq_mcontained(PG_FUNCTION_ARGS);
+extern Datum gtsquery_compress(PG_FUNCTION_ARGS);
+extern Datum text_starts_with(PG_FUNCTION_ARGS);
+extern Datum gtsquery_picksplit(PG_FUNCTION_ARGS);
+extern Datum gtsquery_union(PG_FUNCTION_ARGS);
+extern Datum gtsquery_same(PG_FUNCTION_ARGS);
+extern Datum gtsquery_penalty(PG_FUNCTION_ARGS);
+extern Datum gtsquery_consistent(PG_FUNCTION_ARGS);
+extern Datum ts_rank_wttf(PG_FUNCTION_ARGS);
+extern Datum ts_rank_wtt(PG_FUNCTION_ARGS);
+extern Datum ts_rank_ttf(PG_FUNCTION_ARGS);
+extern Datum ts_rank_tt(PG_FUNCTION_ARGS);
+extern Datum ts_rankcd_wttf(PG_FUNCTION_ARGS);
+extern Datum ts_rankcd_wtt(PG_FUNCTION_ARGS);
+extern Datum ts_rankcd_ttf(PG_FUNCTION_ARGS);
+extern Datum ts_rankcd_tt(PG_FUNCTION_ARGS);
+extern Datum tsvector_length(PG_FUNCTION_ARGS);
+extern Datum ts_token_type_byid(PG_FUNCTION_ARGS);
+extern Datum ts_token_type_byname(PG_FUNCTION_ARGS);
+extern Datum ts_parse_byid(PG_FUNCTION_ARGS);
+extern Datum ts_parse_byname(PG_FUNCTION_ARGS);
+extern Datum prsd_start(PG_FUNCTION_ARGS);
+extern Datum prsd_nexttoken(PG_FUNCTION_ARGS);
+extern Datum prsd_end(PG_FUNCTION_ARGS);
+extern Datum prsd_headline(PG_FUNCTION_ARGS);
+extern Datum prsd_lextype(PG_FUNCTION_ARGS);
+extern Datum ts_lexize(PG_FUNCTION_ARGS);
+extern Datum gin_cmp_tslexeme(PG_FUNCTION_ARGS);
+extern Datum dsimple_init(PG_FUNCTION_ARGS);
+extern Datum dsimple_lexize(PG_FUNCTION_ARGS);
+extern Datum dsynonym_init(PG_FUNCTION_ARGS);
+extern Datum dsynonym_lexize(PG_FUNCTION_ARGS);
+extern Datum dispell_init(PG_FUNCTION_ARGS);
+extern Datum dispell_lexize(PG_FUNCTION_ARGS);
+extern Datum regconfigin(PG_FUNCTION_ARGS);
+extern Datum regconfigout(PG_FUNCTION_ARGS);
+extern Datum regconfigrecv(PG_FUNCTION_ARGS);
+extern Datum regconfigsend(PG_FUNCTION_ARGS);
+extern Datum thesaurus_init(PG_FUNCTION_ARGS);
+extern Datum thesaurus_lexize(PG_FUNCTION_ARGS);
+extern Datum ts_headline_byid_opt(PG_FUNCTION_ARGS);
+extern Datum ts_headline_byid(PG_FUNCTION_ARGS);
+extern Datum to_tsvector_byid(PG_FUNCTION_ARGS);
+extern Datum to_tsquery_byid(PG_FUNCTION_ARGS);
+extern Datum plainto_tsquery_byid(PG_FUNCTION_ARGS);
+extern Datum to_tsvector(PG_FUNCTION_ARGS);
+extern Datum to_tsquery(PG_FUNCTION_ARGS);
+extern Datum plainto_tsquery(PG_FUNCTION_ARGS);
+extern Datum tsvector_update_trigger_byid(PG_FUNCTION_ARGS);
+extern Datum tsvector_update_trigger_bycolumn(PG_FUNCTION_ARGS);
+extern Datum ts_headline_opt(PG_FUNCTION_ARGS);
+extern Datum ts_headline(PG_FUNCTION_ARGS);
+extern Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
+extern Datum get_current_ts_config(PG_FUNCTION_ARGS);
+extern Datum ts_match_tt(PG_FUNCTION_ARGS);
+extern Datum ts_match_tq(PG_FUNCTION_ARGS);
+extern Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
+extern Datum regdictionaryin(PG_FUNCTION_ARGS);
+extern Datum regdictionaryout(PG_FUNCTION_ARGS);
+extern Datum regdictionaryrecv(PG_FUNCTION_ARGS);
+extern Datum regdictionarysend(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset_shared(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset_single_table_counters(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset_single_function_counters(PG_FUNCTION_ARGS);
+extern Datum pg_tablespace_location(PG_FUNCTION_ARGS);
+extern Datum pg_create_physical_replication_slot(PG_FUNCTION_ARGS);
+extern Datum pg_drop_replication_slot(PG_FUNCTION_ARGS);
+extern Datum pg_get_replication_slots(PG_FUNCTION_ARGS);
+extern Datum pg_logical_slot_get_changes(PG_FUNCTION_ARGS);
+extern Datum pg_logical_slot_get_binary_changes(PG_FUNCTION_ARGS);
+extern Datum pg_logical_slot_peek_changes(PG_FUNCTION_ARGS);
+extern Datum pg_logical_slot_peek_binary_changes(PG_FUNCTION_ARGS);
+extern Datum pg_create_logical_replication_slot(PG_FUNCTION_ARGS);
+extern Datum to_jsonb(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_snapshot_timestamp(PG_FUNCTION_ARGS);
+extern Datum gin_clean_pending_list(PG_FUNCTION_ARGS);
+extern Datum gtsvector_consistent_oldsig(PG_FUNCTION_ARGS);
+extern Datum gin_extract_tsquery_oldsig(PG_FUNCTION_ARGS);
+extern Datum gin_tsquery_consistent_oldsig(PG_FUNCTION_ARGS);
+extern Datum gtsquery_consistent_oldsig(PG_FUNCTION_ARGS);
+extern Datum inet_spg_config(PG_FUNCTION_ARGS);
+extern Datum inet_spg_choose(PG_FUNCTION_ARGS);
+extern Datum inet_spg_picksplit(PG_FUNCTION_ARGS);
+extern Datum inet_spg_inner_consistent(PG_FUNCTION_ARGS);
+extern Datum inet_spg_leaf_consistent(PG_FUNCTION_ARGS);
+extern Datum pg_current_logfile(PG_FUNCTION_ARGS);
+extern Datum pg_current_logfile_1arg(PG_FUNCTION_ARGS);
+extern Datum jsonb_send(PG_FUNCTION_ARGS);
+extern Datum jsonb_out(PG_FUNCTION_ARGS);
+extern Datum jsonb_recv(PG_FUNCTION_ARGS);
+extern Datum jsonb_in(PG_FUNCTION_ARGS);
+extern Datum pg_get_function_arg_default(PG_FUNCTION_ARGS);
+extern Datum pg_export_snapshot(PG_FUNCTION_ARGS);
+extern Datum pg_is_in_recovery(PG_FUNCTION_ARGS);
+extern Datum int4_cash(PG_FUNCTION_ARGS);
+extern Datum int8_cash(PG_FUNCTION_ARGS);
+extern Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
+extern Datum array_typanalyze(PG_FUNCTION_ARGS);
+extern Datum arraycontsel(PG_FUNCTION_ARGS);
+extern Datum arraycontjoinsel(PG_FUNCTION_ARGS);
+extern Datum pg_get_multixact_members(PG_FUNCTION_ARGS);
+extern Datum pg_last_wal_receive_lsn(PG_FUNCTION_ARGS);
+extern Datum pg_last_wal_replay_lsn(PG_FUNCTION_ARGS);
+extern Datum cash_div_cash(PG_FUNCTION_ARGS);
+extern Datum cash_numeric(PG_FUNCTION_ARGS);
+extern Datum numeric_cash(PG_FUNCTION_ARGS);
+extern Datum pg_read_file_all(PG_FUNCTION_ARGS);
+extern Datum pg_read_binary_file_off_len(PG_FUNCTION_ARGS);
+extern Datum pg_read_binary_file_all(PG_FUNCTION_ARGS);
+extern Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
+extern Datum pg_last_xact_replay_timestamp(PG_FUNCTION_ARGS);
+extern Datum anyrange_in(PG_FUNCTION_ARGS);
+extern Datum anyrange_out(PG_FUNCTION_ARGS);
+extern Datum range_in(PG_FUNCTION_ARGS);
+extern Datum range_out(PG_FUNCTION_ARGS);
+extern Datum range_recv(PG_FUNCTION_ARGS);
+extern Datum range_send(PG_FUNCTION_ARGS);
+extern Datum pg_identify_object(PG_FUNCTION_ARGS);
+extern Datum range_constructor2(PG_FUNCTION_ARGS);
+extern Datum range_constructor3(PG_FUNCTION_ARGS);
+extern Datum pg_relation_is_updatable(PG_FUNCTION_ARGS);
+extern Datum pg_column_is_updatable(PG_FUNCTION_ARGS);
+extern Datum make_date(PG_FUNCTION_ARGS);
+extern Datum make_time(PG_FUNCTION_ARGS);
+extern Datum range_lower(PG_FUNCTION_ARGS);
+extern Datum range_upper(PG_FUNCTION_ARGS);
+extern Datum range_empty(PG_FUNCTION_ARGS);
+extern Datum range_lower_inc(PG_FUNCTION_ARGS);
+extern Datum range_upper_inc(PG_FUNCTION_ARGS);
+extern Datum range_lower_inf(PG_FUNCTION_ARGS);
+extern Datum range_upper_inf(PG_FUNCTION_ARGS);
+extern Datum range_eq(PG_FUNCTION_ARGS);
+extern Datum range_ne(PG_FUNCTION_ARGS);
+extern Datum range_overlaps(PG_FUNCTION_ARGS);
+extern Datum range_contains_elem(PG_FUNCTION_ARGS);
+extern Datum range_contains(PG_FUNCTION_ARGS);
+extern Datum elem_contained_by_range(PG_FUNCTION_ARGS);
+extern Datum range_contained_by(PG_FUNCTION_ARGS);
+extern Datum range_adjacent(PG_FUNCTION_ARGS);
+extern Datum range_before(PG_FUNCTION_ARGS);
+extern Datum range_after(PG_FUNCTION_ARGS);
+extern Datum range_overleft(PG_FUNCTION_ARGS);
+extern Datum range_overright(PG_FUNCTION_ARGS);
+extern Datum range_union(PG_FUNCTION_ARGS);
+extern Datum range_intersect(PG_FUNCTION_ARGS);
+extern Datum range_minus(PG_FUNCTION_ARGS);
+extern Datum range_cmp(PG_FUNCTION_ARGS);
+extern Datum range_lt(PG_FUNCTION_ARGS);
+extern Datum range_le(PG_FUNCTION_ARGS);
+extern Datum range_ge(PG_FUNCTION_ARGS);
+extern Datum range_gt(PG_FUNCTION_ARGS);
+extern Datum range_gist_consistent(PG_FUNCTION_ARGS);
+extern Datum range_gist_union(PG_FUNCTION_ARGS);
+extern Datum pg_replication_slot_advance(PG_FUNCTION_ARGS);
+extern Datum range_gist_penalty(PG_FUNCTION_ARGS);
+extern Datum range_gist_picksplit(PG_FUNCTION_ARGS);
+extern Datum range_gist_same(PG_FUNCTION_ARGS);
+extern Datum hash_range(PG_FUNCTION_ARGS);
+extern Datum int4range_canonical(PG_FUNCTION_ARGS);
+extern Datum daterange_canonical(PG_FUNCTION_ARGS);
+extern Datum range_typanalyze(PG_FUNCTION_ARGS);
+extern Datum timestamp_support(PG_FUNCTION_ARGS);
+extern Datum interval_support(PG_FUNCTION_ARGS);
+extern Datum ginarraytriconsistent(PG_FUNCTION_ARGS);
+extern Datum gin_tsquery_triconsistent(PG_FUNCTION_ARGS);
+extern Datum int4range_subdiff(PG_FUNCTION_ARGS);
+extern Datum int8range_subdiff(PG_FUNCTION_ARGS);
+extern Datum numrange_subdiff(PG_FUNCTION_ARGS);
+extern Datum daterange_subdiff(PG_FUNCTION_ARGS);
+extern Datum int8range_canonical(PG_FUNCTION_ARGS);
+extern Datum tsrange_subdiff(PG_FUNCTION_ARGS);
+extern Datum tstzrange_subdiff(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_keys(PG_FUNCTION_ARGS);
+extern Datum jsonb_each_text(PG_FUNCTION_ARGS);
+extern Datum mxid_age(PG_FUNCTION_ARGS);
+extern Datum jsonb_extract_path_text(PG_FUNCTION_ARGS);
+extern Datum acldefault_sql(PG_FUNCTION_ARGS);
+extern Datum time_support(PG_FUNCTION_ARGS);
+extern Datum json_object_field(PG_FUNCTION_ARGS);
+extern Datum json_object_field_text(PG_FUNCTION_ARGS);
+extern Datum json_array_element(PG_FUNCTION_ARGS);
+extern Datum json_array_element_text(PG_FUNCTION_ARGS);
+extern Datum json_extract_path(PG_FUNCTION_ARGS);
+extern Datum brin_summarize_new_values(PG_FUNCTION_ARGS);
+extern Datum json_extract_path_text(PG_FUNCTION_ARGS);
+extern Datum pg_get_object_address(PG_FUNCTION_ARGS);
+extern Datum json_array_elements(PG_FUNCTION_ARGS);
+extern Datum json_array_length(PG_FUNCTION_ARGS);
+extern Datum json_object_keys(PG_FUNCTION_ARGS);
+extern Datum json_each(PG_FUNCTION_ARGS);
+extern Datum json_each_text(PG_FUNCTION_ARGS);
+extern Datum json_populate_record(PG_FUNCTION_ARGS);
+extern Datum json_populate_recordset(PG_FUNCTION_ARGS);
+extern Datum json_typeof(PG_FUNCTION_ARGS);
+extern Datum json_array_elements_text(PG_FUNCTION_ARGS);
+extern Datum ordered_set_transition(PG_FUNCTION_ARGS);
+extern Datum ordered_set_transition_multi(PG_FUNCTION_ARGS);
+extern Datum percentile_disc_final(PG_FUNCTION_ARGS);
+extern Datum percentile_cont_float8_final(PG_FUNCTION_ARGS);
+extern Datum percentile_cont_interval_final(PG_FUNCTION_ARGS);
+extern Datum percentile_disc_multi_final(PG_FUNCTION_ARGS);
+extern Datum percentile_cont_float8_multi_final(PG_FUNCTION_ARGS);
+extern Datum percentile_cont_interval_multi_final(PG_FUNCTION_ARGS);
+extern Datum mode_final(PG_FUNCTION_ARGS);
+extern Datum hypothetical_rank_final(PG_FUNCTION_ARGS);
+extern Datum hypothetical_percent_rank_final(PG_FUNCTION_ARGS);
+extern Datum hypothetical_cume_dist_final(PG_FUNCTION_ARGS);
+extern Datum hypothetical_dense_rank_final(PG_FUNCTION_ARGS);
+extern Datum generate_series_int4_support(PG_FUNCTION_ARGS);
+extern Datum generate_series_int8_support(PG_FUNCTION_ARGS);
+extern Datum array_unnest_support(PG_FUNCTION_ARGS);
+extern Datum gist_box_distance(PG_FUNCTION_ARGS);
+extern Datum brin_summarize_range(PG_FUNCTION_ARGS);
+extern Datum jsonpath_in(PG_FUNCTION_ARGS);
+extern Datum jsonpath_recv(PG_FUNCTION_ARGS);
+extern Datum jsonpath_out(PG_FUNCTION_ARGS);
+extern Datum jsonpath_send(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_exists(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_query(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_query_array(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_query_first(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_match(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_exists_opr(PG_FUNCTION_ARGS);
+extern Datum jsonb_path_match_opr(PG_FUNCTION_ARGS);
+extern Datum brin_desummarize_range(PG_FUNCTION_ARGS);
+extern Datum spg_quad_config(PG_FUNCTION_ARGS);
+extern Datum spg_quad_choose(PG_FUNCTION_ARGS);
+extern Datum spg_quad_picksplit(PG_FUNCTION_ARGS);
+extern Datum spg_quad_inner_consistent(PG_FUNCTION_ARGS);
+extern Datum spg_quad_leaf_consistent(PG_FUNCTION_ARGS);
+extern Datum spg_kd_config(PG_FUNCTION_ARGS);
+extern Datum spg_kd_choose(PG_FUNCTION_ARGS);
+extern Datum spg_kd_picksplit(PG_FUNCTION_ARGS);
+extern Datum spg_kd_inner_consistent(PG_FUNCTION_ARGS);
+extern Datum spg_text_config(PG_FUNCTION_ARGS);
+extern Datum spg_text_choose(PG_FUNCTION_ARGS);
+extern Datum spg_text_picksplit(PG_FUNCTION_ARGS);
+extern Datum spg_text_inner_consistent(PG_FUNCTION_ARGS);
+extern Datum spg_text_leaf_consistent(PG_FUNCTION_ARGS);
+extern Datum pg_sequence_last_value(PG_FUNCTION_ARGS);
+extern Datum jsonb_ne(PG_FUNCTION_ARGS);
+extern Datum jsonb_lt(PG_FUNCTION_ARGS);
+extern Datum jsonb_gt(PG_FUNCTION_ARGS);
+extern Datum jsonb_le(PG_FUNCTION_ARGS);
+extern Datum jsonb_ge(PG_FUNCTION_ARGS);
+extern Datum jsonb_eq(PG_FUNCTION_ARGS);
+extern Datum jsonb_cmp(PG_FUNCTION_ARGS);
+extern Datum jsonb_hash(PG_FUNCTION_ARGS);
+extern Datum jsonb_contains(PG_FUNCTION_ARGS);
+extern Datum jsonb_exists(PG_FUNCTION_ARGS);
+extern Datum jsonb_exists_any(PG_FUNCTION_ARGS);
+extern Datum jsonb_exists_all(PG_FUNCTION_ARGS);
+extern Datum jsonb_contained(PG_FUNCTION_ARGS);
+extern Datum array_agg_array_transfn(PG_FUNCTION_ARGS);
+extern Datum array_agg_array_finalfn(PG_FUNCTION_ARGS);
+extern Datum range_merge(PG_FUNCTION_ARGS);
+extern Datum inet_merge(PG_FUNCTION_ARGS);
+extern Datum boxes_bound_box(PG_FUNCTION_ARGS);
+extern Datum inet_same_family(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_record_init_privs(PG_FUNCTION_ARGS);
+extern Datum regnamespacein(PG_FUNCTION_ARGS);
+extern Datum regnamespaceout(PG_FUNCTION_ARGS);
+extern Datum to_regnamespace(PG_FUNCTION_ARGS);
+extern Datum regnamespacerecv(PG_FUNCTION_ARGS);
+extern Datum regnamespacesend(PG_FUNCTION_ARGS);
+extern Datum point_box(PG_FUNCTION_ARGS);
+extern Datum regroleout(PG_FUNCTION_ARGS);
+extern Datum to_regrole(PG_FUNCTION_ARGS);
+extern Datum regrolerecv(PG_FUNCTION_ARGS);
+extern Datum regrolesend(PG_FUNCTION_ARGS);
+extern Datum regrolein(PG_FUNCTION_ARGS);
+extern Datum pg_rotate_logfile(PG_FUNCTION_ARGS);
+extern Datum pg_read_file(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_missing_value(PG_FUNCTION_ARGS);
+extern Datum brin_inclusion_opcinfo(PG_FUNCTION_ARGS);
+extern Datum brin_inclusion_add_value(PG_FUNCTION_ARGS);
+extern Datum brin_inclusion_consistent(PG_FUNCTION_ARGS);
+extern Datum brin_inclusion_union(PG_FUNCTION_ARGS);
+extern Datum macaddr8_in(PG_FUNCTION_ARGS);
+extern Datum macaddr8_out(PG_FUNCTION_ARGS);
+extern Datum macaddr8_trunc(PG_FUNCTION_ARGS);
+extern Datum macaddr8_eq(PG_FUNCTION_ARGS);
+extern Datum macaddr8_lt(PG_FUNCTION_ARGS);
+extern Datum macaddr8_le(PG_FUNCTION_ARGS);
+extern Datum macaddr8_gt(PG_FUNCTION_ARGS);
+extern Datum macaddr8_ge(PG_FUNCTION_ARGS);
+extern Datum macaddr8_ne(PG_FUNCTION_ARGS);
+extern Datum macaddr8_cmp(PG_FUNCTION_ARGS);
+extern Datum macaddr8_not(PG_FUNCTION_ARGS);
+extern Datum macaddr8_and(PG_FUNCTION_ARGS);
+extern Datum macaddr8_or(PG_FUNCTION_ARGS);
+extern Datum macaddrtomacaddr8(PG_FUNCTION_ARGS);
+extern Datum macaddr8tomacaddr(PG_FUNCTION_ARGS);
+extern Datum macaddr8_set7bit(PG_FUNCTION_ARGS);
+extern Datum in_range_int8_int8(PG_FUNCTION_ARGS);
+extern Datum in_range_int4_int8(PG_FUNCTION_ARGS);
+extern Datum in_range_int4_int4(PG_FUNCTION_ARGS);
+extern Datum in_range_int4_int2(PG_FUNCTION_ARGS);
+extern Datum in_range_int2_int8(PG_FUNCTION_ARGS);
+extern Datum in_range_int2_int4(PG_FUNCTION_ARGS);
+extern Datum in_range_int2_int2(PG_FUNCTION_ARGS);
+extern Datum in_range_date_interval(PG_FUNCTION_ARGS);
+extern Datum in_range_timestamp_interval(PG_FUNCTION_ARGS);
+extern Datum in_range_timestamptz_interval(PG_FUNCTION_ARGS);
+extern Datum in_range_interval_interval(PG_FUNCTION_ARGS);
+extern Datum in_range_time_interval(PG_FUNCTION_ARGS);
+extern Datum in_range_timetz_interval(PG_FUNCTION_ARGS);
+extern Datum in_range_float8_float8(PG_FUNCTION_ARGS);
+extern Datum in_range_float4_float8(PG_FUNCTION_ARGS);
+extern Datum in_range_numeric_numeric(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_larger(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_smaller(PG_FUNCTION_ARGS);
+extern Datum regcollationin(PG_FUNCTION_ARGS);
+extern Datum regcollationout(PG_FUNCTION_ARGS);
+extern Datum to_regcollation(PG_FUNCTION_ARGS);
+extern Datum regcollationrecv(PG_FUNCTION_ARGS);
+extern Datum regcollationsend(PG_FUNCTION_ARGS);
+extern Datum ts_headline_jsonb_byid_opt(PG_FUNCTION_ARGS);
+extern Datum ts_headline_jsonb_byid(PG_FUNCTION_ARGS);
+extern Datum ts_headline_jsonb_opt(PG_FUNCTION_ARGS);
+extern Datum ts_headline_jsonb(PG_FUNCTION_ARGS);
+extern Datum ts_headline_json_byid_opt(PG_FUNCTION_ARGS);
+extern Datum ts_headline_json_byid(PG_FUNCTION_ARGS);
+extern Datum ts_headline_json_opt(PG_FUNCTION_ARGS);
+extern Datum ts_headline_json(PG_FUNCTION_ARGS);
+extern Datum jsonb_string_to_tsvector(PG_FUNCTION_ARGS);
+extern Datum json_string_to_tsvector(PG_FUNCTION_ARGS);
+extern Datum jsonb_string_to_tsvector_byid(PG_FUNCTION_ARGS);
+extern Datum json_string_to_tsvector_byid(PG_FUNCTION_ARGS);
+extern Datum jsonb_to_tsvector(PG_FUNCTION_ARGS);
+extern Datum jsonb_to_tsvector_byid(PG_FUNCTION_ARGS);
+extern Datum json_to_tsvector(PG_FUNCTION_ARGS);
+extern Datum json_to_tsvector_byid(PG_FUNCTION_ARGS);
+extern Datum pg_copy_physical_replication_slot_a(PG_FUNCTION_ARGS);
+extern Datum pg_copy_physical_replication_slot_b(PG_FUNCTION_ARGS);
+extern Datum pg_copy_logical_replication_slot_a(PG_FUNCTION_ARGS);
+extern Datum pg_copy_logical_replication_slot_b(PG_FUNCTION_ARGS);
+extern Datum pg_copy_logical_replication_slot_c(PG_FUNCTION_ARGS);
+extern Datum anycompatiblemultirange_in(PG_FUNCTION_ARGS);
+extern Datum anycompatiblemultirange_out(PG_FUNCTION_ARGS);
+extern Datum range_merge_from_multirange(PG_FUNCTION_ARGS);
+extern Datum anymultirange_in(PG_FUNCTION_ARGS);
+extern Datum anymultirange_out(PG_FUNCTION_ARGS);
+extern Datum multirange_in(PG_FUNCTION_ARGS);
+extern Datum multirange_out(PG_FUNCTION_ARGS);
+extern Datum multirange_recv(PG_FUNCTION_ARGS);
+extern Datum multirange_send(PG_FUNCTION_ARGS);
+extern Datum multirange_lower(PG_FUNCTION_ARGS);
+extern Datum multirange_upper(PG_FUNCTION_ARGS);
+extern Datum multirange_empty(PG_FUNCTION_ARGS);
+extern Datum multirange_lower_inc(PG_FUNCTION_ARGS);
+extern Datum multirange_upper_inc(PG_FUNCTION_ARGS);
+extern Datum multirange_lower_inf(PG_FUNCTION_ARGS);
+extern Datum multirange_upper_inf(PG_FUNCTION_ARGS);
+extern Datum multirange_typanalyze(PG_FUNCTION_ARGS);
+extern Datum multirangesel(PG_FUNCTION_ARGS);
+extern Datum multirange_eq(PG_FUNCTION_ARGS);
+extern Datum multirange_ne(PG_FUNCTION_ARGS);
+extern Datum range_overlaps_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_overlaps_range(PG_FUNCTION_ARGS);
+extern Datum multirange_overlaps_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_contains_elem(PG_FUNCTION_ARGS);
+extern Datum multirange_contains_range(PG_FUNCTION_ARGS);
+extern Datum multirange_contains_multirange(PG_FUNCTION_ARGS);
+extern Datum elem_contained_by_multirange(PG_FUNCTION_ARGS);
+extern Datum range_contained_by_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_contained_by_multirange(PG_FUNCTION_ARGS);
+extern Datum range_adjacent_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_adjacent_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_adjacent_range(PG_FUNCTION_ARGS);
+extern Datum range_before_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_before_range(PG_FUNCTION_ARGS);
+extern Datum multirange_before_multirange(PG_FUNCTION_ARGS);
+extern Datum range_after_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_after_range(PG_FUNCTION_ARGS);
+extern Datum multirange_after_multirange(PG_FUNCTION_ARGS);
+extern Datum range_overleft_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_overleft_range(PG_FUNCTION_ARGS);
+extern Datum multirange_overleft_multirange(PG_FUNCTION_ARGS);
+extern Datum range_overright_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_overright_range(PG_FUNCTION_ARGS);
+extern Datum multirange_overright_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_union(PG_FUNCTION_ARGS);
+extern Datum multirange_minus(PG_FUNCTION_ARGS);
+extern Datum multirange_intersect(PG_FUNCTION_ARGS);
+extern Datum multirange_cmp(PG_FUNCTION_ARGS);
+extern Datum multirange_lt(PG_FUNCTION_ARGS);
+extern Datum multirange_le(PG_FUNCTION_ARGS);
+extern Datum multirange_ge(PG_FUNCTION_ARGS);
+extern Datum multirange_gt(PG_FUNCTION_ARGS);
+extern Datum hash_multirange(PG_FUNCTION_ARGS);
+extern Datum hash_multirange_extended(PG_FUNCTION_ARGS);
+extern Datum multirange_constructor0(PG_FUNCTION_ARGS);
+extern Datum multirange_constructor1(PG_FUNCTION_ARGS);
+extern Datum multirange_constructor2(PG_FUNCTION_ARGS);
+extern Datum range_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum range_agg_finalfn(PG_FUNCTION_ARGS);
+extern Datum unicode_normalize_func(PG_FUNCTION_ARGS);
+extern Datum unicode_is_normalized(PG_FUNCTION_ARGS);
+extern Datum multirange_intersect_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_multirange_pg_type_oid(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_multirange_array_pg_type_oid(PG_FUNCTION_ARGS);
+extern Datum range_intersect_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum range_contains_multirange(PG_FUNCTION_ARGS);
+extern Datum multirange_contained_by_range(PG_FUNCTION_ARGS);
+extern Datum pg_log_backend_memory_contexts(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_heap_relfilenode(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_index_relfilenode(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_toast_relfilenode(PG_FUNCTION_ARGS);
+extern Datum binary_upgrade_set_next_pg_tablespace_oid(PG_FUNCTION_ARGS);
+extern Datum pg_event_trigger_table_rewrite_oid(PG_FUNCTION_ARGS);
+extern Datum pg_event_trigger_table_rewrite_reason(PG_FUNCTION_ARGS);
+extern Datum pg_event_trigger_ddl_commands(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_opcinfo(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_add_value(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_consistent(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_union(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_options(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_summary_in(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_summary_out(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_summary_recv(PG_FUNCTION_ARGS);
+extern Datum brin_bloom_summary_send(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_opcinfo(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_add_value(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_consistent(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_union(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_options(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_int2(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_int4(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_int8(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_float4(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_float8(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_numeric(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_tid(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_uuid(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_date(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_time(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_interval(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_timetz(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_pg_lsn(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_macaddr(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_macaddr8(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_inet(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_distance_timestamp(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_summary_in(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_summary_out(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_summary_recv(PG_FUNCTION_ARGS);
+extern Datum brin_minmax_multi_summary_send(PG_FUNCTION_ARGS);
+extern Datum phraseto_tsquery(PG_FUNCTION_ARGS);
+extern Datum tsquery_phrase(PG_FUNCTION_ARGS);
+extern Datum tsquery_phrase_distance(PG_FUNCTION_ARGS);
+extern Datum phraseto_tsquery_byid(PG_FUNCTION_ARGS);
+extern Datum websearch_to_tsquery_byid(PG_FUNCTION_ARGS);
+extern Datum websearch_to_tsquery(PG_FUNCTION_ARGS);
+extern Datum spg_bbox_quad_config(PG_FUNCTION_ARGS);
+extern Datum spg_poly_quad_compress(PG_FUNCTION_ARGS);
+extern Datum spg_box_quad_config(PG_FUNCTION_ARGS);
+extern Datum spg_box_quad_choose(PG_FUNCTION_ARGS);
+extern Datum spg_box_quad_picksplit(PG_FUNCTION_ARGS);
+extern Datum spg_box_quad_inner_consistent(PG_FUNCTION_ARGS);
+extern Datum spg_box_quad_leaf_consistent(PG_FUNCTION_ARGS);
+extern Datum pg_mcv_list_in(PG_FUNCTION_ARGS);
+extern Datum pg_mcv_list_out(PG_FUNCTION_ARGS);
+extern Datum pg_mcv_list_recv(PG_FUNCTION_ARGS);
+extern Datum pg_mcv_list_send(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_pli(PG_FUNCTION_ARGS);
+extern Datum pg_lsn_mii(PG_FUNCTION_ARGS);
+extern Datum satisfies_hash_partition(PG_FUNCTION_ARGS);
+extern Datum pg_ls_tmpdir_noargs(PG_FUNCTION_ARGS);
+extern Datum pg_ls_tmpdir_1arg(PG_FUNCTION_ARGS);
+extern Datum pg_ls_archive_statusdir(PG_FUNCTION_ARGS);
+extern Datum network_sortsupport(PG_FUNCTION_ARGS);
+extern Datum xid8lt(PG_FUNCTION_ARGS);
+extern Datum xid8gt(PG_FUNCTION_ARGS);
+extern Datum xid8le(PG_FUNCTION_ARGS);
+extern Datum xid8ge(PG_FUNCTION_ARGS);
+extern Datum matchingsel(PG_FUNCTION_ARGS);
+extern Datum matchingjoinsel(PG_FUNCTION_ARGS);
+extern Datum numeric_min_scale(PG_FUNCTION_ARGS);
+extern Datum numeric_trim_scale(PG_FUNCTION_ARGS);
+extern Datum int4gcd(PG_FUNCTION_ARGS);
+extern Datum int8gcd(PG_FUNCTION_ARGS);
+extern Datum int4lcm(PG_FUNCTION_ARGS);
+extern Datum int8lcm(PG_FUNCTION_ARGS);
+extern Datum numeric_gcd(PG_FUNCTION_ARGS);
+extern Datum numeric_lcm(PG_FUNCTION_ARGS);
+extern Datum btvarstrequalimage(PG_FUNCTION_ARGS);
+extern Datum btequalimage(PG_FUNCTION_ARGS);
+extern Datum pg_get_shmem_allocations(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_ins_since_vacuum(PG_FUNCTION_ARGS);
+extern Datum jsonb_set_lax(PG_FUNCTION_ARGS);
+extern Datum xid8in(PG_FUNCTION_ARGS);
+extern Datum xid8toxid(PG_FUNCTION_ARGS);
+extern Datum xid8out(PG_FUNCTION_ARGS);
+extern Datum xid8recv(PG_FUNCTION_ARGS);
+extern Datum xid8send(PG_FUNCTION_ARGS);
+extern Datum xid8eq(PG_FUNCTION_ARGS);
+extern Datum xid8ne(PG_FUNCTION_ARGS);
+extern Datum anycompatible_in(PG_FUNCTION_ARGS);
+extern Datum anycompatible_out(PG_FUNCTION_ARGS);
+extern Datum anycompatiblearray_in(PG_FUNCTION_ARGS);
+extern Datum anycompatiblearray_out(PG_FUNCTION_ARGS);
+extern Datum anycompatiblearray_recv(PG_FUNCTION_ARGS);
+extern Datum anycompatiblearray_send(PG_FUNCTION_ARGS);
+extern Datum anycompatiblenonarray_in(PG_FUNCTION_ARGS);
+extern Datum anycompatiblenonarray_out(PG_FUNCTION_ARGS);
+extern Datum anycompatiblerange_in(PG_FUNCTION_ARGS);
+extern Datum anycompatiblerange_out(PG_FUNCTION_ARGS);
+extern Datum xid8cmp(PG_FUNCTION_ARGS);
+extern Datum xid8_larger(PG_FUNCTION_ARGS);
+extern Datum xid8_smaller(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_create(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_drop(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_oid(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_session_setup(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_session_reset(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_session_is_setup(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_session_progress(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_xact_setup(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_xact_reset(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_advance(PG_FUNCTION_ARGS);
+extern Datum pg_replication_origin_progress(PG_FUNCTION_ARGS);
+extern Datum pg_show_replication_origin_status(PG_FUNCTION_ARGS);
+extern Datum jsonb_subscript_handler(PG_FUNCTION_ARGS);
+extern Datum numeric_pg_lsn(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_backend_subxact(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_subscription(PG_FUNCTION_ARGS);
+extern Datum pg_get_publication_tables(PG_FUNCTION_ARGS);
+extern Datum pg_get_replica_identity_index(PG_FUNCTION_ARGS);
+extern Datum pg_relation_is_publishable(PG_FUNCTION_ARGS);
+extern Datum multirange_gist_consistent(PG_FUNCTION_ARGS);
+extern Datum multirange_gist_compress(PG_FUNCTION_ARGS);
+extern Datum pg_get_catalog_foreign_keys(PG_FUNCTION_ARGS);
+extern Datum text_to_table(PG_FUNCTION_ARGS);
+extern Datum text_to_table_null(PG_FUNCTION_ARGS);
+extern Datum bit_bit_count(PG_FUNCTION_ARGS);
+extern Datum bytea_bit_count(PG_FUNCTION_ARGS);
+extern Datum pg_xact_commit_timestamp_origin(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_replication_slot(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset_replication_slot(PG_FUNCTION_ARGS);
+extern Datum trim_array(PG_FUNCTION_ARGS);
+extern Datum pg_get_statisticsobjdef_expressions(PG_FUNCTION_ARGS);
+extern Datum pg_get_statisticsobjdef_columns(PG_FUNCTION_ARGS);
+extern Datum timestamp_bin(PG_FUNCTION_ARGS);
+extern Datum timestamptz_bin(PG_FUNCTION_ARGS);
+extern Datum array_subscript_handler(PG_FUNCTION_ARGS);
+extern Datum raw_array_subscript_handler(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_session_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_active_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_idle_in_transaction_time(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_sessions(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_sessions_abandoned(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_sessions_fatal(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_sessions_killed(PG_FUNCTION_ARGS);
+extern Datum hash_record(PG_FUNCTION_ARGS);
+extern Datum hash_record_extended(PG_FUNCTION_ARGS);
+extern Datum bytealtrim(PG_FUNCTION_ARGS);
+extern Datum byteartrim(PG_FUNCTION_ARGS);
+extern Datum pg_get_function_sqlbody(PG_FUNCTION_ARGS);
+extern Datum unistr(PG_FUNCTION_ARGS);
+extern Datum extract_date(PG_FUNCTION_ARGS);
+extern Datum extract_time(PG_FUNCTION_ARGS);
+extern Datum extract_timetz(PG_FUNCTION_ARGS);
+extern Datum extract_timestamp(PG_FUNCTION_ARGS);
+extern Datum extract_timestamptz(PG_FUNCTION_ARGS);
+extern Datum extract_interval(PG_FUNCTION_ARGS);
+extern Datum has_parameter_privilege_name_name(PG_FUNCTION_ARGS);
+extern Datum has_parameter_privilege_id_name(PG_FUNCTION_ARGS);
+extern Datum has_parameter_privilege_name(PG_FUNCTION_ARGS);
+extern Datum pg_read_file_all_missing(PG_FUNCTION_ARGS);
+extern Datum pg_read_binary_file_all_missing(PG_FUNCTION_ARGS);
+extern Datum pg_input_is_valid(PG_FUNCTION_ARGS);
+extern Datum pg_input_error_info(PG_FUNCTION_ARGS);
+extern Datum drandom_normal(PG_FUNCTION_ARGS);
+extern Datum pg_split_walfile_name(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_io(PG_FUNCTION_ARGS);
+extern Datum array_shuffle(PG_FUNCTION_ARGS);
+extern Datum array_sample(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_tuples_newpage_updated(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_xact_tuples_newpage_updated(PG_FUNCTION_ARGS);
+extern Datum derf(PG_FUNCTION_ARGS);
+extern Datum derfc(PG_FUNCTION_ARGS);
+extern Datum timestamptz_pl_interval_at_zone(PG_FUNCTION_ARGS);
+extern Datum pg_get_wal_resource_managers(PG_FUNCTION_ARGS);
+extern Datum multirange_agg_transfn(PG_FUNCTION_ARGS);
+extern Datum pg_stat_have_stats(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_subscription_stats(PG_FUNCTION_ARGS);
+extern Datum pg_stat_reset_subscription_stats(PG_FUNCTION_ARGS);
+extern Datum window_row_number_support(PG_FUNCTION_ARGS);
+extern Datum window_rank_support(PG_FUNCTION_ARGS);
+extern Datum window_dense_rank_support(PG_FUNCTION_ARGS);
+extern Datum int8inc_support(PG_FUNCTION_ARGS);
+extern Datum pg_settings_get_flags(PG_FUNCTION_ARGS);
+extern Datum pg_stop_making_pinned_objects(PG_FUNCTION_ARGS);
+extern Datum text_starts_with_support(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_recovery_prefetch(PG_FUNCTION_ARGS);
+extern Datum pg_database_collation_actual_version(PG_FUNCTION_ARGS);
+extern Datum pg_ident_file_mappings(PG_FUNCTION_ARGS);
+extern Datum textregexreplace_extended(PG_FUNCTION_ARGS);
+extern Datum textregexreplace_extended_no_flags(PG_FUNCTION_ARGS);
+extern Datum textregexreplace_extended_no_n(PG_FUNCTION_ARGS);
+extern Datum regexp_count_no_start(PG_FUNCTION_ARGS);
+extern Datum regexp_count_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_count(PG_FUNCTION_ARGS);
+extern Datum regexp_instr_no_start(PG_FUNCTION_ARGS);
+extern Datum regexp_instr_no_n(PG_FUNCTION_ARGS);
+extern Datum regexp_instr_no_endoption(PG_FUNCTION_ARGS);
+extern Datum regexp_instr_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_instr_no_subexpr(PG_FUNCTION_ARGS);
+extern Datum regexp_instr(PG_FUNCTION_ARGS);
+extern Datum regexp_like_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_like(PG_FUNCTION_ARGS);
+extern Datum regexp_substr_no_start(PG_FUNCTION_ARGS);
+extern Datum regexp_substr_no_n(PG_FUNCTION_ARGS);
+extern Datum regexp_substr_no_flags(PG_FUNCTION_ARGS);
+extern Datum regexp_substr_no_subexpr(PG_FUNCTION_ARGS);
+extern Datum regexp_substr(PG_FUNCTION_ARGS);
+extern Datum pg_ls_logicalsnapdir(PG_FUNCTION_ARGS);
+extern Datum pg_ls_logicalmapdir(PG_FUNCTION_ARGS);
+extern Datum pg_ls_replslotdir(PG_FUNCTION_ARGS);
+extern Datum timestamptz_mi_interval_at_zone(PG_FUNCTION_ARGS);
+extern Datum generate_series_timestamptz_at_zone(PG_FUNCTION_ARGS);
+extern Datum json_agg_strict_transfn(PG_FUNCTION_ARGS);
+extern Datum json_object_agg_strict_transfn(PG_FUNCTION_ARGS);
+extern Datum json_object_agg_unique_transfn(PG_FUNCTION_ARGS);
+extern Datum json_object_agg_unique_strict_transfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_agg_strict_transfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_agg_strict_transfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_agg_unique_transfn(PG_FUNCTION_ARGS);
+extern Datum jsonb_object_agg_unique_strict_transfn(PG_FUNCTION_ARGS);
+extern Datum any_value_transfn(PG_FUNCTION_ARGS);
+extern Datum array_agg_combine(PG_FUNCTION_ARGS);
+extern Datum array_agg_serialize(PG_FUNCTION_ARGS);
+extern Datum array_agg_deserialize(PG_FUNCTION_ARGS);
+extern Datum array_agg_array_combine(PG_FUNCTION_ARGS);
+extern Datum array_agg_array_serialize(PG_FUNCTION_ARGS);
+extern Datum array_agg_array_deserialize(PG_FUNCTION_ARGS);
+extern Datum string_agg_combine(PG_FUNCTION_ARGS);
+extern Datum string_agg_serialize(PG_FUNCTION_ARGS);
+extern Datum string_agg_deserialize(PG_FUNCTION_ARGS);
+extern Datum pg_log_standby_snapshot(PG_FUNCTION_ARGS);
+extern Datum window_percent_rank_support(PG_FUNCTION_ARGS);
+extern Datum window_cume_dist_support(PG_FUNCTION_ARGS);
+extern Datum window_ntile_support(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_db_conflict_logicalslot(PG_FUNCTION_ARGS);
+extern Datum pg_stat_get_lastscan(PG_FUNCTION_ARGS);
+extern Datum system_user(PG_FUNCTION_ARGS);
+
+#endif /* FMGRPROTOS_H */
diff --git a/pgsql/include/server/utils/fmgrtab.h b/pgsql/include/server/utils/fmgrtab.h
new file mode 100644
index 0000000000000000000000000000000000000000..838ffe3bc1c2d2c22b3dc4fffc6f733819ed76dc
--- /dev/null
+++ b/pgsql/include/server/utils/fmgrtab.h
@@ -0,0 +1,49 @@
+/*-------------------------------------------------------------------------
+ *
+ * fmgrtab.h
+ * The function manager's table of internal functions.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/fmgrtab.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef FMGRTAB_H
+#define FMGRTAB_H
+
+#include "access/transam.h"
+#include "fmgr.h"
+
+
+/*
+ * This table stores info about all the built-in functions (ie, functions
+ * that are compiled into the Postgres executable).
+ */
+
+typedef struct
+{
+ Oid foid; /* OID of the function */
+ short nargs; /* 0..FUNC_MAX_ARGS, or -1 if variable count */
+ bool strict; /* T if function is "strict" */
+ bool retset; /* T if function returns a set */
+ const char *funcName; /* C name of the function */
+ PGFunction func; /* pointer to compiled function */
+} FmgrBuiltin;
+
+extern PGDLLIMPORT const FmgrBuiltin fmgr_builtins[];
+
+extern PGDLLIMPORT const int fmgr_nbuiltins; /* number of entries in table */
+
+extern PGDLLIMPORT const Oid fmgr_last_builtin_oid; /* highest function OID in
+ * table */
+
+/*
+ * Mapping from a builtin function's OID to its index in the fmgr_builtins
+ * array. This is indexed from 0 through fmgr_last_builtin_oid.
+ */
+#define InvalidOidBuiltinMapping PG_UINT16_MAX
+extern PGDLLIMPORT const uint16 fmgr_builtin_oid_index[];
+
+#endif /* FMGRTAB_H */
diff --git a/pgsql/include/server/utils/formatting.h b/pgsql/include/server/utils/formatting.h
new file mode 100644
index 0000000000000000000000000000000000000000..0cad3a2709040b98239fa1cfa28932968d69d83f
--- /dev/null
+++ b/pgsql/include/server/utils/formatting.h
@@ -0,0 +1,33 @@
+/* -----------------------------------------------------------------------
+ * formatting.h
+ *
+ * src/include/utils/formatting.h
+ *
+ *
+ * Portions Copyright (c) 1999-2023, PostgreSQL Global Development Group
+ *
+ * The PostgreSQL routines for a DateTime/int/float/numeric formatting,
+ * inspired by the Oracle TO_CHAR() / TO_DATE() / TO_NUMBER() routines.
+ *
+ * Karel Zak
+ *
+ * -----------------------------------------------------------------------
+ */
+
+#ifndef _FORMATTING_H_
+#define _FORMATTING_H_
+
+
+extern char *str_tolower(const char *buff, size_t nbytes, Oid collid);
+extern char *str_toupper(const char *buff, size_t nbytes, Oid collid);
+extern char *str_initcap(const char *buff, size_t nbytes, Oid collid);
+
+extern char *asc_tolower(const char *buff, size_t nbytes);
+extern char *asc_toupper(const char *buff, size_t nbytes);
+extern char *asc_initcap(const char *buff, size_t nbytes);
+
+extern Datum parse_datetime(text *date_txt, text *fmt, Oid collid, bool strict,
+ Oid *typid, int32 *typmod, int *tz,
+ struct Node *escontext);
+
+#endif
diff --git a/pgsql/include/server/utils/freepage.h b/pgsql/include/server/utils/freepage.h
new file mode 100644
index 0000000000000000000000000000000000000000..8d1ebb4c47cff9b6db8cd2300fdac169d29c1e94
--- /dev/null
+++ b/pgsql/include/server/utils/freepage.h
@@ -0,0 +1,99 @@
+/*-------------------------------------------------------------------------
+ *
+ * freepage.h
+ * Management of page-organized free memory.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/freepage.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef FREEPAGE_H
+#define FREEPAGE_H
+
+#include "storage/lwlock.h"
+#include "utils/relptr.h"
+
+/* Forward declarations. */
+typedef struct FreePageSpanLeader FreePageSpanLeader;
+typedef struct FreePageBtree FreePageBtree;
+typedef struct FreePageManager FreePageManager;
+
+/*
+ * PostgreSQL normally uses 8kB pages for most things, but many common
+ * architecture/operating system pairings use a 4kB page size for memory
+ * allocation, so we do that here also.
+ */
+#define FPM_PAGE_SIZE 4096
+
+/*
+ * Each freelist except for the last contains only spans of one particular
+ * size. Everything larger goes on the last one. In some sense this seems
+ * like a waste since most allocations are in a few common sizes, but it
+ * means that small allocations can simply pop the head of the relevant list
+ * without needing to worry about whether the object we find there is of
+ * precisely the correct size (because we know it must be).
+ */
+#define FPM_NUM_FREELISTS 129
+
+/* Define relative pointer types. */
+relptr_declare(FreePageBtree, RelptrFreePageBtree);
+relptr_declare(FreePageManager, RelptrFreePageManager);
+relptr_declare(FreePageSpanLeader, RelptrFreePageSpanLeader);
+
+/* Everything we need in order to manage free pages (see freepage.c) */
+struct FreePageManager
+{
+ RelptrFreePageManager self;
+ RelptrFreePageBtree btree_root;
+ RelptrFreePageSpanLeader btree_recycle;
+ unsigned btree_depth;
+ unsigned btree_recycle_count;
+ Size singleton_first_page;
+ Size singleton_npages;
+ Size contiguous_pages;
+ bool contiguous_pages_dirty;
+ RelptrFreePageSpanLeader freelist[FPM_NUM_FREELISTS];
+#ifdef FPM_EXTRA_ASSERTS
+ /* For debugging only, pages put minus pages gotten. */
+ Size free_pages;
+#endif
+};
+
+/* Macros to convert between page numbers (expressed as Size) and pointers. */
+#define fpm_page_to_pointer(base, page) \
+ (AssertVariableIsOfTypeMacro(page, Size), \
+ (base) + FPM_PAGE_SIZE * (page))
+#define fpm_pointer_to_page(base, ptr) \
+ (((Size) (((char *) (ptr)) - (base))) / FPM_PAGE_SIZE)
+
+/* Macro to convert an allocation size to a number of pages. */
+#define fpm_size_to_pages(sz) \
+ (((sz) + FPM_PAGE_SIZE - 1) / FPM_PAGE_SIZE)
+
+/* Macros to check alignment of absolute and relative pointers. */
+#define fpm_pointer_is_page_aligned(base, ptr) \
+ (((Size) (((char *) (ptr)) - (base))) % FPM_PAGE_SIZE == 0)
+#define fpm_relptr_is_page_aligned(base, relptr) \
+ (relptr_offset(relptr) % FPM_PAGE_SIZE == 0)
+
+/* Macro to find base address of the segment containing a FreePageManager. */
+#define fpm_segment_base(fpm) \
+ (((char *) fpm) - relptr_offset(fpm->self))
+
+/* Macro to access a FreePageManager's largest consecutive run of pages. */
+#define fpm_largest(fpm) \
+ (fpm->contiguous_pages)
+
+/* Functions to manipulate the free page map. */
+extern void FreePageManagerInitialize(FreePageManager *fpm, char *base);
+extern bool FreePageManagerGet(FreePageManager *fpm, Size npages,
+ Size *first_page);
+extern void FreePageManagerPut(FreePageManager *fpm, Size first_page,
+ Size npages);
+extern char *FreePageManagerDump(FreePageManager *fpm);
+
+#endif /* FREEPAGE_H */
diff --git a/pgsql/include/server/utils/geo_decls.h b/pgsql/include/server/utils/geo_decls.h
new file mode 100644
index 0000000000000000000000000000000000000000..d176f589d4b6593dc82a17ac48c21f76f8ea6a85
--- /dev/null
+++ b/pgsql/include/server/utils/geo_decls.h
@@ -0,0 +1,285 @@
+/*-------------------------------------------------------------------------
+ *
+ * geo_decls.h - Declarations for various 2D constructs.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/geo_decls.h
+ *
+ * XXX These routines were not written by a numerical analyst.
+ *
+ * XXX I have made some attempt to flesh out the operators
+ * and data types. There are still some more to do. - tgl 97/04/19
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef GEO_DECLS_H
+#define GEO_DECLS_H
+
+#include
+
+#include "fmgr.h"
+
+/*--------------------------------------------------------------------
+ * Useful floating point utilities and constants.
+ *--------------------------------------------------------------------
+ *
+ * "Fuzzy" floating-point comparisons: values within EPSILON of each other
+ * are considered equal. Beware of normal reasoning about the behavior of
+ * these comparisons, since for example FPeq does not behave transitively.
+ *
+ * Note that these functions are not NaN-aware and will give FALSE for
+ * any case involving NaN inputs.
+ *
+ * Also note that these will give sane answers for infinite inputs,
+ * where it's important to avoid computing Inf minus Inf; we do so
+ * by eliminating equality cases before subtracting.
+ */
+
+#define EPSILON 1.0E-06
+
+#ifdef EPSILON
+#define FPzero(A) (fabs(A) <= EPSILON)
+
+static inline bool
+FPeq(double A, double B)
+{
+ return A == B || fabs(A - B) <= EPSILON;
+}
+
+static inline bool
+FPne(double A, double B)
+{
+ return A != B && fabs(A - B) > EPSILON;
+}
+
+static inline bool
+FPlt(double A, double B)
+{
+ return A + EPSILON < B;
+}
+
+static inline bool
+FPle(double A, double B)
+{
+ return A <= B + EPSILON;
+}
+
+static inline bool
+FPgt(double A, double B)
+{
+ return A > B + EPSILON;
+}
+
+static inline bool
+FPge(double A, double B)
+{
+ return A + EPSILON >= B;
+}
+#else
+#define FPzero(A) ((A) == 0)
+#define FPeq(A,B) ((A) == (B))
+#define FPne(A,B) ((A) != (B))
+#define FPlt(A,B) ((A) < (B))
+#define FPle(A,B) ((A) <= (B))
+#define FPgt(A,B) ((A) > (B))
+#define FPge(A,B) ((A) >= (B))
+#endif
+
+#define HYPOT(A, B) pg_hypot(A, B)
+
+/*---------------------------------------------------------------------
+ * Point - (x,y)
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ float8 x,
+ y;
+} Point;
+
+
+/*---------------------------------------------------------------------
+ * LSEG - A straight line, specified by endpoints.
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ Point p[2];
+} LSEG;
+
+
+/*---------------------------------------------------------------------
+ * PATH - Specified by vertex points.
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int32 npts;
+ int32 closed; /* is this a closed polygon? */
+ int32 dummy; /* padding to make it double align */
+ Point p[FLEXIBLE_ARRAY_MEMBER];
+} PATH;
+
+
+/*---------------------------------------------------------------------
+ * LINE - Specified by its general equation (Ax+By+C=0).
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ float8 A,
+ B,
+ C;
+} LINE;
+
+
+/*---------------------------------------------------------------------
+ * BOX - Specified by two corner points, which are
+ * sorted to save calculation time later.
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ Point high,
+ low; /* corner POINTs */
+} BOX;
+
+/*---------------------------------------------------------------------
+ * POLYGON - Specified by an array of doubles defining the points,
+ * keeping the number of points and the bounding box for
+ * speed purposes.
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int32 npts;
+ BOX boundbox;
+ Point p[FLEXIBLE_ARRAY_MEMBER];
+} POLYGON;
+
+/*---------------------------------------------------------------------
+ * CIRCLE - Specified by a center point and radius.
+ *-------------------------------------------------------------------*/
+typedef struct
+{
+ Point center;
+ float8 radius;
+} CIRCLE;
+
+/*
+ * fmgr interface functions
+ *
+ * Path and Polygon are toastable varlena types, the others are just
+ * fixed-size pass-by-reference types.
+ */
+
+static inline Point *
+DatumGetPointP(Datum X)
+{
+ return (Point *) DatumGetPointer(X);
+}
+static inline Datum
+PointPGetDatum(const Point *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_POINT_P(n) DatumGetPointP(PG_GETARG_DATUM(n))
+#define PG_RETURN_POINT_P(x) return PointPGetDatum(x)
+
+static inline LSEG *
+DatumGetLsegP(Datum X)
+{
+ return (LSEG *) DatumGetPointer(X);
+}
+static inline Datum
+LsegPGetDatum(const LSEG *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_LSEG_P(n) DatumGetLsegP(PG_GETARG_DATUM(n))
+#define PG_RETURN_LSEG_P(x) return LsegPGetDatum(x)
+
+static inline PATH *
+DatumGetPathP(Datum X)
+{
+ return (PATH *) PG_DETOAST_DATUM(X);
+}
+static inline PATH *
+DatumGetPathPCopy(Datum X)
+{
+ return (PATH *) PG_DETOAST_DATUM_COPY(X);
+}
+static inline Datum
+PathPGetDatum(const PATH *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_PATH_P(n) DatumGetPathP(PG_GETARG_DATUM(n))
+#define PG_GETARG_PATH_P_COPY(n) DatumGetPathPCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_PATH_P(x) return PathPGetDatum(x)
+
+static inline LINE *
+DatumGetLineP(Datum X)
+{
+ return (LINE *) DatumGetPointer(X);
+}
+static inline Datum
+LinePGetDatum(const LINE *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_LINE_P(n) DatumGetLineP(PG_GETARG_DATUM(n))
+#define PG_RETURN_LINE_P(x) return LinePGetDatum(x)
+
+static inline BOX *
+DatumGetBoxP(Datum X)
+{
+ return (BOX *) DatumGetPointer(X);
+}
+static inline Datum
+BoxPGetDatum(const BOX *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_BOX_P(n) DatumGetBoxP(PG_GETARG_DATUM(n))
+#define PG_RETURN_BOX_P(x) return BoxPGetDatum(x)
+
+static inline POLYGON *
+DatumGetPolygonP(Datum X)
+{
+ return (POLYGON *) PG_DETOAST_DATUM(X);
+}
+static inline POLYGON *
+DatumGetPolygonPCopy(Datum X)
+{
+ return (POLYGON *) PG_DETOAST_DATUM_COPY(X);
+}
+static inline Datum
+PolygonPGetDatum(const POLYGON *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_POLYGON_P(n) DatumGetPolygonP(PG_GETARG_DATUM(n))
+#define PG_GETARG_POLYGON_P_COPY(n) DatumGetPolygonPCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_POLYGON_P(x) return PolygonPGetDatum(x)
+
+static inline CIRCLE *
+DatumGetCircleP(Datum X)
+{
+ return (CIRCLE *) DatumGetPointer(X);
+}
+static inline Datum
+CirclePGetDatum(const CIRCLE *X)
+{
+ return PointerGetDatum(X);
+}
+#define PG_GETARG_CIRCLE_P(n) DatumGetCircleP(PG_GETARG_DATUM(n))
+#define PG_RETURN_CIRCLE_P(x) return CirclePGetDatum(x)
+
+
+/*
+ * in geo_ops.c
+ */
+
+extern float8 pg_hypot(float8 x, float8 y);
+
+#endif /* GEO_DECLS_H */
diff --git a/pgsql/include/server/utils/guc.h b/pgsql/include/server/utils/guc.h
new file mode 100644
index 0000000000000000000000000000000000000000..d5253c7ed23d23db6031a62e3c59e7a71893d169
--- /dev/null
+++ b/pgsql/include/server/utils/guc.h
@@ -0,0 +1,442 @@
+/*--------------------------------------------------------------------
+ * guc.h
+ *
+ * External declarations pertaining to Grand Unified Configuration.
+ *
+ * Copyright (c) 2000-2023, PostgreSQL Global Development Group
+ * Written by Peter Eisentraut .
+ *
+ * src/include/utils/guc.h
+ *--------------------------------------------------------------------
+ */
+#ifndef GUC_H
+#define GUC_H
+
+#include "nodes/parsenodes.h"
+#include "tcop/dest.h"
+#include "utils/array.h"
+
+
+/* upper limit for GUC variables measured in kilobytes of memory */
+/* note that various places assume the byte size fits in a "long" variable */
+#if SIZEOF_SIZE_T > 4 && SIZEOF_LONG > 4
+#define MAX_KILOBYTES INT_MAX
+#else
+#define MAX_KILOBYTES (INT_MAX / 1024)
+#endif
+
+/*
+ * Automatic configuration file name for ALTER SYSTEM.
+ * This file will be used to store values of configuration parameters
+ * set by ALTER SYSTEM command.
+ */
+#define PG_AUTOCONF_FILENAME "postgresql.auto.conf"
+
+/*
+ * Certain options can only be set at certain times. The rules are
+ * like this:
+ *
+ * INTERNAL options cannot be set by the user at all, but only through
+ * internal processes ("server_version" is an example). These are GUC
+ * variables only so they can be shown by SHOW, etc.
+ *
+ * POSTMASTER options can only be set when the postmaster starts,
+ * either from the configuration file or the command line.
+ *
+ * SIGHUP options can only be set at postmaster startup or by changing
+ * the configuration file and sending the HUP signal to the postmaster
+ * or a backend process. (Notice that the signal receipt will not be
+ * evaluated immediately. The postmaster and the backend check it at a
+ * certain point in their main loop. It's safer to wait than to read a
+ * file asynchronously.)
+ *
+ * BACKEND and SU_BACKEND options can only be set at postmaster startup,
+ * from the configuration file, or by client request in the connection
+ * startup packet (e.g., from libpq's PGOPTIONS variable). SU_BACKEND
+ * options can be set from the startup packet only when the user is a
+ * superuser. Furthermore, an already-started backend will ignore changes
+ * to such an option in the configuration file. The idea is that these
+ * options are fixed for a given backend once it's started, but they can
+ * vary across backends.
+ *
+ * SUSET options can be set at postmaster startup, with the SIGHUP
+ * mechanism, or from the startup packet or SQL if you're a superuser.
+ *
+ * USERSET options can be set by anyone any time.
+ */
+typedef enum
+{
+ PGC_INTERNAL,
+ PGC_POSTMASTER,
+ PGC_SIGHUP,
+ PGC_SU_BACKEND,
+ PGC_BACKEND,
+ PGC_SUSET,
+ PGC_USERSET
+} GucContext;
+
+/*
+ * The following type records the source of the current setting. A
+ * new setting can only take effect if the previous setting had the
+ * same or lower level. (E.g, changing the config file doesn't
+ * override the postmaster command line.) Tracking the source allows us
+ * to process sources in any convenient order without affecting results.
+ * Sources <= PGC_S_OVERRIDE will set the default used by RESET, as well
+ * as the current value.
+ *
+ * PGC_S_INTERACTIVE isn't actually a source value, but is the
+ * dividing line between "interactive" and "non-interactive" sources for
+ * error reporting purposes.
+ *
+ * PGC_S_TEST is used when testing values to be used later. For example,
+ * ALTER DATABASE/ROLE tests proposed per-database or per-user defaults this
+ * way, and CREATE FUNCTION tests proposed function SET clauses this way.
+ * This is an interactive case, but it needs its own source value because
+ * some assign hooks need to make different validity checks in this case.
+ * In particular, references to nonexistent database objects generally
+ * shouldn't throw hard errors in this case, at most NOTICEs, since the
+ * objects might exist by the time the setting is used for real.
+ *
+ * When setting the value of a non-compile-time-constant PGC_INTERNAL option,
+ * source == PGC_S_DYNAMIC_DEFAULT should typically be used so that the value
+ * will show as "default" in pg_settings. If there is a specific reason not
+ * to want that, use source == PGC_S_OVERRIDE.
+ *
+ * NB: see GucSource_Names in guc.c if you change this.
+ */
+typedef enum
+{
+ PGC_S_DEFAULT, /* hard-wired default ("boot_val") */
+ PGC_S_DYNAMIC_DEFAULT, /* default computed during initialization */
+ PGC_S_ENV_VAR, /* postmaster environment variable */
+ PGC_S_FILE, /* postgresql.conf */
+ PGC_S_ARGV, /* postmaster command line */
+ PGC_S_GLOBAL, /* global in-database setting */
+ PGC_S_DATABASE, /* per-database setting */
+ PGC_S_USER, /* per-user setting */
+ PGC_S_DATABASE_USER, /* per-user-and-database setting */
+ PGC_S_CLIENT, /* from client connection request */
+ PGC_S_OVERRIDE, /* special case to forcibly set default */
+ PGC_S_INTERACTIVE, /* dividing line for error reporting */
+ PGC_S_TEST, /* test per-database or per-user setting */
+ PGC_S_SESSION /* SET command */
+} GucSource;
+
+/*
+ * Parsing the configuration file(s) will return a list of name-value pairs
+ * with source location info. We also abuse this data structure to carry
+ * error reports about the config files. An entry reporting an error will
+ * have errmsg != NULL, and might have NULLs for name, value, and/or filename.
+ *
+ * If "ignore" is true, don't attempt to apply the item (it might be an error
+ * report, or an item we determined to be duplicate). "applied" is set true
+ * if we successfully applied, or could have applied, the setting.
+ */
+typedef struct ConfigVariable
+{
+ char *name;
+ char *value;
+ char *errmsg;
+ char *filename;
+ int sourceline;
+ bool ignore;
+ bool applied;
+ struct ConfigVariable *next;
+} ConfigVariable;
+
+extern bool ParseConfigFile(const char *config_file, bool strict,
+ const char *calling_file, int calling_lineno,
+ int depth, int elevel,
+ ConfigVariable **head_p, ConfigVariable **tail_p);
+extern bool ParseConfigFp(FILE *fp, const char *config_file,
+ int depth, int elevel,
+ ConfigVariable **head_p, ConfigVariable **tail_p);
+extern bool ParseConfigDirectory(const char *includedir,
+ const char *calling_file, int calling_lineno,
+ int depth, int elevel,
+ ConfigVariable **head_p,
+ ConfigVariable **tail_p);
+extern void FreeConfigVariables(ConfigVariable *list);
+extern char *DeescapeQuotedString(const char *s);
+
+/*
+ * The possible values of an enum variable are specified by an array of
+ * name-value pairs. The "hidden" flag means the value is accepted but
+ * won't be displayed when guc.c is asked for a list of acceptable values.
+ */
+struct config_enum_entry
+{
+ const char *name;
+ int val;
+ bool hidden;
+};
+
+/*
+ * Signatures for per-variable check/assign/show hook functions
+ */
+typedef bool (*GucBoolCheckHook) (bool *newval, void **extra, GucSource source);
+typedef bool (*GucIntCheckHook) (int *newval, void **extra, GucSource source);
+typedef bool (*GucRealCheckHook) (double *newval, void **extra, GucSource source);
+typedef bool (*GucStringCheckHook) (char **newval, void **extra, GucSource source);
+typedef bool (*GucEnumCheckHook) (int *newval, void **extra, GucSource source);
+
+typedef void (*GucBoolAssignHook) (bool newval, void *extra);
+typedef void (*GucIntAssignHook) (int newval, void *extra);
+typedef void (*GucRealAssignHook) (double newval, void *extra);
+typedef void (*GucStringAssignHook) (const char *newval, void *extra);
+typedef void (*GucEnumAssignHook) (int newval, void *extra);
+
+typedef const char *(*GucShowHook) (void);
+
+/*
+ * Miscellaneous
+ */
+typedef enum
+{
+ /* Types of set_config_option actions */
+ GUC_ACTION_SET, /* regular SET command */
+ GUC_ACTION_LOCAL, /* SET LOCAL command */
+ GUC_ACTION_SAVE /* function SET option, or temp assignment */
+} GucAction;
+
+#define GUC_QUALIFIER_SEPARATOR '.'
+
+/*
+ * Bit values in "flags" of a GUC variable. Note that these don't appear
+ * on disk, so we can reassign their values freely.
+ */
+#define GUC_LIST_INPUT 0x000001 /* input can be list format */
+#define GUC_LIST_QUOTE 0x000002 /* double-quote list elements */
+#define GUC_NO_SHOW_ALL 0x000004 /* exclude from SHOW ALL */
+#define GUC_NO_RESET 0x000008 /* disallow RESET and SAVE */
+#define GUC_NO_RESET_ALL 0x000010 /* exclude from RESET ALL */
+#define GUC_EXPLAIN 0x000020 /* include in EXPLAIN */
+#define GUC_REPORT 0x000040 /* auto-report changes to client */
+#define GUC_NOT_IN_SAMPLE 0x000080 /* not in postgresql.conf.sample */
+#define GUC_DISALLOW_IN_FILE 0x000100 /* can't set in postgresql.conf */
+#define GUC_CUSTOM_PLACEHOLDER 0x000200 /* placeholder for custom variable */
+#define GUC_SUPERUSER_ONLY 0x000400 /* show only to superusers */
+#define GUC_IS_NAME 0x000800 /* limit string to NAMEDATALEN-1 */
+#define GUC_NOT_WHILE_SEC_REST 0x001000 /* can't set if security restricted */
+#define GUC_DISALLOW_IN_AUTO_FILE \
+ 0x002000 /* can't set in PG_AUTOCONF_FILENAME */
+#define GUC_RUNTIME_COMPUTED 0x004000 /* delay processing in 'postgres -C' */
+
+#define GUC_UNIT_KB 0x01000000 /* value is in kilobytes */
+#define GUC_UNIT_BLOCKS 0x02000000 /* value is in blocks */
+#define GUC_UNIT_XBLOCKS 0x03000000 /* value is in xlog blocks */
+#define GUC_UNIT_MB 0x04000000 /* value is in megabytes */
+#define GUC_UNIT_BYTE 0x05000000 /* value is in bytes */
+#define GUC_UNIT_MEMORY 0x0F000000 /* mask for size-related units */
+
+#define GUC_UNIT_MS 0x10000000 /* value is in milliseconds */
+#define GUC_UNIT_S 0x20000000 /* value is in seconds */
+#define GUC_UNIT_MIN 0x30000000 /* value is in minutes */
+#define GUC_UNIT_TIME 0x70000000 /* mask for time-related units */
+
+#define GUC_UNIT (GUC_UNIT_MEMORY | GUC_UNIT_TIME)
+
+
+/* GUC vars that are actually defined in guc_tables.c, rather than elsewhere */
+extern PGDLLIMPORT bool Debug_print_plan;
+extern PGDLLIMPORT bool Debug_print_parse;
+extern PGDLLIMPORT bool Debug_print_rewritten;
+extern PGDLLIMPORT bool Debug_pretty_print;
+
+extern PGDLLIMPORT bool log_parser_stats;
+extern PGDLLIMPORT bool log_planner_stats;
+extern PGDLLIMPORT bool log_executor_stats;
+extern PGDLLIMPORT bool log_statement_stats;
+extern PGDLLIMPORT bool log_btree_build_stats;
+
+extern PGDLLIMPORT bool check_function_bodies;
+extern PGDLLIMPORT bool session_auth_is_superuser;
+
+extern PGDLLIMPORT bool log_duration;
+extern PGDLLIMPORT int log_parameter_max_length;
+extern PGDLLIMPORT int log_parameter_max_length_on_error;
+extern PGDLLIMPORT int log_min_error_statement;
+extern PGDLLIMPORT int log_min_messages;
+extern PGDLLIMPORT int client_min_messages;
+extern PGDLLIMPORT int log_min_duration_sample;
+extern PGDLLIMPORT int log_min_duration_statement;
+extern PGDLLIMPORT int log_temp_files;
+extern PGDLLIMPORT double log_statement_sample_rate;
+extern PGDLLIMPORT double log_xact_sample_rate;
+extern PGDLLIMPORT char *backtrace_functions;
+
+extern PGDLLIMPORT int temp_file_limit;
+
+extern PGDLLIMPORT int num_temp_buffers;
+
+extern PGDLLIMPORT char *cluster_name;
+extern PGDLLIMPORT char *ConfigFileName;
+extern PGDLLIMPORT char *HbaFileName;
+extern PGDLLIMPORT char *IdentFileName;
+extern PGDLLIMPORT char *external_pid_file;
+
+extern PGDLLIMPORT char *application_name;
+
+extern PGDLLIMPORT int tcp_keepalives_idle;
+extern PGDLLIMPORT int tcp_keepalives_interval;
+extern PGDLLIMPORT int tcp_keepalives_count;
+extern PGDLLIMPORT int tcp_user_timeout;
+
+#ifdef TRACE_SORT
+extern PGDLLIMPORT bool trace_sort;
+#endif
+
+/*
+ * Functions exported by guc.c
+ */
+extern void SetConfigOption(const char *name, const char *value,
+ GucContext context, GucSource source);
+
+extern void DefineCustomBoolVariable(const char *name,
+ const char *short_desc,
+ const char *long_desc,
+ bool *valueAddr,
+ bool bootValue,
+ GucContext context,
+ int flags,
+ GucBoolCheckHook check_hook,
+ GucBoolAssignHook assign_hook,
+ GucShowHook show_hook) pg_attribute_nonnull(1, 4);
+
+extern void DefineCustomIntVariable(const char *name,
+ const char *short_desc,
+ const char *long_desc,
+ int *valueAddr,
+ int bootValue,
+ int minValue,
+ int maxValue,
+ GucContext context,
+ int flags,
+ GucIntCheckHook check_hook,
+ GucIntAssignHook assign_hook,
+ GucShowHook show_hook) pg_attribute_nonnull(1, 4);
+
+extern void DefineCustomRealVariable(const char *name,
+ const char *short_desc,
+ const char *long_desc,
+ double *valueAddr,
+ double bootValue,
+ double minValue,
+ double maxValue,
+ GucContext context,
+ int flags,
+ GucRealCheckHook check_hook,
+ GucRealAssignHook assign_hook,
+ GucShowHook show_hook) pg_attribute_nonnull(1, 4);
+
+extern void DefineCustomStringVariable(const char *name,
+ const char *short_desc,
+ const char *long_desc,
+ char **valueAddr,
+ const char *bootValue,
+ GucContext context,
+ int flags,
+ GucStringCheckHook check_hook,
+ GucStringAssignHook assign_hook,
+ GucShowHook show_hook) pg_attribute_nonnull(1, 4);
+
+extern void DefineCustomEnumVariable(const char *name,
+ const char *short_desc,
+ const char *long_desc,
+ int *valueAddr,
+ int bootValue,
+ const struct config_enum_entry *options,
+ GucContext context,
+ int flags,
+ GucEnumCheckHook check_hook,
+ GucEnumAssignHook assign_hook,
+ GucShowHook show_hook) pg_attribute_nonnull(1, 4);
+
+extern void MarkGUCPrefixReserved(const char *className);
+
+/* old name for MarkGUCPrefixReserved, for backwards compatibility: */
+#define EmitWarningsOnPlaceholders(className) MarkGUCPrefixReserved(className)
+
+extern const char *GetConfigOption(const char *name, bool missing_ok,
+ bool restrict_privileged);
+extern const char *GetConfigOptionResetString(const char *name);
+extern int GetConfigOptionFlags(const char *name, bool missing_ok);
+extern void ProcessConfigFile(GucContext context);
+extern char *convert_GUC_name_for_parameter_acl(const char *name);
+extern bool check_GUC_name_for_parameter_acl(const char *name);
+extern void InitializeGUCOptions(void);
+extern bool SelectConfigFiles(const char *userDoption, const char *progname);
+extern void ResetAllOptions(void);
+extern void AtStart_GUC(void);
+extern int NewGUCNestLevel(void);
+extern void AtEOXact_GUC(bool isCommit, int nestLevel);
+extern void BeginReportingGUCOptions(void);
+extern void ReportChangedGUCOptions(void);
+extern void ParseLongOption(const char *string, char **name, char **value);
+extern const char *get_config_unit_name(int flags);
+extern bool parse_int(const char *value, int *result, int flags,
+ const char **hintmsg);
+extern bool parse_real(const char *value, double *result, int flags,
+ const char **hintmsg);
+extern int set_config_option(const char *name, const char *value,
+ GucContext context, GucSource source,
+ GucAction action, bool changeVal, int elevel,
+ bool is_reload);
+extern int set_config_option_ext(const char *name, const char *value,
+ GucContext context, GucSource source,
+ Oid srole,
+ GucAction action, bool changeVal, int elevel,
+ bool is_reload);
+extern void AlterSystemSetConfigFile(AlterSystemStmt *altersysstmt);
+extern char *GetConfigOptionByName(const char *name, const char **varname,
+ bool missing_ok);
+
+extern void ProcessGUCArray(ArrayType *array,
+ GucContext context, GucSource source, GucAction action);
+extern ArrayType *GUCArrayAdd(ArrayType *array, const char *name, const char *value);
+extern ArrayType *GUCArrayDelete(ArrayType *array, const char *name);
+extern ArrayType *GUCArrayReset(ArrayType *array);
+
+extern void *guc_malloc(int elevel, size_t size);
+extern pg_nodiscard void *guc_realloc(int elevel, void *old, size_t size);
+extern char *guc_strdup(int elevel, const char *src);
+extern void guc_free(void *ptr);
+
+#ifdef EXEC_BACKEND
+extern void write_nondefault_variables(GucContext context);
+extern void read_nondefault_variables(void);
+#endif
+
+/* GUC serialization */
+extern Size EstimateGUCStateSpace(void);
+extern void SerializeGUCState(Size maxsize, char *start_address);
+extern void RestoreGUCState(void *gucstate);
+
+/* Functions exported by guc_funcs.c */
+extern void ExecSetVariableStmt(VariableSetStmt *stmt, bool isTopLevel);
+extern char *ExtractSetVariableArgs(VariableSetStmt *stmt);
+extern void SetPGVariable(const char *name, List *args, bool is_local);
+extern void GetPGVariable(const char *name, DestReceiver *dest);
+extern TupleDesc GetPGVariableResultDesc(const char *name);
+
+/* Support for messages reported from GUC check hooks */
+
+extern PGDLLIMPORT char *GUC_check_errmsg_string;
+extern PGDLLIMPORT char *GUC_check_errdetail_string;
+extern PGDLLIMPORT char *GUC_check_errhint_string;
+
+extern void GUC_check_errcode(int sqlerrcode);
+
+#define GUC_check_errmsg \
+ pre_format_elog_string(errno, TEXTDOMAIN), \
+ GUC_check_errmsg_string = format_elog_string
+
+#define GUC_check_errdetail \
+ pre_format_elog_string(errno, TEXTDOMAIN), \
+ GUC_check_errdetail_string = format_elog_string
+
+#define GUC_check_errhint \
+ pre_format_elog_string(errno, TEXTDOMAIN), \
+ GUC_check_errhint_string = format_elog_string
+
+#endif /* GUC_H */
diff --git a/pgsql/include/server/utils/guc_hooks.h b/pgsql/include/server/utils/guc_hooks.h
new file mode 100644
index 0000000000000000000000000000000000000000..952293a1c3059932a0ffdf03fec15e1fbf3de078
--- /dev/null
+++ b/pgsql/include/server/utils/guc_hooks.h
@@ -0,0 +1,163 @@
+/*-------------------------------------------------------------------------
+ *
+ * guc_hooks.h
+ * Declarations of per-variable callback functions used by GUC.
+ *
+ * These functions are scattered throughout the system, but we
+ * declare them all here to avoid having to propagate guc.h into
+ * a lot of unrelated header files.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/guc_hooks.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef GUC_HOOKS_H
+#define GUC_HOOKS_H 1
+
+#include "utils/guc.h"
+
+/*
+ * See guc.h for the typedefs that these hook functions should match
+ * (GucBoolCheckHook and so on).
+ *
+ * Please keep the declarations in order by GUC variable name.
+ */
+
+extern bool check_application_name(char **newval, void **extra,
+ GucSource source);
+extern void assign_application_name(const char *newval, void *extra);
+extern const char *show_archive_command(void);
+extern bool check_autovacuum_max_workers(int *newval, void **extra,
+ GucSource source);
+extern bool check_autovacuum_work_mem(int *newval, void **extra,
+ GucSource source);
+extern bool check_vacuum_buffer_usage_limit(int *newval, void **extra,
+ GucSource source);
+extern bool check_backtrace_functions(char **newval, void **extra,
+ GucSource source);
+extern void assign_backtrace_functions(const char *newval, void *extra);
+extern bool check_bonjour(bool *newval, void **extra, GucSource source);
+extern bool check_canonical_path(char **newval, void **extra, GucSource source);
+extern void assign_checkpoint_completion_target(double newval, void *extra);
+extern bool check_client_connection_check_interval(int *newval, void **extra,
+ GucSource source);
+extern bool check_client_encoding(char **newval, void **extra, GucSource source);
+extern void assign_client_encoding(const char *newval, void *extra);
+extern bool check_cluster_name(char **newval, void **extra, GucSource source);
+extern const char *show_data_directory_mode(void);
+extern bool check_datestyle(char **newval, void **extra, GucSource source);
+extern void assign_datestyle(const char *newval, void *extra);
+extern bool check_debug_io_direct(char **newval, void **extra, GucSource source);
+extern void assign_debug_io_direct(const char *newval, void *extra);
+extern bool check_default_table_access_method(char **newval, void **extra,
+ GucSource source);
+extern bool check_default_tablespace(char **newval, void **extra,
+ GucSource source);
+extern bool check_default_text_search_config(char **newval, void **extra, GucSource source);
+extern void assign_default_text_search_config(const char *newval, void *extra);
+extern bool check_default_with_oids(bool *newval, void **extra,
+ GucSource source);
+extern bool check_effective_io_concurrency(int *newval, void **extra,
+ GucSource source);
+extern bool check_huge_page_size(int *newval, void **extra, GucSource source);
+extern const char *show_in_hot_standby(void);
+extern bool check_locale_messages(char **newval, void **extra, GucSource source);
+extern void assign_locale_messages(const char *newval, void *extra);
+extern bool check_locale_monetary(char **newval, void **extra, GucSource source);
+extern void assign_locale_monetary(const char *newval, void *extra);
+extern bool check_locale_numeric(char **newval, void **extra, GucSource source);
+extern void assign_locale_numeric(const char *newval, void *extra);
+extern bool check_locale_time(char **newval, void **extra, GucSource source);
+extern void assign_locale_time(const char *newval, void *extra);
+extern bool check_log_destination(char **newval, void **extra,
+ GucSource source);
+extern void assign_log_destination(const char *newval, void *extra);
+extern const char *show_log_file_mode(void);
+extern bool check_log_stats(bool *newval, void **extra, GucSource source);
+extern bool check_log_timezone(char **newval, void **extra, GucSource source);
+extern void assign_log_timezone(const char *newval, void *extra);
+extern const char *show_log_timezone(void);
+extern bool check_maintenance_io_concurrency(int *newval, void **extra,
+ GucSource source);
+extern void assign_maintenance_io_concurrency(int newval, void *extra);
+extern bool check_max_connections(int *newval, void **extra, GucSource source);
+extern bool check_max_wal_senders(int *newval, void **extra, GucSource source);
+extern void assign_max_wal_size(int newval, void *extra);
+extern bool check_max_worker_processes(int *newval, void **extra,
+ GucSource source);
+extern bool check_max_stack_depth(int *newval, void **extra, GucSource source);
+extern void assign_max_stack_depth(int newval, void *extra);
+extern bool check_primary_slot_name(char **newval, void **extra,
+ GucSource source);
+extern bool check_random_seed(double *newval, void **extra, GucSource source);
+extern void assign_random_seed(double newval, void *extra);
+extern const char *show_random_seed(void);
+extern bool check_recovery_prefetch(int *new_value, void **extra,
+ GucSource source);
+extern void assign_recovery_prefetch(int new_value, void *extra);
+extern bool check_recovery_target(char **newval, void **extra,
+ GucSource source);
+extern void assign_recovery_target(const char *newval, void *extra);
+extern bool check_recovery_target_lsn(char **newval, void **extra,
+ GucSource source);
+extern void assign_recovery_target_lsn(const char *newval, void *extra);
+extern bool check_recovery_target_name(char **newval, void **extra,
+ GucSource source);
+extern void assign_recovery_target_name(const char *newval, void *extra);
+extern bool check_recovery_target_time(char **newval, void **extra,
+ GucSource source);
+extern void assign_recovery_target_time(const char *newval, void *extra);
+extern bool check_recovery_target_timeline(char **newval, void **extra,
+ GucSource source);
+extern void assign_recovery_target_timeline(const char *newval, void *extra);
+extern bool check_recovery_target_xid(char **newval, void **extra,
+ GucSource source);
+extern void assign_recovery_target_xid(const char *newval, void *extra);
+extern bool check_role(char **newval, void **extra, GucSource source);
+extern void assign_role(const char *newval, void *extra);
+extern const char *show_role(void);
+extern bool check_search_path(char **newval, void **extra, GucSource source);
+extern void assign_search_path(const char *newval, void *extra);
+extern bool check_session_authorization(char **newval, void **extra, GucSource source);
+extern void assign_session_authorization(const char *newval, void *extra);
+extern void assign_session_replication_role(int newval, void *extra);
+extern void assign_stats_fetch_consistency(int newval, void *extra);
+extern bool check_ssl(bool *newval, void **extra, GucSource source);
+extern bool check_stage_log_stats(bool *newval, void **extra, GucSource source);
+extern bool check_synchronous_standby_names(char **newval, void **extra,
+ GucSource source);
+extern void assign_synchronous_standby_names(const char *newval, void *extra);
+extern void assign_synchronous_commit(int newval, void *extra);
+extern void assign_syslog_facility(int newval, void *extra);
+extern void assign_syslog_ident(const char *newval, void *extra);
+extern void assign_tcp_keepalives_count(int newval, void *extra);
+extern const char *show_tcp_keepalives_count(void);
+extern void assign_tcp_keepalives_idle(int newval, void *extra);
+extern const char *show_tcp_keepalives_idle(void);
+extern void assign_tcp_keepalives_interval(int newval, void *extra);
+extern const char *show_tcp_keepalives_interval(void);
+extern void assign_tcp_user_timeout(int newval, void *extra);
+extern const char *show_tcp_user_timeout(void);
+extern bool check_temp_buffers(int *newval, void **extra, GucSource source);
+extern bool check_temp_tablespaces(char **newval, void **extra,
+ GucSource source);
+extern void assign_temp_tablespaces(const char *newval, void *extra);
+extern bool check_timezone(char **newval, void **extra, GucSource source);
+extern void assign_timezone(const char *newval, void *extra);
+extern const char *show_timezone(void);
+extern bool check_timezone_abbreviations(char **newval, void **extra,
+ GucSource source);
+extern void assign_timezone_abbreviations(const char *newval, void *extra);
+extern bool check_transaction_deferrable(bool *newval, void **extra, GucSource source);
+extern bool check_transaction_isolation(int *newval, void **extra, GucSource source);
+extern bool check_transaction_read_only(bool *newval, void **extra, GucSource source);
+extern const char *show_unix_socket_permissions(void);
+extern bool check_wal_buffers(int *newval, void **extra, GucSource source);
+extern bool check_wal_consistency_checking(char **newval, void **extra,
+ GucSource source);
+extern void assign_wal_consistency_checking(const char *newval, void *extra);
+extern void assign_xlog_sync_method(int new_sync_method, void *extra);
+
+#endif /* GUC_HOOKS_H */
diff --git a/pgsql/include/server/utils/guc_tables.h b/pgsql/include/server/utils/guc_tables.h
new file mode 100644
index 0000000000000000000000000000000000000000..ab880cae2c410955f66551190618643066ffaad6
--- /dev/null
+++ b/pgsql/include/server/utils/guc_tables.h
@@ -0,0 +1,322 @@
+/*-------------------------------------------------------------------------
+ *
+ * guc_tables.h
+ * Declarations of tables used by GUC.
+ *
+ * See src/backend/utils/misc/README for design notes.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/guc_tables.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef GUC_TABLES_H
+#define GUC_TABLES_H 1
+
+#include "lib/ilist.h"
+#include "utils/guc.h"
+
+/*
+ * GUC supports these types of variables:
+ */
+enum config_type
+{
+ PGC_BOOL,
+ PGC_INT,
+ PGC_REAL,
+ PGC_STRING,
+ PGC_ENUM
+};
+
+union config_var_val
+{
+ bool boolval;
+ int intval;
+ double realval;
+ char *stringval;
+ int enumval;
+};
+
+/*
+ * The actual value of a GUC variable can include a malloc'd opaque struct
+ * "extra", which is created by its check_hook and used by its assign_hook.
+ */
+typedef struct config_var_value
+{
+ union config_var_val val;
+ void *extra;
+} config_var_value;
+
+/*
+ * Groupings to help organize all the run-time options for display.
+ * Be sure this agrees with the way the options are categorized in config.sgml!
+ */
+enum config_group
+{
+ UNGROUPED, /* use for options not shown in pg_settings */
+ FILE_LOCATIONS,
+ CONN_AUTH_SETTINGS,
+ CONN_AUTH_TCP,
+ CONN_AUTH_AUTH,
+ CONN_AUTH_SSL,
+ RESOURCES_MEM,
+ RESOURCES_DISK,
+ RESOURCES_KERNEL,
+ RESOURCES_VACUUM_DELAY,
+ RESOURCES_BGWRITER,
+ RESOURCES_ASYNCHRONOUS,
+ WAL_SETTINGS,
+ WAL_CHECKPOINTS,
+ WAL_ARCHIVING,
+ WAL_RECOVERY,
+ WAL_ARCHIVE_RECOVERY,
+ WAL_RECOVERY_TARGET,
+ REPLICATION_SENDING,
+ REPLICATION_PRIMARY,
+ REPLICATION_STANDBY,
+ REPLICATION_SUBSCRIBERS,
+ QUERY_TUNING_METHOD,
+ QUERY_TUNING_COST,
+ QUERY_TUNING_GEQO,
+ QUERY_TUNING_OTHER,
+ LOGGING_WHERE,
+ LOGGING_WHEN,
+ LOGGING_WHAT,
+ PROCESS_TITLE,
+ STATS_MONITORING,
+ STATS_CUMULATIVE,
+ AUTOVACUUM,
+ CLIENT_CONN_STATEMENT,
+ CLIENT_CONN_LOCALE,
+ CLIENT_CONN_PRELOAD,
+ CLIENT_CONN_OTHER,
+ LOCK_MANAGEMENT,
+ COMPAT_OPTIONS_PREVIOUS,
+ COMPAT_OPTIONS_CLIENT,
+ ERROR_HANDLING_OPTIONS,
+ PRESET_OPTIONS,
+ CUSTOM_OPTIONS,
+ DEVELOPER_OPTIONS
+};
+
+/*
+ * Stack entry for saving the state a variable had prior to an uncommitted
+ * transactional change
+ */
+typedef enum
+{
+ /* This is almost GucAction, but we need a fourth state for SET+LOCAL */
+ GUC_SAVE, /* entry caused by function SET option */
+ GUC_SET, /* entry caused by plain SET command */
+ GUC_LOCAL, /* entry caused by SET LOCAL command */
+ GUC_SET_LOCAL /* entry caused by SET then SET LOCAL */
+} GucStackState;
+
+typedef struct guc_stack
+{
+ struct guc_stack *prev; /* previous stack item, if any */
+ int nest_level; /* nesting depth at which we made entry */
+ GucStackState state; /* see enum above */
+ GucSource source; /* source of the prior value */
+ /* masked value's source must be PGC_S_SESSION, so no need to store it */
+ GucContext scontext; /* context that set the prior value */
+ GucContext masked_scontext; /* context that set the masked value */
+ Oid srole; /* role that set the prior value */
+ Oid masked_srole; /* role that set the masked value */
+ config_var_value prior; /* previous value of variable */
+ config_var_value masked; /* SET value in a GUC_SET_LOCAL entry */
+} GucStack;
+
+/*
+ * Generic fields applicable to all types of variables
+ *
+ * The short description should be less than 80 chars in length. Some
+ * applications may use the long description as well, and will append
+ * it to the short description. (separated by a newline or '. ')
+ *
+ * srole is the role that set the current value, or BOOTSTRAP_SUPERUSERID
+ * if the value came from an internal source or the config file. Similarly
+ * for reset_srole (which is usually BOOTSTRAP_SUPERUSERID, but not always).
+ *
+ * Variables that are currently of active interest for maintenance
+ * operations are linked into various lists using the xxx_link fields.
+ * The link fields are unused/garbage in variables not currently having
+ * the specified properties.
+ *
+ * Note that sourcefile/sourceline are kept here, and not pushed into stacked
+ * values, although in principle they belong with some stacked value if the
+ * active value is session- or transaction-local. This is to avoid bloating
+ * stack entries. We know they are only relevant when source == PGC_S_FILE.
+ */
+struct config_generic
+{
+ /* constant fields, must be set correctly in initial value: */
+ const char *name; /* name of variable - MUST BE FIRST */
+ GucContext context; /* context required to set the variable */
+ enum config_group group; /* to help organize variables by function */
+ const char *short_desc; /* short desc. of this variable's purpose */
+ const char *long_desc; /* long desc. of this variable's purpose */
+ int flags; /* flag bits, see guc.h */
+ /* variable fields, initialized at runtime: */
+ enum config_type vartype; /* type of variable (set only at startup) */
+ int status; /* status bits, see below */
+ GucSource source; /* source of the current actual value */
+ GucSource reset_source; /* source of the reset_value */
+ GucContext scontext; /* context that set the current value */
+ GucContext reset_scontext; /* context that set the reset value */
+ Oid srole; /* role that set the current value */
+ Oid reset_srole; /* role that set the reset value */
+ GucStack *stack; /* stacked prior values */
+ void *extra; /* "extra" pointer for current actual value */
+ dlist_node nondef_link; /* list link for variables that have source
+ * different from PGC_S_DEFAULT */
+ slist_node stack_link; /* list link for variables that have non-NULL
+ * stack */
+ slist_node report_link; /* list link for variables that have the
+ * GUC_NEEDS_REPORT bit set in status */
+ char *last_reported; /* if variable is GUC_REPORT, value last sent
+ * to client (NULL if not yet sent) */
+ char *sourcefile; /* file current setting is from (NULL if not
+ * set in config file) */
+ int sourceline; /* line in source file */
+};
+
+/* bit values in status field */
+#define GUC_IS_IN_FILE 0x0001 /* found it in config file */
+/*
+ * Caution: the GUC_IS_IN_FILE bit is transient state for ProcessConfigFile.
+ * Do not assume that its value represents useful information elsewhere.
+ */
+#define GUC_PENDING_RESTART 0x0002 /* changed value cannot be applied yet */
+#define GUC_NEEDS_REPORT 0x0004 /* new value must be reported to client */
+
+
+/* GUC records for specific variable types */
+
+struct config_bool
+{
+ struct config_generic gen;
+ /* constant fields, must be set correctly in initial value: */
+ bool *variable;
+ bool boot_val;
+ GucBoolCheckHook check_hook;
+ GucBoolAssignHook assign_hook;
+ GucShowHook show_hook;
+ /* variable fields, initialized at runtime: */
+ bool reset_val;
+ void *reset_extra;
+};
+
+struct config_int
+{
+ struct config_generic gen;
+ /* constant fields, must be set correctly in initial value: */
+ int *variable;
+ int boot_val;
+ int min;
+ int max;
+ GucIntCheckHook check_hook;
+ GucIntAssignHook assign_hook;
+ GucShowHook show_hook;
+ /* variable fields, initialized at runtime: */
+ int reset_val;
+ void *reset_extra;
+};
+
+struct config_real
+{
+ struct config_generic gen;
+ /* constant fields, must be set correctly in initial value: */
+ double *variable;
+ double boot_val;
+ double min;
+ double max;
+ GucRealCheckHook check_hook;
+ GucRealAssignHook assign_hook;
+ GucShowHook show_hook;
+ /* variable fields, initialized at runtime: */
+ double reset_val;
+ void *reset_extra;
+};
+
+/*
+ * A note about string GUCs: the boot_val is allowed to be NULL, which leads
+ * to the reset_val and the actual variable value (*variable) also being NULL.
+ * However, there is no way to set a NULL value subsequently using
+ * set_config_option or any other GUC API. Also, GUC APIs such as SHOW will
+ * display a NULL value as an empty string. Callers that choose to use a NULL
+ * boot_val should overwrite the setting later in startup, or else be careful
+ * that NULL doesn't have semantics that are visibly different from an empty
+ * string.
+ */
+struct config_string
+{
+ struct config_generic gen;
+ /* constant fields, must be set correctly in initial value: */
+ char **variable;
+ const char *boot_val;
+ GucStringCheckHook check_hook;
+ GucStringAssignHook assign_hook;
+ GucShowHook show_hook;
+ /* variable fields, initialized at runtime: */
+ char *reset_val;
+ void *reset_extra;
+};
+
+struct config_enum
+{
+ struct config_generic gen;
+ /* constant fields, must be set correctly in initial value: */
+ int *variable;
+ int boot_val;
+ const struct config_enum_entry *options;
+ GucEnumCheckHook check_hook;
+ GucEnumAssignHook assign_hook;
+ GucShowHook show_hook;
+ /* variable fields, initialized at runtime: */
+ int reset_val;
+ void *reset_extra;
+};
+
+/* constant tables corresponding to enums above and in guc.h */
+extern PGDLLIMPORT const char *const config_group_names[];
+extern PGDLLIMPORT const char *const config_type_names[];
+extern PGDLLIMPORT const char *const GucContext_Names[];
+extern PGDLLIMPORT const char *const GucSource_Names[];
+
+/* data arrays defining all the built-in GUC variables */
+extern PGDLLIMPORT struct config_bool ConfigureNamesBool[];
+extern PGDLLIMPORT struct config_int ConfigureNamesInt[];
+extern PGDLLIMPORT struct config_real ConfigureNamesReal[];
+extern PGDLLIMPORT struct config_string ConfigureNamesString[];
+extern PGDLLIMPORT struct config_enum ConfigureNamesEnum[];
+
+/* lookup GUC variables, returning config_generic pointers */
+extern struct config_generic *find_option(const char *name,
+ bool create_placeholders,
+ bool skip_errors,
+ int elevel);
+extern struct config_generic **get_explain_guc_options(int *num);
+
+/* get string value of variable */
+extern char *ShowGUCOption(struct config_generic *record, bool use_units);
+
+/* get whether or not the GUC variable is visible to current user */
+extern bool ConfigOptionIsVisible(struct config_generic *conf);
+
+/* get the current set of variables */
+extern struct config_generic **get_guc_variables(int *num_vars);
+
+extern void build_guc_variables(void);
+
+/* search in enum options */
+extern const char *config_enum_lookup_by_value(struct config_enum *record, int val);
+extern bool config_enum_lookup_by_name(struct config_enum *record,
+ const char *value, int *retval);
+extern char *config_enum_get_options(struct config_enum *record,
+ const char *prefix,
+ const char *suffix,
+ const char *separator);
+
+#endif /* GUC_TABLES_H */
diff --git a/pgsql/include/server/utils/help_config.h b/pgsql/include/server/utils/help_config.h
new file mode 100644
index 0000000000000000000000000000000000000000..e9bc417ca45fbfc858ef6a75627eb61b2d1235d0
--- /dev/null
+++ b/pgsql/include/server/utils/help_config.h
@@ -0,0 +1,17 @@
+/*-------------------------------------------------------------------------
+ *
+ * help_config.h
+ * Interface to the --help-config option of main.c
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/help_config.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef HELP_CONFIG_H
+#define HELP_CONFIG_H 1
+
+extern void GucInfoMain(void) pg_attribute_noreturn();
+
+#endif
diff --git a/pgsql/include/server/utils/hsearch.h b/pgsql/include/server/utils/hsearch.h
new file mode 100644
index 0000000000000000000000000000000000000000..bc3d5efa9637b14744e9d257f5e06be5d1a0547b
--- /dev/null
+++ b/pgsql/include/server/utils/hsearch.h
@@ -0,0 +1,153 @@
+/*-------------------------------------------------------------------------
+ *
+ * hsearch.h
+ * exported definitions for utils/hash/dynahash.c; see notes therein
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/hsearch.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef HSEARCH_H
+#define HSEARCH_H
+
+
+/*
+ * Hash functions must have this signature.
+ */
+typedef uint32 (*HashValueFunc) (const void *key, Size keysize);
+
+/*
+ * Key comparison functions must have this signature. Comparison functions
+ * return zero for match, nonzero for no match. (The comparison function
+ * definition is designed to allow memcmp() and strncmp() to be used directly
+ * as key comparison functions.)
+ */
+typedef int (*HashCompareFunc) (const void *key1, const void *key2,
+ Size keysize);
+
+/*
+ * Key copying functions must have this signature. The return value is not
+ * used. (The definition is set up to allow memcpy() and strlcpy() to be
+ * used directly.)
+ */
+typedef void *(*HashCopyFunc) (void *dest, const void *src, Size keysize);
+
+/*
+ * Space allocation function for a hashtable --- designed to match malloc().
+ * Note: there is no free function API; can't destroy a hashtable unless you
+ * use the default allocator.
+ */
+typedef void *(*HashAllocFunc) (Size request);
+
+/*
+ * HASHELEMENT is the private part of a hashtable entry. The caller's data
+ * follows the HASHELEMENT structure (on a MAXALIGN'd boundary). The hash key
+ * is expected to be at the start of the caller's hash entry data structure.
+ */
+typedef struct HASHELEMENT
+{
+ struct HASHELEMENT *link; /* link to next entry in same bucket */
+ uint32 hashvalue; /* hash function result for this entry */
+} HASHELEMENT;
+
+/* Hash table header struct is an opaque type known only within dynahash.c */
+typedef struct HASHHDR HASHHDR;
+
+/* Hash table control struct is an opaque type known only within dynahash.c */
+typedef struct HTAB HTAB;
+
+/* Parameter data structure for hash_create */
+/* Only those fields indicated by hash_flags need be set */
+typedef struct HASHCTL
+{
+ /* Used if HASH_PARTITION flag is set: */
+ long num_partitions; /* # partitions (must be power of 2) */
+ /* Used if HASH_SEGMENT flag is set: */
+ long ssize; /* segment size */
+ /* Used if HASH_DIRSIZE flag is set: */
+ long dsize; /* (initial) directory size */
+ long max_dsize; /* limit to dsize if dir size is limited */
+ /* Used if HASH_ELEM flag is set (which is now required): */
+ Size keysize; /* hash key length in bytes */
+ Size entrysize; /* total user element size in bytes */
+ /* Used if HASH_FUNCTION flag is set: */
+ HashValueFunc hash; /* hash function */
+ /* Used if HASH_COMPARE flag is set: */
+ HashCompareFunc match; /* key comparison function */
+ /* Used if HASH_KEYCOPY flag is set: */
+ HashCopyFunc keycopy; /* key copying function */
+ /* Used if HASH_ALLOC flag is set: */
+ HashAllocFunc alloc; /* memory allocator */
+ /* Used if HASH_CONTEXT flag is set: */
+ MemoryContext hcxt; /* memory context to use for allocations */
+ /* Used if HASH_SHARED_MEM flag is set: */
+ HASHHDR *hctl; /* location of header in shared mem */
+} HASHCTL;
+
+/* Flag bits for hash_create; most indicate which parameters are supplied */
+#define HASH_PARTITION 0x0001 /* Hashtable is used w/partitioned locking */
+#define HASH_SEGMENT 0x0002 /* Set segment size */
+#define HASH_DIRSIZE 0x0004 /* Set directory size (initial and max) */
+#define HASH_ELEM 0x0008 /* Set keysize and entrysize (now required!) */
+#define HASH_STRINGS 0x0010 /* Select support functions for string keys */
+#define HASH_BLOBS 0x0020 /* Select support functions for binary keys */
+#define HASH_FUNCTION 0x0040 /* Set user defined hash function */
+#define HASH_COMPARE 0x0080 /* Set user defined comparison function */
+#define HASH_KEYCOPY 0x0100 /* Set user defined key-copying function */
+#define HASH_ALLOC 0x0200 /* Set memory allocator */
+#define HASH_CONTEXT 0x0400 /* Set memory allocation context */
+#define HASH_SHARED_MEM 0x0800 /* Hashtable is in shared memory */
+#define HASH_ATTACH 0x1000 /* Do not initialize hctl */
+#define HASH_FIXED_SIZE 0x2000 /* Initial size is a hard limit */
+
+/* max_dsize value to indicate expansible directory */
+#define NO_MAX_DSIZE (-1)
+
+/* hash_search operations */
+typedef enum
+{
+ HASH_FIND,
+ HASH_ENTER,
+ HASH_REMOVE,
+ HASH_ENTER_NULL
+} HASHACTION;
+
+/* hash_seq status (should be considered an opaque type by callers) */
+typedef struct
+{
+ HTAB *hashp;
+ uint32 curBucket; /* index of current bucket */
+ HASHELEMENT *curEntry; /* current entry in bucket */
+} HASH_SEQ_STATUS;
+
+/*
+ * prototypes for functions in dynahash.c
+ */
+extern HTAB *hash_create(const char *tabname, long nelem,
+ const HASHCTL *info, int flags);
+extern void hash_destroy(HTAB *hashp);
+extern void hash_stats(const char *where, HTAB *hashp);
+extern void *hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action,
+ bool *foundPtr);
+extern uint32 get_hash_value(HTAB *hashp, const void *keyPtr);
+extern void *hash_search_with_hash_value(HTAB *hashp, const void *keyPtr,
+ uint32 hashvalue, HASHACTION action,
+ bool *foundPtr);
+extern bool hash_update_hash_key(HTAB *hashp, void *existingEntry,
+ const void *newKeyPtr);
+extern long hash_get_num_entries(HTAB *hashp);
+extern void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp);
+extern void *hash_seq_search(HASH_SEQ_STATUS *status);
+extern void hash_seq_term(HASH_SEQ_STATUS *status);
+extern void hash_freeze(HTAB *hashp);
+extern Size hash_estimate_size(long num_entries, Size entrysize);
+extern long hash_select_dirsize(long num_entries);
+extern Size hash_get_shared_size(HASHCTL *info, int flags);
+extern void AtEOXact_HashTables(bool isCommit);
+extern void AtEOSubXact_HashTables(bool isCommit, int nestDepth);
+
+#endif /* HSEARCH_H */
diff --git a/pgsql/include/server/utils/index_selfuncs.h b/pgsql/include/server/utils/index_selfuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..f081a1a326b3dbd61e8dc6840f030a8512f83e04
--- /dev/null
+++ b/pgsql/include/server/utils/index_selfuncs.h
@@ -0,0 +1,74 @@
+/*-------------------------------------------------------------------------
+ *
+ * index_selfuncs.h
+ * Index cost estimation functions for standard index access methods.
+ *
+ *
+ * Note: this is split out of selfuncs.h mainly to avoid importing all of the
+ * planner's data structures into the non-planner parts of the index AMs.
+ * If you make it depend on anything besides access/amapi.h, that's likely
+ * a mistake.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/index_selfuncs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef INDEX_SELFUNCS_H
+#define INDEX_SELFUNCS_H
+
+#include "access/amapi.h"
+
+/* Functions in selfuncs.c */
+extern void brincostestimate(struct PlannerInfo *root,
+ struct IndexPath *path,
+ double loop_count,
+ Cost *indexStartupCost,
+ Cost *indexTotalCost,
+ Selectivity *indexSelectivity,
+ double *indexCorrelation,
+ double *indexPages);
+extern void btcostestimate(struct PlannerInfo *root,
+ struct IndexPath *path,
+ double loop_count,
+ Cost *indexStartupCost,
+ Cost *indexTotalCost,
+ Selectivity *indexSelectivity,
+ double *indexCorrelation,
+ double *indexPages);
+extern void hashcostestimate(struct PlannerInfo *root,
+ struct IndexPath *path,
+ double loop_count,
+ Cost *indexStartupCost,
+ Cost *indexTotalCost,
+ Selectivity *indexSelectivity,
+ double *indexCorrelation,
+ double *indexPages);
+extern void gistcostestimate(struct PlannerInfo *root,
+ struct IndexPath *path,
+ double loop_count,
+ Cost *indexStartupCost,
+ Cost *indexTotalCost,
+ Selectivity *indexSelectivity,
+ double *indexCorrelation,
+ double *indexPages);
+extern void spgcostestimate(struct PlannerInfo *root,
+ struct IndexPath *path,
+ double loop_count,
+ Cost *indexStartupCost,
+ Cost *indexTotalCost,
+ Selectivity *indexSelectivity,
+ double *indexCorrelation,
+ double *indexPages);
+extern void gincostestimate(struct PlannerInfo *root,
+ struct IndexPath *path,
+ double loop_count,
+ Cost *indexStartupCost,
+ Cost *indexTotalCost,
+ Selectivity *indexSelectivity,
+ double *indexCorrelation,
+ double *indexPages);
+
+#endif /* INDEX_SELFUNCS_H */
diff --git a/pgsql/include/server/utils/inet.h b/pgsql/include/server/utils/inet.h
new file mode 100644
index 0000000000000000000000000000000000000000..96d9f6a234b36ad865924a035096a0e1b068b846
--- /dev/null
+++ b/pgsql/include/server/utils/inet.h
@@ -0,0 +1,184 @@
+/*-------------------------------------------------------------------------
+ *
+ * inet.h
+ * Declarations for operations on INET datatypes.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/inet.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef INET_H
+#define INET_H
+
+#include "fmgr.h"
+
+/*
+ * This is the internal storage format for IP addresses
+ * (both INET and CIDR datatypes):
+ */
+typedef struct
+{
+ unsigned char family; /* PGSQL_AF_INET or PGSQL_AF_INET6 */
+ unsigned char bits; /* number of bits in netmask */
+ unsigned char ipaddr[16]; /* up to 128 bits of address */
+} inet_struct;
+
+/*
+ * We use these values for the "family" field.
+ *
+ * Referencing all of the non-AF_INET types to AF_INET lets us work on
+ * machines which did not have the appropriate address family (like
+ * inet6 addresses when AF_INET6 wasn't present) but didn't cause a
+ * dump/reload requirement. Pre-7.4 databases used AF_INET for the family
+ * type on disk.
+ */
+#define PGSQL_AF_INET (AF_INET + 0)
+#define PGSQL_AF_INET6 (AF_INET + 1)
+
+/*
+ * Both INET and CIDR addresses are represented within Postgres as varlena
+ * objects, ie, there is a varlena header in front of the struct type
+ * depicted above. This struct depicts what we actually have in memory
+ * in "uncompressed" cases. Note that since the maximum data size is only
+ * 18 bytes, INET/CIDR will invariably be stored into tuples using the
+ * 1-byte-header varlena format. However, we have to be prepared to cope
+ * with the 4-byte-header format too, because various code may helpfully
+ * try to "decompress" 1-byte-header datums.
+ */
+typedef struct
+{
+ char vl_len_[4]; /* Do not touch this field directly! */
+ inet_struct inet_data;
+} inet;
+
+/*
+ * Access macros. We use VARDATA_ANY so that we can process short-header
+ * varlena values without detoasting them. This requires a trick:
+ * VARDATA_ANY assumes the varlena header is already filled in, which is
+ * not the case when constructing a new value (until SET_INET_VARSIZE is
+ * called, which we typically can't do till the end). Therefore, we
+ * always initialize the newly-allocated value to zeroes (using palloc0).
+ * A zero length word will look like the not-1-byte case to VARDATA_ANY,
+ * and so we correctly construct an uncompressed value.
+ *
+ * Note that ip_addrsize(), ip_maxbits(), and SET_INET_VARSIZE() require
+ * the family field to be set correctly.
+ */
+#define ip_family(inetptr) \
+ (((inet_struct *) VARDATA_ANY(inetptr))->family)
+
+#define ip_bits(inetptr) \
+ (((inet_struct *) VARDATA_ANY(inetptr))->bits)
+
+#define ip_addr(inetptr) \
+ (((inet_struct *) VARDATA_ANY(inetptr))->ipaddr)
+
+#define ip_addrsize(inetptr) \
+ (ip_family(inetptr) == PGSQL_AF_INET ? 4 : 16)
+
+#define ip_maxbits(inetptr) \
+ (ip_family(inetptr) == PGSQL_AF_INET ? 32 : 128)
+
+#define SET_INET_VARSIZE(dst) \
+ SET_VARSIZE(dst, VARHDRSZ + offsetof(inet_struct, ipaddr) + \
+ ip_addrsize(dst))
+
+
+/*
+ * This is the internal storage format for MAC addresses:
+ */
+typedef struct macaddr
+{
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+ unsigned char d;
+ unsigned char e;
+ unsigned char f;
+} macaddr;
+
+/*
+ * This is the internal storage format for MAC8 addresses:
+ */
+typedef struct macaddr8
+{
+ unsigned char a;
+ unsigned char b;
+ unsigned char c;
+ unsigned char d;
+ unsigned char e;
+ unsigned char f;
+ unsigned char g;
+ unsigned char h;
+} macaddr8;
+
+/*
+ * fmgr interface macros
+ */
+static inline inet *
+DatumGetInetPP(Datum X)
+{
+ return (inet *) PG_DETOAST_DATUM_PACKED(X);
+}
+
+static inline Datum
+InetPGetDatum(const inet *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_INET_PP(n) DatumGetInetPP(PG_GETARG_DATUM(n))
+#define PG_RETURN_INET_P(x) return InetPGetDatum(x)
+
+/* obsolescent variants */
+static inline inet *
+DatumGetInetP(Datum X)
+{
+ return (inet *) PG_DETOAST_DATUM(X);
+}
+#define PG_GETARG_INET_P(n) DatumGetInetP(PG_GETARG_DATUM(n))
+
+/* macaddr is a fixed-length pass-by-reference datatype */
+static inline macaddr *
+DatumGetMacaddrP(Datum X)
+{
+ return (macaddr *) DatumGetPointer(X);
+}
+
+static inline Datum
+MacaddrPGetDatum(const macaddr *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_MACADDR_P(n) DatumGetMacaddrP(PG_GETARG_DATUM(n))
+#define PG_RETURN_MACADDR_P(x) return MacaddrPGetDatum(x)
+
+/* macaddr8 is a fixed-length pass-by-reference datatype */
+static inline macaddr8 *
+DatumGetMacaddr8P(Datum X)
+{
+ return (macaddr8 *) DatumGetPointer(X);
+}
+
+static inline Datum
+Macaddr8PGetDatum(const macaddr8 *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_MACADDR8_P(n) DatumGetMacaddr8P(PG_GETARG_DATUM(n))
+#define PG_RETURN_MACADDR8_P(x) return Macaddr8PGetDatum(x)
+
+/*
+ * Support functions in network.c
+ */
+extern inet *cidr_set_masklen_internal(const inet *src, int bits);
+extern int bitncmp(const unsigned char *l, const unsigned char *r, int n);
+extern int bitncommon(const unsigned char *l, const unsigned char *r, int n);
+
+#endif /* INET_H */
diff --git a/pgsql/include/server/utils/inval.h b/pgsql/include/server/utils/inval.h
new file mode 100644
index 0000000000000000000000000000000000000000..14b4eac06304de90bc1afbee50fce41dbefa0f2e
--- /dev/null
+++ b/pgsql/include/server/utils/inval.h
@@ -0,0 +1,68 @@
+/*-------------------------------------------------------------------------
+ *
+ * inval.h
+ * POSTGRES cache invalidation dispatcher definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/inval.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef INVAL_H
+#define INVAL_H
+
+#include "access/htup.h"
+#include "storage/relfilelocator.h"
+#include "utils/relcache.h"
+
+extern PGDLLIMPORT int debug_discard_caches;
+
+typedef void (*SyscacheCallbackFunction) (Datum arg, int cacheid, uint32 hashvalue);
+typedef void (*RelcacheCallbackFunction) (Datum arg, Oid relid);
+
+
+extern void AcceptInvalidationMessages(void);
+
+extern void AtEOXact_Inval(bool isCommit);
+
+extern void AtEOSubXact_Inval(bool isCommit);
+
+extern void PostPrepare_Inval(void);
+
+extern void CommandEndInvalidationMessages(void);
+
+extern void CacheInvalidateHeapTuple(Relation relation,
+ HeapTuple tuple,
+ HeapTuple newtuple);
+
+extern void CacheInvalidateCatalog(Oid catalogId);
+
+extern void CacheInvalidateRelcache(Relation relation);
+
+extern void CacheInvalidateRelcacheAll(void);
+
+extern void CacheInvalidateRelcacheByTuple(HeapTuple classTuple);
+
+extern void CacheInvalidateRelcacheByRelid(Oid relid);
+
+extern void CacheInvalidateSmgr(RelFileLocatorBackend rlocator);
+
+extern void CacheInvalidateRelmap(Oid databaseId);
+
+extern void CacheRegisterSyscacheCallback(int cacheid,
+ SyscacheCallbackFunction func,
+ Datum arg);
+
+extern void CacheRegisterRelcacheCallback(RelcacheCallbackFunction func,
+ Datum arg);
+
+extern void CallSyscacheCallbacks(int cacheid, uint32 hashvalue);
+
+extern void InvalidateSystemCaches(void);
+extern void InvalidateSystemCachesExtended(bool debug_discard);
+
+extern void LogLogicalInvalidations(void);
+#endif /* INVAL_H */
diff --git a/pgsql/include/server/utils/json.h b/pgsql/include/server/utils/json.h
new file mode 100644
index 0000000000000000000000000000000000000000..35a9a5545d85ec8c805eb9a9d11400576ae24ff5
--- /dev/null
+++ b/pgsql/include/server/utils/json.h
@@ -0,0 +1,31 @@
+/*-------------------------------------------------------------------------
+ *
+ * json.h
+ * Declarations for JSON data type support.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/json.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef JSON_H
+#define JSON_H
+
+#include "lib/stringinfo.h"
+
+/* functions in json.c */
+extern void escape_json(StringInfo buf, const char *str);
+extern char *JsonEncodeDateTime(char *buf, Datum value, Oid typid,
+ const int *tzp);
+extern bool to_json_is_immutable(Oid typoid);
+extern Datum json_build_object_worker(int nargs, Datum *args, bool *nulls,
+ Oid *types, bool absent_on_null,
+ bool unique_keys);
+extern Datum json_build_array_worker(int nargs, Datum *args, bool *nulls,
+ Oid *types, bool absent_on_null);
+extern bool json_validate(text *json, bool check_unique_keys, bool throw_error);
+
+#endif /* JSON_H */
diff --git a/pgsql/include/server/utils/jsonb.h b/pgsql/include/server/utils/jsonb.h
new file mode 100644
index 0000000000000000000000000000000000000000..649a1644f24c2cf0f7dd894db5321408fc58f12a
--- /dev/null
+++ b/pgsql/include/server/utils/jsonb.h
@@ -0,0 +1,439 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonb.h
+ * Declarations for jsonb data type support.
+ *
+ * Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/jsonb.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef __JSONB_H__
+#define __JSONB_H__
+
+#include "lib/stringinfo.h"
+#include "utils/array.h"
+#include "utils/numeric.h"
+
+/* Tokens used when sequentially processing a jsonb value */
+typedef enum
+{
+ WJB_DONE,
+ WJB_KEY,
+ WJB_VALUE,
+ WJB_ELEM,
+ WJB_BEGIN_ARRAY,
+ WJB_END_ARRAY,
+ WJB_BEGIN_OBJECT,
+ WJB_END_OBJECT
+} JsonbIteratorToken;
+
+/* Strategy numbers for GIN index opclasses */
+#define JsonbContainsStrategyNumber 7
+#define JsonbExistsStrategyNumber 9
+#define JsonbExistsAnyStrategyNumber 10
+#define JsonbExistsAllStrategyNumber 11
+#define JsonbJsonpathExistsStrategyNumber 15
+#define JsonbJsonpathPredicateStrategyNumber 16
+
+
+/*
+ * In the standard jsonb_ops GIN opclass for jsonb, we choose to index both
+ * keys and values. The storage format is text. The first byte of the text
+ * string distinguishes whether this is a key (always a string), null value,
+ * boolean value, numeric value, or string value. However, array elements
+ * that are strings are marked as though they were keys; this imprecision
+ * supports the definition of the "exists" operator, which treats array
+ * elements like keys. The remainder of the text string is empty for a null
+ * value, "t" or "f" for a boolean value, a normalized print representation of
+ * a numeric value, or the text of a string value. However, if the length of
+ * this text representation would exceed JGIN_MAXLENGTH bytes, we instead hash
+ * the text representation and store an 8-hex-digit representation of the
+ * uint32 hash value, marking the prefix byte with an additional bit to
+ * distinguish that this has happened. Hashing long strings saves space and
+ * ensures that we won't overrun the maximum entry length for a GIN index.
+ * (But JGIN_MAXLENGTH is quite a bit shorter than GIN's limit. It's chosen
+ * to ensure that the on-disk text datum will have a short varlena header.)
+ * Note that when any hashed item appears in a query, we must recheck index
+ * matches against the heap tuple; currently, this costs nothing because we
+ * must always recheck for other reasons.
+ */
+#define JGINFLAG_KEY 0x01 /* key (or string array element) */
+#define JGINFLAG_NULL 0x02 /* null value */
+#define JGINFLAG_BOOL 0x03 /* boolean value */
+#define JGINFLAG_NUM 0x04 /* numeric value */
+#define JGINFLAG_STR 0x05 /* string value (if not an array element) */
+#define JGINFLAG_HASHED 0x10 /* OR'd into flag if value was hashed */
+#define JGIN_MAXLENGTH 125 /* max length of text part before hashing */
+
+typedef struct JsonbPair JsonbPair;
+typedef struct JsonbValue JsonbValue;
+
+/*
+ * Jsonbs are varlena objects, so must meet the varlena convention that the
+ * first int32 of the object contains the total object size in bytes. Be sure
+ * to use VARSIZE() and SET_VARSIZE() to access it, though!
+ *
+ * Jsonb is the on-disk representation, in contrast to the in-memory JsonbValue
+ * representation. Often, JsonbValues are just shims through which a Jsonb
+ * buffer is accessed, but they can also be deep copied and passed around.
+ *
+ * Jsonb is a tree structure. Each node in the tree consists of a JEntry
+ * header and a variable-length content (possibly of zero size). The JEntry
+ * header indicates what kind of a node it is, e.g. a string or an array,
+ * and provides the length of its variable-length portion.
+ *
+ * The JEntry and the content of a node are not stored physically together.
+ * Instead, the container array or object has an array that holds the JEntrys
+ * of all the child nodes, followed by their variable-length portions.
+ *
+ * The root node is an exception; it has no parent array or object that could
+ * hold its JEntry. Hence, no JEntry header is stored for the root node. It
+ * is implicitly known that the root node must be an array or an object,
+ * so we can get away without the type indicator as long as we can distinguish
+ * the two. For that purpose, both an array and an object begin with a uint32
+ * header field, which contains an JB_FOBJECT or JB_FARRAY flag. When a naked
+ * scalar value needs to be stored as a Jsonb value, what we actually store is
+ * an array with one element, with the flags in the array's header field set
+ * to JB_FSCALAR | JB_FARRAY.
+ *
+ * Overall, the Jsonb struct requires 4-bytes alignment. Within the struct,
+ * the variable-length portion of some node types is aligned to a 4-byte
+ * boundary, while others are not. When alignment is needed, the padding is
+ * in the beginning of the node that requires it. For example, if a numeric
+ * node is stored after a string node, so that the numeric node begins at
+ * offset 3, the variable-length portion of the numeric node will begin with
+ * one padding byte so that the actual numeric data is 4-byte aligned.
+ */
+
+/*
+ * JEntry format.
+ *
+ * The least significant 28 bits store either the data length of the entry,
+ * or its end+1 offset from the start of the variable-length portion of the
+ * containing object. The next three bits store the type of the entry, and
+ * the high-order bit tells whether the least significant bits store a length
+ * or an offset.
+ *
+ * The reason for the offset-or-length complication is to compromise between
+ * access speed and data compressibility. In the initial design each JEntry
+ * always stored an offset, but this resulted in JEntry arrays with horrible
+ * compressibility properties, so that TOAST compression of a JSONB did not
+ * work well. Storing only lengths would greatly improve compressibility,
+ * but it makes random access into large arrays expensive (O(N) not O(1)).
+ * So what we do is store an offset in every JB_OFFSET_STRIDE'th JEntry and
+ * a length in the rest. This results in reasonably compressible data (as
+ * long as the stride isn't too small). We may have to examine as many as
+ * JB_OFFSET_STRIDE JEntrys in order to find out the offset or length of any
+ * given item, but that's still O(1) no matter how large the container is.
+ *
+ * We could avoid eating a flag bit for this purpose if we were to store
+ * the stride in the container header, or if we were willing to treat the
+ * stride as an unchangeable constant. Neither of those options is very
+ * attractive though.
+ */
+typedef uint32 JEntry;
+
+#define JENTRY_OFFLENMASK 0x0FFFFFFF
+#define JENTRY_TYPEMASK 0x70000000
+#define JENTRY_HAS_OFF 0x80000000
+
+/* values stored in the type bits */
+#define JENTRY_ISSTRING 0x00000000
+#define JENTRY_ISNUMERIC 0x10000000
+#define JENTRY_ISBOOL_FALSE 0x20000000
+#define JENTRY_ISBOOL_TRUE 0x30000000
+#define JENTRY_ISNULL 0x40000000
+#define JENTRY_ISCONTAINER 0x50000000 /* array or object */
+
+/* Access macros. Note possible multiple evaluations */
+#define JBE_OFFLENFLD(je_) ((je_) & JENTRY_OFFLENMASK)
+#define JBE_HAS_OFF(je_) (((je_) & JENTRY_HAS_OFF) != 0)
+#define JBE_ISSTRING(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISSTRING)
+#define JBE_ISNUMERIC(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISNUMERIC)
+#define JBE_ISCONTAINER(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISCONTAINER)
+#define JBE_ISNULL(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISNULL)
+#define JBE_ISBOOL_TRUE(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISBOOL_TRUE)
+#define JBE_ISBOOL_FALSE(je_) (((je_) & JENTRY_TYPEMASK) == JENTRY_ISBOOL_FALSE)
+#define JBE_ISBOOL(je_) (JBE_ISBOOL_TRUE(je_) || JBE_ISBOOL_FALSE(je_))
+
+/* Macro for advancing an offset variable to the next JEntry */
+#define JBE_ADVANCE_OFFSET(offset, je) \
+ do { \
+ JEntry je_ = (je); \
+ if (JBE_HAS_OFF(je_)) \
+ (offset) = JBE_OFFLENFLD(je_); \
+ else \
+ (offset) += JBE_OFFLENFLD(je_); \
+ } while(0)
+
+/*
+ * We store an offset, not a length, every JB_OFFSET_STRIDE children.
+ * Caution: this macro should only be referenced when creating a JSONB
+ * value. When examining an existing value, pay attention to the HAS_OFF
+ * bits instead. This allows changes in the offset-placement heuristic
+ * without breaking on-disk compatibility.
+ */
+#define JB_OFFSET_STRIDE 32
+
+/*
+ * A jsonb array or object node, within a Jsonb Datum.
+ *
+ * An array has one child for each element, stored in array order.
+ *
+ * An object has two children for each key/value pair. The keys all appear
+ * first, in key sort order; then the values appear, in an order matching the
+ * key order. This arrangement keeps the keys compact in memory, making a
+ * search for a particular key more cache-friendly.
+ */
+typedef struct JsonbContainer
+{
+ uint32 header; /* number of elements or key/value pairs, and
+ * flags */
+ JEntry children[FLEXIBLE_ARRAY_MEMBER];
+
+ /* the data for each child node follows. */
+} JsonbContainer;
+
+/* flags for the header-field in JsonbContainer */
+#define JB_CMASK 0x0FFFFFFF /* mask for count field */
+#define JB_FSCALAR 0x10000000 /* flag bits */
+#define JB_FOBJECT 0x20000000
+#define JB_FARRAY 0x40000000
+
+/* convenience macros for accessing a JsonbContainer struct */
+#define JsonContainerSize(jc) ((jc)->header & JB_CMASK)
+#define JsonContainerIsScalar(jc) (((jc)->header & JB_FSCALAR) != 0)
+#define JsonContainerIsObject(jc) (((jc)->header & JB_FOBJECT) != 0)
+#define JsonContainerIsArray(jc) (((jc)->header & JB_FARRAY) != 0)
+
+/* The top-level on-disk format for a jsonb datum. */
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ JsonbContainer root;
+} Jsonb;
+
+/* convenience macros for accessing the root container in a Jsonb datum */
+#define JB_ROOT_COUNT(jbp_) (*(uint32 *) VARDATA(jbp_) & JB_CMASK)
+#define JB_ROOT_IS_SCALAR(jbp_) ((*(uint32 *) VARDATA(jbp_) & JB_FSCALAR) != 0)
+#define JB_ROOT_IS_OBJECT(jbp_) ((*(uint32 *) VARDATA(jbp_) & JB_FOBJECT) != 0)
+#define JB_ROOT_IS_ARRAY(jbp_) ((*(uint32 *) VARDATA(jbp_) & JB_FARRAY) != 0)
+
+
+enum jbvType
+{
+ /* Scalar types */
+ jbvNull = 0x0,
+ jbvString,
+ jbvNumeric,
+ jbvBool,
+ /* Composite types */
+ jbvArray = 0x10,
+ jbvObject,
+ /* Binary (i.e. struct Jsonb) jbvArray/jbvObject */
+ jbvBinary,
+
+ /*
+ * Virtual types.
+ *
+ * These types are used only for in-memory JSON processing and serialized
+ * into JSON strings when outputted to json/jsonb.
+ */
+ jbvDatetime = 0x20,
+};
+
+/*
+ * JsonbValue: In-memory representation of Jsonb. This is a convenient
+ * deserialized representation, that can easily support using the "val"
+ * union across underlying types during manipulation. The Jsonb on-disk
+ * representation has various alignment considerations.
+ */
+struct JsonbValue
+{
+ enum jbvType type; /* Influences sort order */
+
+ union
+ {
+ Numeric numeric;
+ bool boolean;
+ struct
+ {
+ int len;
+ char *val; /* Not necessarily null-terminated */
+ } string; /* String primitive type */
+
+ struct
+ {
+ int nElems;
+ JsonbValue *elems;
+ bool rawScalar; /* Top-level "raw scalar" array? */
+ } array; /* Array container type */
+
+ struct
+ {
+ int nPairs; /* 1 pair, 2 elements */
+ JsonbPair *pairs;
+ } object; /* Associative container type */
+
+ struct
+ {
+ int len;
+ JsonbContainer *data;
+ } binary; /* Array or object, in on-disk format */
+
+ struct
+ {
+ Datum value;
+ Oid typid;
+ int32 typmod;
+ int tz; /* Numeric time zone, in seconds, for
+ * TimestampTz data type */
+ } datetime;
+ } val;
+};
+
+#define IsAJsonbScalar(jsonbval) (((jsonbval)->type >= jbvNull && \
+ (jsonbval)->type <= jbvBool) || \
+ (jsonbval)->type == jbvDatetime)
+
+/*
+ * Key/value pair within an Object.
+ *
+ * This struct type is only used briefly while constructing a Jsonb; it is
+ * *not* the on-disk representation.
+ *
+ * Pairs with duplicate keys are de-duplicated. We store the originally
+ * observed pair ordering for the purpose of removing duplicates in a
+ * well-defined way (which is "last observed wins").
+ */
+struct JsonbPair
+{
+ JsonbValue key; /* Must be a jbvString */
+ JsonbValue value; /* May be of any type */
+ uint32 order; /* Pair's index in original sequence */
+};
+
+/* Conversion state used when parsing Jsonb from text, or for type coercion */
+typedef struct JsonbParseState
+{
+ JsonbValue contVal;
+ Size size;
+ struct JsonbParseState *next;
+ bool unique_keys; /* Check object key uniqueness */
+ bool skip_nulls; /* Skip null object fields */
+} JsonbParseState;
+
+/*
+ * JsonbIterator holds details of the type for each iteration. It also stores a
+ * Jsonb varlena buffer, which can be directly accessed in some contexts.
+ */
+typedef enum
+{
+ JBI_ARRAY_START,
+ JBI_ARRAY_ELEM,
+ JBI_OBJECT_START,
+ JBI_OBJECT_KEY,
+ JBI_OBJECT_VALUE
+} JsonbIterState;
+
+typedef struct JsonbIterator
+{
+ /* Container being iterated */
+ JsonbContainer *container;
+ uint32 nElems; /* Number of elements in children array (will
+ * be nPairs for objects) */
+ bool isScalar; /* Pseudo-array scalar value? */
+ JEntry *children; /* JEntrys for child nodes */
+ /* Data proper. This points to the beginning of the variable-length data */
+ char *dataProper;
+
+ /* Current item in buffer (up to nElems) */
+ int curIndex;
+
+ /* Data offset corresponding to current item */
+ uint32 curDataOffset;
+
+ /*
+ * If the container is an object, we want to return keys and values
+ * alternately; so curDataOffset points to the current key, and
+ * curValueOffset points to the current value.
+ */
+ uint32 curValueOffset;
+
+ /* Private state */
+ JsonbIterState state;
+
+ struct JsonbIterator *parent;
+} JsonbIterator;
+
+
+/* Convenience macros */
+static inline Jsonb *
+DatumGetJsonbP(Datum d)
+{
+ return (Jsonb *) PG_DETOAST_DATUM(d);
+}
+
+static inline Jsonb *
+DatumGetJsonbPCopy(Datum d)
+{
+ return (Jsonb *) PG_DETOAST_DATUM_COPY(d);
+}
+
+static inline Datum
+JsonbPGetDatum(const Jsonb *p)
+{
+ return PointerGetDatum(p);
+}
+
+#define PG_GETARG_JSONB_P(x) DatumGetJsonbP(PG_GETARG_DATUM(x))
+#define PG_GETARG_JSONB_P_COPY(x) DatumGetJsonbPCopy(PG_GETARG_DATUM(x))
+#define PG_RETURN_JSONB_P(x) PG_RETURN_POINTER(x)
+
+/* Support functions */
+extern uint32 getJsonbOffset(const JsonbContainer *jc, int index);
+extern uint32 getJsonbLength(const JsonbContainer *jc, int index);
+extern int compareJsonbContainers(JsonbContainer *a, JsonbContainer *b);
+extern JsonbValue *findJsonbValueFromContainer(JsonbContainer *container,
+ uint32 flags,
+ JsonbValue *key);
+extern JsonbValue *getKeyJsonValueFromContainer(JsonbContainer *container,
+ const char *keyVal, int keyLen,
+ JsonbValue *res);
+extern JsonbValue *getIthJsonbValueFromContainer(JsonbContainer *container,
+ uint32 i);
+extern JsonbValue *pushJsonbValue(JsonbParseState **pstate,
+ JsonbIteratorToken seq, JsonbValue *jbval);
+extern JsonbIterator *JsonbIteratorInit(JsonbContainer *container);
+extern JsonbIteratorToken JsonbIteratorNext(JsonbIterator **it, JsonbValue *val,
+ bool skipNested);
+extern void JsonbToJsonbValue(Jsonb *jsonb, JsonbValue *val);
+extern Jsonb *JsonbValueToJsonb(JsonbValue *val);
+extern bool JsonbDeepContains(JsonbIterator **val,
+ JsonbIterator **mContained);
+extern void JsonbHashScalarValue(const JsonbValue *scalarVal, uint32 *hash);
+extern void JsonbHashScalarValueExtended(const JsonbValue *scalarVal,
+ uint64 *hash, uint64 seed);
+
+/* jsonb.c support functions */
+extern char *JsonbToCString(StringInfo out, JsonbContainer *in,
+ int estimated_len);
+extern char *JsonbToCStringIndent(StringInfo out, JsonbContainer *in,
+ int estimated_len);
+extern bool JsonbExtractScalar(JsonbContainer *jbc, JsonbValue *res);
+extern const char *JsonbTypeName(JsonbValue *val);
+
+extern Datum jsonb_set_element(Jsonb *jb, Datum *path, int path_len,
+ JsonbValue *newval);
+extern Datum jsonb_get_element(Jsonb *jb, Datum *path, int npath,
+ bool *isnull, bool as_text);
+extern bool to_jsonb_is_immutable(Oid typoid);
+extern Datum jsonb_build_object_worker(int nargs, Datum *args, bool *nulls,
+ Oid *types, bool absent_on_null,
+ bool unique_keys);
+extern Datum jsonb_build_array_worker(int nargs, Datum *args, bool *nulls,
+ Oid *types, bool absent_on_null);
+
+#endif /* __JSONB_H__ */
diff --git a/pgsql/include/server/utils/jsonfuncs.h b/pgsql/include/server/utils/jsonfuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..a85203d4a4ba4f773f11ea13f4d1075e1da9dab2
--- /dev/null
+++ b/pgsql/include/server/utils/jsonfuncs.h
@@ -0,0 +1,66 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonfuncs.h
+ * Functions to process JSON data types.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/jsonfuncs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef JSONFUNCS_H
+#define JSONFUNCS_H
+
+#include "common/jsonapi.h"
+#include "utils/jsonb.h"
+
+/*
+ * Flag types for iterate_json(b)_values to specify what elements from a
+ * json(b) document we want to iterate.
+ */
+typedef enum JsonToIndex
+{
+ jtiKey = 0x01,
+ jtiString = 0x02,
+ jtiNumeric = 0x04,
+ jtiBool = 0x08,
+ jtiAll = jtiKey | jtiString | jtiNumeric | jtiBool
+} JsonToIndex;
+
+/* an action that will be applied to each value in iterate_json(b)_values functions */
+typedef void (*JsonIterateStringValuesAction) (void *state, char *elem_value, int elem_len);
+
+/* an action that will be applied to each value in transform_json(b)_values functions */
+typedef text *(*JsonTransformStringValuesAction) (void *state, char *elem_value, int elem_len);
+
+/* build a JsonLexContext from a text datum */
+extern JsonLexContext *makeJsonLexContext(text *json, bool need_escapes);
+
+/* try to parse json, and errsave(escontext) on failure */
+extern bool pg_parse_json_or_errsave(JsonLexContext *lex, JsonSemAction *sem,
+ struct Node *escontext);
+
+#define pg_parse_json_or_ereport(lex, sem) \
+ (void) pg_parse_json_or_errsave(lex, sem, NULL)
+
+/* save an error during json lexing or parsing */
+extern void json_errsave_error(JsonParseErrorType error, JsonLexContext *lex,
+ struct Node *escontext);
+
+/* get first JSON token */
+extern JsonTokenType json_get_first_token(text *json, bool throw_error);
+
+extern uint32 parse_jsonb_index_flags(Jsonb *jb);
+extern void iterate_jsonb_values(Jsonb *jb, uint32 flags, void *state,
+ JsonIterateStringValuesAction action);
+extern void iterate_json_values(text *json, uint32 flags, void *action_state,
+ JsonIterateStringValuesAction action);
+extern Jsonb *transform_jsonb_string_values(Jsonb *jsonb, void *action_state,
+ JsonTransformStringValuesAction transform_action);
+extern text *transform_json_string_values(text *json, void *action_state,
+ JsonTransformStringValuesAction transform_action);
+
+#endif
diff --git a/pgsql/include/server/utils/jsonpath.h b/pgsql/include/server/utils/jsonpath.h
new file mode 100644
index 0000000000000000000000000000000000000000..f0181e045f795207f866b5b10069bbca207a3756
--- /dev/null
+++ b/pgsql/include/server/utils/jsonpath.h
@@ -0,0 +1,264 @@
+/*-------------------------------------------------------------------------
+ *
+ * jsonpath.h
+ * Definitions for jsonpath datatype
+ *
+ * Copyright (c) 2019-2023, PostgreSQL Global Development Group
+ *
+ * IDENTIFICATION
+ * src/include/utils/jsonpath.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef JSONPATH_H
+#define JSONPATH_H
+
+#include "fmgr.h"
+#include "nodes/pg_list.h"
+#include "utils/jsonb.h"
+
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ uint32 header; /* version and flags (see below) */
+ char data[FLEXIBLE_ARRAY_MEMBER];
+} JsonPath;
+
+#define JSONPATH_VERSION (0x01)
+#define JSONPATH_LAX (0x80000000)
+#define JSONPATH_HDRSZ (offsetof(JsonPath, data))
+
+static inline JsonPath *
+DatumGetJsonPathP(Datum d)
+{
+ return (JsonPath *) PG_DETOAST_DATUM(d);
+}
+
+static inline JsonPath *
+DatumGetJsonPathPCopy(Datum d)
+{
+ return (JsonPath *) PG_DETOAST_DATUM_COPY(d);
+}
+
+#define PG_GETARG_JSONPATH_P(x) DatumGetJsonPathP(PG_GETARG_DATUM(x))
+#define PG_GETARG_JSONPATH_P_COPY(x) DatumGetJsonPathPCopy(PG_GETARG_DATUM(x))
+#define PG_RETURN_JSONPATH_P(p) PG_RETURN_POINTER(p)
+
+#define jspIsScalar(type) ((type) >= jpiNull && (type) <= jpiBool)
+
+/*
+ * All node's type of jsonpath expression
+ */
+typedef enum JsonPathItemType
+{
+ jpiNull = jbvNull, /* NULL literal */
+ jpiString = jbvString, /* string literal */
+ jpiNumeric = jbvNumeric, /* numeric literal */
+ jpiBool = jbvBool, /* boolean literal: TRUE or FALSE */
+ jpiAnd, /* predicate && predicate */
+ jpiOr, /* predicate || predicate */
+ jpiNot, /* ! predicate */
+ jpiIsUnknown, /* (predicate) IS UNKNOWN */
+ jpiEqual, /* expr == expr */
+ jpiNotEqual, /* expr != expr */
+ jpiLess, /* expr < expr */
+ jpiGreater, /* expr > expr */
+ jpiLessOrEqual, /* expr <= expr */
+ jpiGreaterOrEqual, /* expr >= expr */
+ jpiAdd, /* expr + expr */
+ jpiSub, /* expr - expr */
+ jpiMul, /* expr * expr */
+ jpiDiv, /* expr / expr */
+ jpiMod, /* expr % expr */
+ jpiPlus, /* + expr */
+ jpiMinus, /* - expr */
+ jpiAnyArray, /* [*] */
+ jpiAnyKey, /* .* */
+ jpiIndexArray, /* [subscript, ...] */
+ jpiAny, /* .** */
+ jpiKey, /* .key */
+ jpiCurrent, /* @ */
+ jpiRoot, /* $ */
+ jpiVariable, /* $variable */
+ jpiFilter, /* ? (predicate) */
+ jpiExists, /* EXISTS (expr) predicate */
+ jpiType, /* .type() item method */
+ jpiSize, /* .size() item method */
+ jpiAbs, /* .abs() item method */
+ jpiFloor, /* .floor() item method */
+ jpiCeiling, /* .ceiling() item method */
+ jpiDouble, /* .double() item method */
+ jpiDatetime, /* .datetime() item method */
+ jpiKeyValue, /* .keyvalue() item method */
+ jpiSubscript, /* array subscript: 'expr' or 'expr TO expr' */
+ jpiLast, /* LAST array subscript */
+ jpiStartsWith, /* STARTS WITH predicate */
+ jpiLikeRegex, /* LIKE_REGEX predicate */
+} JsonPathItemType;
+
+/* XQuery regex mode flags for LIKE_REGEX predicate */
+#define JSP_REGEX_ICASE 0x01 /* i flag, case insensitive */
+#define JSP_REGEX_DOTALL 0x02 /* s flag, dot matches newline */
+#define JSP_REGEX_MLINE 0x04 /* m flag, ^/$ match at newlines */
+#define JSP_REGEX_WSPACE 0x08 /* x flag, ignore whitespace in pattern */
+#define JSP_REGEX_QUOTE 0x10 /* q flag, no special characters */
+
+/*
+ * Support functions to parse/construct binary value.
+ * Unlike many other representation of expression the first/main
+ * node is not an operation but left operand of expression. That
+ * allows to implement cheap follow-path descending in jsonb
+ * structure and then execute operator with right operand
+ */
+
+typedef struct JsonPathItem
+{
+ JsonPathItemType type;
+
+ /* position form base to next node */
+ int32 nextPos;
+
+ /*
+ * pointer into JsonPath value to current node, all positions of current
+ * are relative to this base
+ */
+ char *base;
+
+ union
+ {
+ /* classic operator with two operands: and, or etc */
+ struct
+ {
+ int32 left;
+ int32 right;
+ } args;
+
+ /* any unary operation */
+ int32 arg;
+
+ /* storage for jpiIndexArray: indexes of array */
+ struct
+ {
+ int32 nelems;
+ struct
+ {
+ int32 from;
+ int32 to;
+ } *elems;
+ } array;
+
+ /* jpiAny: levels */
+ struct
+ {
+ uint32 first;
+ uint32 last;
+ } anybounds;
+
+ struct
+ {
+ char *data; /* for bool, numeric and string/key */
+ int32 datalen; /* filled only for string/key */
+ } value;
+
+ struct
+ {
+ int32 expr;
+ char *pattern;
+ int32 patternlen;
+ uint32 flags;
+ } like_regex;
+ } content;
+} JsonPathItem;
+
+#define jspHasNext(jsp) ((jsp)->nextPos > 0)
+
+extern void jspInit(JsonPathItem *v, JsonPath *js);
+extern void jspInitByBuffer(JsonPathItem *v, char *base, int32 pos);
+extern bool jspGetNext(JsonPathItem *v, JsonPathItem *a);
+extern void jspGetArg(JsonPathItem *v, JsonPathItem *a);
+extern void jspGetLeftArg(JsonPathItem *v, JsonPathItem *a);
+extern void jspGetRightArg(JsonPathItem *v, JsonPathItem *a);
+extern Numeric jspGetNumeric(JsonPathItem *v);
+extern bool jspGetBool(JsonPathItem *v);
+extern char *jspGetString(JsonPathItem *v, int32 *len);
+extern bool jspGetArraySubscript(JsonPathItem *v, JsonPathItem *from,
+ JsonPathItem *to, int i);
+
+extern const char *jspOperationName(JsonPathItemType type);
+
+/*
+ * Parsing support data structures.
+ */
+
+typedef struct JsonPathParseItem JsonPathParseItem;
+
+struct JsonPathParseItem
+{
+ JsonPathItemType type;
+ JsonPathParseItem *next; /* next in path */
+
+ union
+ {
+
+ /* classic operator with two operands: and, or etc */
+ struct
+ {
+ JsonPathParseItem *left;
+ JsonPathParseItem *right;
+ } args;
+
+ /* any unary operation */
+ JsonPathParseItem *arg;
+
+ /* storage for jpiIndexArray: indexes of array */
+ struct
+ {
+ int nelems;
+ struct
+ {
+ JsonPathParseItem *from;
+ JsonPathParseItem *to;
+ } *elems;
+ } array;
+
+ /* jpiAny: levels */
+ struct
+ {
+ uint32 first;
+ uint32 last;
+ } anybounds;
+
+ struct
+ {
+ JsonPathParseItem *expr;
+ char *pattern; /* could not be not null-terminated */
+ uint32 patternlen;
+ uint32 flags;
+ } like_regex;
+
+ /* scalars */
+ Numeric numeric;
+ bool boolean;
+ struct
+ {
+ uint32 len;
+ char *val; /* could not be not null-terminated */
+ } string;
+ } value;
+};
+
+typedef struct JsonPathParseResult
+{
+ JsonPathParseItem *expr;
+ bool lax;
+} JsonPathParseResult;
+
+extern JsonPathParseResult *parsejsonpath(const char *str, int len,
+ struct Node *escontext);
+
+extern bool jspConvertRegexFlags(uint32 xflags, int *result,
+ struct Node *escontext);
+
+
+#endif
diff --git a/pgsql/include/server/utils/logtape.h b/pgsql/include/server/utils/logtape.h
new file mode 100644
index 0000000000000000000000000000000000000000..5420a24ac9b9a3c2e2bfd860587e6b82318da9cb
--- /dev/null
+++ b/pgsql/include/server/utils/logtape.h
@@ -0,0 +1,77 @@
+/*-------------------------------------------------------------------------
+ *
+ * logtape.h
+ * Management of "logical tapes" within temporary files.
+ *
+ * See logtape.c for explanations.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/logtape.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef LOGTAPE_H
+#define LOGTAPE_H
+
+#include "storage/sharedfileset.h"
+
+/*
+ * LogicalTapeSet and LogicalTape are opaque types whose details are not
+ * known outside logtape.c.
+ */
+typedef struct LogicalTapeSet LogicalTapeSet;
+typedef struct LogicalTape LogicalTape;
+
+
+/*
+ * The approach tuplesort.c takes to parallel external sorts is that workers,
+ * whose state is almost the same as independent serial sorts, are made to
+ * produce a final materialized tape of sorted output in all cases. This is
+ * frozen, just like any case requiring a final materialized tape. However,
+ * there is one difference, which is that freezing will also export an
+ * underlying shared fileset BufFile for sharing. Freezing produces TapeShare
+ * metadata for the worker when this happens, which is passed along through
+ * shared memory to leader.
+ *
+ * The leader process can then pass an array of TapeShare metadata (one per
+ * worker participant) to LogicalTapeSetCreate(), alongside a handle to a
+ * shared fileset, which is sufficient to construct a new logical tapeset that
+ * consists of each of the tapes materialized by workers.
+ *
+ * Note that while logtape.c does create an empty leader tape at the end of the
+ * tapeset in the leader case, it can never be written to due to a restriction
+ * in the shared buffile infrastructure.
+ */
+typedef struct TapeShare
+{
+ /*
+ * Currently, all the leader process needs is the location of the
+ * materialized tape's first block.
+ */
+ long firstblocknumber;
+} TapeShare;
+
+/*
+ * prototypes for functions in logtape.c
+ */
+
+extern LogicalTapeSet *LogicalTapeSetCreate(bool preallocate,
+ SharedFileSet *fileset, int worker);
+extern void LogicalTapeClose(LogicalTape *lt);
+extern void LogicalTapeSetClose(LogicalTapeSet *lts);
+extern LogicalTape *LogicalTapeCreate(LogicalTapeSet *lts);
+extern LogicalTape *LogicalTapeImport(LogicalTapeSet *lts, int worker, TapeShare *shared);
+extern void LogicalTapeSetForgetFreeSpace(LogicalTapeSet *lts);
+extern size_t LogicalTapeRead(LogicalTape *lt, void *ptr, size_t size);
+extern void LogicalTapeWrite(LogicalTape *lt, const void *ptr, size_t size);
+extern void LogicalTapeRewindForRead(LogicalTape *lt, size_t buffer_size);
+extern void LogicalTapeFreeze(LogicalTape *lt, TapeShare *share);
+extern size_t LogicalTapeBackspace(LogicalTape *lt, size_t size);
+extern void LogicalTapeSeek(LogicalTape *lt, long blocknum, int offset);
+extern void LogicalTapeTell(LogicalTape *lt, long *blocknum, int *offset);
+extern long LogicalTapeSetBlocks(LogicalTapeSet *lts);
+
+#endif /* LOGTAPE_H */
diff --git a/pgsql/include/server/utils/lsyscache.h b/pgsql/include/server/utils/lsyscache.h
new file mode 100644
index 0000000000000000000000000000000000000000..4f5418b9728fdbb852ed0bc1690b9a80c20a20eb
--- /dev/null
+++ b/pgsql/include/server/utils/lsyscache.h
@@ -0,0 +1,212 @@
+/*-------------------------------------------------------------------------
+ *
+ * lsyscache.h
+ * Convenience routines for common queries in the system catalog cache.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/lsyscache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef LSYSCACHE_H
+#define LSYSCACHE_H
+
+#include "access/attnum.h"
+#include "access/htup.h"
+#include "nodes/pg_list.h"
+
+/* avoid including subscripting.h here */
+struct SubscriptRoutines;
+
+/* Result list element for get_op_btree_interpretation */
+typedef struct OpBtreeInterpretation
+{
+ Oid opfamily_id; /* btree opfamily containing operator */
+ int strategy; /* its strategy number */
+ Oid oplefttype; /* declared left input datatype */
+ Oid oprighttype; /* declared right input datatype */
+} OpBtreeInterpretation;
+
+/* I/O function selector for get_type_io_data */
+typedef enum IOFuncSelector
+{
+ IOFunc_input,
+ IOFunc_output,
+ IOFunc_receive,
+ IOFunc_send
+} IOFuncSelector;
+
+/* Flag bits for get_attstatsslot */
+#define ATTSTATSSLOT_VALUES 0x01
+#define ATTSTATSSLOT_NUMBERS 0x02
+
+/* Result struct for get_attstatsslot */
+typedef struct AttStatsSlot
+{
+ /* Always filled: */
+ Oid staop; /* Actual staop for the found slot */
+ Oid stacoll; /* Actual collation for the found slot */
+ /* Filled if ATTSTATSSLOT_VALUES is specified: */
+ Oid valuetype; /* Actual datatype of the values */
+ Datum *values; /* slot's "values" array, or NULL if none */
+ int nvalues; /* length of values[], or 0 */
+ /* Filled if ATTSTATSSLOT_NUMBERS is specified: */
+ float4 *numbers; /* slot's "numbers" array, or NULL if none */
+ int nnumbers; /* length of numbers[], or 0 */
+
+ /* Remaining fields are private to get_attstatsslot/free_attstatsslot */
+ void *values_arr; /* palloc'd values array, if any */
+ void *numbers_arr; /* palloc'd numbers array, if any */
+} AttStatsSlot;
+
+/* Hook for plugins to get control in get_attavgwidth() */
+typedef int32 (*get_attavgwidth_hook_type) (Oid relid, AttrNumber attnum);
+extern PGDLLIMPORT get_attavgwidth_hook_type get_attavgwidth_hook;
+
+extern bool op_in_opfamily(Oid opno, Oid opfamily);
+extern int get_op_opfamily_strategy(Oid opno, Oid opfamily);
+extern Oid get_op_opfamily_sortfamily(Oid opno, Oid opfamily);
+extern void get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op,
+ int *strategy,
+ Oid *lefttype,
+ Oid *righttype);
+extern Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype,
+ int16 strategy);
+extern bool get_ordering_op_properties(Oid opno,
+ Oid *opfamily, Oid *opcintype, int16 *strategy);
+extern Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse);
+extern Oid get_ordering_op_for_equality_op(Oid opno, bool use_lhs_type);
+extern List *get_mergejoin_opfamilies(Oid opno);
+extern bool get_compatible_hash_operators(Oid opno,
+ Oid *lhs_opno, Oid *rhs_opno);
+extern bool get_op_hash_functions(Oid opno,
+ RegProcedure *lhs_procno, RegProcedure *rhs_procno);
+extern List *get_op_btree_interpretation(Oid opno);
+extern bool equality_ops_are_compatible(Oid opno1, Oid opno2);
+extern bool comparison_ops_are_compatible(Oid opno1, Oid opno2);
+extern Oid get_opfamily_proc(Oid opfamily, Oid lefttype, Oid righttype,
+ int16 procnum);
+extern char *get_attname(Oid relid, AttrNumber attnum, bool missing_ok);
+extern AttrNumber get_attnum(Oid relid, const char *attname);
+extern int get_attstattarget(Oid relid, AttrNumber attnum);
+extern char get_attgenerated(Oid relid, AttrNumber attnum);
+extern Oid get_atttype(Oid relid, AttrNumber attnum);
+extern void get_atttypetypmodcoll(Oid relid, AttrNumber attnum,
+ Oid *typid, int32 *typmod, Oid *collid);
+extern Datum get_attoptions(Oid relid, int16 attnum);
+extern Oid get_cast_oid(Oid sourcetypeid, Oid targettypeid, bool missing_ok);
+extern char *get_collation_name(Oid colloid);
+extern bool get_collation_isdeterministic(Oid colloid);
+extern char *get_constraint_name(Oid conoid);
+extern Oid get_constraint_index(Oid conoid);
+extern char *get_language_name(Oid langoid, bool missing_ok);
+extern Oid get_opclass_family(Oid opclass);
+extern Oid get_opclass_input_type(Oid opclass);
+extern bool get_opclass_opfamily_and_input_type(Oid opclass,
+ Oid *opfamily, Oid *opcintype);
+extern RegProcedure get_opcode(Oid opno);
+extern char *get_opname(Oid opno);
+extern Oid get_op_rettype(Oid opno);
+extern void op_input_types(Oid opno, Oid *lefttype, Oid *righttype);
+extern bool op_mergejoinable(Oid opno, Oid inputtype);
+extern bool op_hashjoinable(Oid opno, Oid inputtype);
+extern bool op_strict(Oid opno);
+extern char op_volatile(Oid opno);
+extern Oid get_commutator(Oid opno);
+extern Oid get_negator(Oid opno);
+extern RegProcedure get_oprrest(Oid opno);
+extern RegProcedure get_oprjoin(Oid opno);
+extern char *get_func_name(Oid funcid);
+extern Oid get_func_namespace(Oid funcid);
+extern Oid get_func_rettype(Oid funcid);
+extern int get_func_nargs(Oid funcid);
+extern Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs);
+extern Oid get_func_variadictype(Oid funcid);
+extern bool get_func_retset(Oid funcid);
+extern bool func_strict(Oid funcid);
+extern char func_volatile(Oid funcid);
+extern char func_parallel(Oid funcid);
+extern char get_func_prokind(Oid funcid);
+extern bool get_func_leakproof(Oid funcid);
+extern RegProcedure get_func_support(Oid funcid);
+extern Oid get_relname_relid(const char *relname, Oid relnamespace);
+extern char *get_rel_name(Oid relid);
+extern Oid get_rel_namespace(Oid relid);
+extern Oid get_rel_type_id(Oid relid);
+extern char get_rel_relkind(Oid relid);
+extern bool get_rel_relispartition(Oid relid);
+extern Oid get_rel_tablespace(Oid relid);
+extern char get_rel_persistence(Oid relid);
+extern Oid get_transform_fromsql(Oid typid, Oid langid, List *trftypes);
+extern Oid get_transform_tosql(Oid typid, Oid langid, List *trftypes);
+extern bool get_typisdefined(Oid typid);
+extern int16 get_typlen(Oid typid);
+extern bool get_typbyval(Oid typid);
+extern void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval);
+extern void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval,
+ char *typalign);
+extern Oid getTypeIOParam(HeapTuple typeTuple);
+extern void get_type_io_data(Oid typid,
+ IOFuncSelector which_func,
+ int16 *typlen,
+ bool *typbyval,
+ char *typalign,
+ char *typdelim,
+ Oid *typioparam,
+ Oid *func);
+extern char get_typstorage(Oid typid);
+extern Node *get_typdefault(Oid typid);
+extern char get_typtype(Oid typid);
+extern bool type_is_rowtype(Oid typid);
+extern bool type_is_enum(Oid typid);
+extern bool type_is_range(Oid typid);
+extern bool type_is_multirange(Oid typid);
+extern void get_type_category_preferred(Oid typid,
+ char *typcategory,
+ bool *typispreferred);
+extern Oid get_typ_typrelid(Oid typid);
+extern Oid get_element_type(Oid typid);
+extern Oid get_array_type(Oid typid);
+extern Oid get_promoted_array_type(Oid typid);
+extern Oid get_base_element_type(Oid typid);
+extern void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam);
+extern void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena);
+extern void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam);
+extern void getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena);
+extern Oid get_typmodin(Oid typid);
+extern Oid get_typcollation(Oid typid);
+extern bool type_is_collatable(Oid typid);
+extern RegProcedure get_typsubscript(Oid typid, Oid *typelemp);
+extern const struct SubscriptRoutines *getSubscriptingRoutines(Oid typid,
+ Oid *typelemp);
+extern Oid getBaseType(Oid typid);
+extern Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod);
+extern int32 get_typavgwidth(Oid typid, int32 typmod);
+extern int32 get_attavgwidth(Oid relid, AttrNumber attnum);
+extern bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple,
+ int reqkind, Oid reqop, int flags);
+extern void free_attstatsslot(AttStatsSlot *sslot);
+extern char *get_namespace_name(Oid nspid);
+extern char *get_namespace_name_or_temp(Oid nspid);
+extern Oid get_range_subtype(Oid rangeOid);
+extern Oid get_range_collation(Oid rangeOid);
+extern Oid get_range_multirange(Oid rangeOid);
+extern Oid get_multirange_range(Oid multirangeOid);
+extern Oid get_index_column_opclass(Oid index_oid, int attno);
+extern bool get_index_isreplident(Oid index_oid);
+extern bool get_index_isvalid(Oid index_oid);
+extern bool get_index_isclustered(Oid index_oid);
+extern Oid get_publication_oid(const char *pubname, bool missing_ok);
+extern char *get_publication_name(Oid pubid, bool missing_ok);
+extern Oid get_subscription_oid(const char *subname, bool missing_ok);
+extern char *get_subscription_name(Oid subid, bool missing_ok);
+
+#define type_is_array(typid) (get_element_type(typid) != InvalidOid)
+/* type_is_array_domain accepts both plain arrays and domains over arrays */
+#define type_is_array_domain(typid) (get_base_element_type(typid) != InvalidOid)
+
+#define TypeIsToastable(typid) (get_typstorage(typid) != TYPSTORAGE_PLAIN)
+
+#endif /* LSYSCACHE_H */
diff --git a/pgsql/include/server/utils/memdebug.h b/pgsql/include/server/utils/memdebug.h
new file mode 100644
index 0000000000000000000000000000000000000000..804ed1fbc079a25f0434e502d881e2ae4770b91a
--- /dev/null
+++ b/pgsql/include/server/utils/memdebug.h
@@ -0,0 +1,82 @@
+/*-------------------------------------------------------------------------
+ *
+ * memdebug.h
+ * Memory debugging support.
+ *
+ * Currently, this file either wraps or substitutes
+ * empty definitions for Valgrind client request macros we use.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/memdebug.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MEMDEBUG_H
+#define MEMDEBUG_H
+
+#ifdef USE_VALGRIND
+#include
+#else
+#define VALGRIND_CHECK_MEM_IS_DEFINED(addr, size) do {} while (0)
+#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed) do {} while (0)
+#define VALGRIND_DESTROY_MEMPOOL(context) do {} while (0)
+#define VALGRIND_MAKE_MEM_DEFINED(addr, size) do {} while (0)
+#define VALGRIND_MAKE_MEM_NOACCESS(addr, size) do {} while (0)
+#define VALGRIND_MAKE_MEM_UNDEFINED(addr, size) do {} while (0)
+#define VALGRIND_MEMPOOL_ALLOC(context, addr, size) do {} while (0)
+#define VALGRIND_MEMPOOL_FREE(context, addr) do {} while (0)
+#define VALGRIND_MEMPOOL_CHANGE(context, optr, nptr, size) do {} while (0)
+#endif
+
+
+#ifdef CLOBBER_FREED_MEMORY
+
+/* Wipe freed memory for debugging purposes */
+static inline void
+wipe_mem(void *ptr, size_t size)
+{
+ VALGRIND_MAKE_MEM_UNDEFINED(ptr, size);
+ memset(ptr, 0x7F, size);
+ VALGRIND_MAKE_MEM_NOACCESS(ptr, size);
+}
+
+#endif /* CLOBBER_FREED_MEMORY */
+
+#ifdef MEMORY_CONTEXT_CHECKING
+
+static inline void
+set_sentinel(void *base, Size offset)
+{
+ char *ptr = (char *) base + offset;
+
+ VALGRIND_MAKE_MEM_UNDEFINED(ptr, 1);
+ *ptr = 0x7E;
+ VALGRIND_MAKE_MEM_NOACCESS(ptr, 1);
+}
+
+static inline bool
+sentinel_ok(const void *base, Size offset)
+{
+ const char *ptr = (const char *) base + offset;
+ bool ret;
+
+ VALGRIND_MAKE_MEM_DEFINED(ptr, 1);
+ ret = *ptr == 0x7E;
+ VALGRIND_MAKE_MEM_NOACCESS(ptr, 1);
+
+ return ret;
+}
+
+#endif /* MEMORY_CONTEXT_CHECKING */
+
+#ifdef RANDOMIZE_ALLOCATED_MEMORY
+
+void randomize_mem(char *ptr, size_t size);
+
+#endif /* RANDOMIZE_ALLOCATED_MEMORY */
+
+
+#endif /* MEMDEBUG_H */
diff --git a/pgsql/include/server/utils/memutils.h b/pgsql/include/server/utils/memutils.h
new file mode 100644
index 0000000000000000000000000000000000000000..21640d62a647d23a4bfd3f12922b615d9cc03e97
--- /dev/null
+++ b/pgsql/include/server/utils/memutils.h
@@ -0,0 +1,185 @@
+/*-------------------------------------------------------------------------
+ *
+ * memutils.h
+ * This file contains declarations for memory allocation utility
+ * functions. These are functions that are not quite widely used
+ * enough to justify going in utils/palloc.h, but are still part
+ * of the API of the memory management subsystem.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/memutils.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MEMUTILS_H
+#define MEMUTILS_H
+
+#include "nodes/memnodes.h"
+
+
+/*
+ * MaxAllocSize, MaxAllocHugeSize
+ * Quasi-arbitrary limits on size of allocations.
+ *
+ * Note:
+ * There is no guarantee that smaller allocations will succeed, but
+ * larger requests will be summarily denied.
+ *
+ * palloc() enforces MaxAllocSize, chosen to correspond to the limiting size
+ * of varlena objects under TOAST. See VARSIZE_4B() and related macros in
+ * postgres.h. Many datatypes assume that any allocatable size can be
+ * represented in a varlena header. This limit also permits a caller to use
+ * an "int" variable for an index into or length of an allocation. Callers
+ * careful to avoid these hazards can access the higher limit with
+ * MemoryContextAllocHuge(). Both limits permit code to assume that it may
+ * compute twice an allocation's size without overflow.
+ */
+#define MaxAllocSize ((Size) 0x3fffffff) /* 1 gigabyte - 1 */
+
+#define AllocSizeIsValid(size) ((Size) (size) <= MaxAllocSize)
+
+/* Must be less than SIZE_MAX */
+#define MaxAllocHugeSize (SIZE_MAX / 2)
+
+#define InvalidAllocSize SIZE_MAX
+
+#define AllocHugeSizeIsValid(size) ((Size) (size) <= MaxAllocHugeSize)
+
+
+/*
+ * Standard top-level memory contexts.
+ *
+ * Only TopMemoryContext and ErrorContext are initialized by
+ * MemoryContextInit() itself.
+ */
+extern PGDLLIMPORT MemoryContext TopMemoryContext;
+extern PGDLLIMPORT MemoryContext ErrorContext;
+extern PGDLLIMPORT MemoryContext PostmasterContext;
+extern PGDLLIMPORT MemoryContext CacheMemoryContext;
+extern PGDLLIMPORT MemoryContext MessageContext;
+extern PGDLLIMPORT MemoryContext TopTransactionContext;
+extern PGDLLIMPORT MemoryContext CurTransactionContext;
+
+/* This is a transient link to the active portal's memory context: */
+extern PGDLLIMPORT MemoryContext PortalContext;
+
+/* Backwards compatibility macro */
+#define MemoryContextResetAndDeleteChildren(ctx) MemoryContextReset(ctx)
+
+
+/*
+ * Memory-context-type-independent functions in mcxt.c
+ */
+extern void MemoryContextInit(void);
+extern void MemoryContextReset(MemoryContext context);
+extern void MemoryContextDelete(MemoryContext context);
+extern void MemoryContextResetOnly(MemoryContext context);
+extern void MemoryContextResetChildren(MemoryContext context);
+extern void MemoryContextDeleteChildren(MemoryContext context);
+extern void MemoryContextSetIdentifier(MemoryContext context, const char *id);
+extern void MemoryContextSetParent(MemoryContext context,
+ MemoryContext new_parent);
+extern MemoryContext GetMemoryChunkContext(void *pointer);
+extern Size GetMemoryChunkSpace(void *pointer);
+extern MemoryContext MemoryContextGetParent(MemoryContext context);
+extern bool MemoryContextIsEmpty(MemoryContext context);
+extern Size MemoryContextMemAllocated(MemoryContext context, bool recurse);
+extern void MemoryContextStats(MemoryContext context);
+extern void MemoryContextStatsDetail(MemoryContext context, int max_children,
+ bool print_to_stderr);
+extern void MemoryContextAllowInCriticalSection(MemoryContext context,
+ bool allow);
+
+#ifdef MEMORY_CONTEXT_CHECKING
+extern void MemoryContextCheck(MemoryContext context);
+#endif
+
+/* Handy macro for copying and assigning context ID ... but note double eval */
+#define MemoryContextCopyAndSetIdentifier(cxt, id) \
+ MemoryContextSetIdentifier(cxt, MemoryContextStrdup(cxt, id))
+
+extern void HandleLogMemoryContextInterrupt(void);
+extern void ProcessLogMemoryContextInterrupt(void);
+
+/*
+ * Memory-context-type-specific functions
+ */
+
+/* aset.c */
+extern MemoryContext AllocSetContextCreateInternal(MemoryContext parent,
+ const char *name,
+ Size minContextSize,
+ Size initBlockSize,
+ Size maxBlockSize);
+
+/*
+ * This wrapper macro exists to check for non-constant strings used as context
+ * names; that's no longer supported. (Use MemoryContextSetIdentifier if you
+ * want to provide a variable identifier.)
+ */
+#ifdef HAVE__BUILTIN_CONSTANT_P
+#define AllocSetContextCreate(parent, name, ...) \
+ (StaticAssertExpr(__builtin_constant_p(name), \
+ "memory context names must be constant strings"), \
+ AllocSetContextCreateInternal(parent, name, __VA_ARGS__))
+#else
+#define AllocSetContextCreate \
+ AllocSetContextCreateInternal
+#endif
+
+/* slab.c */
+extern MemoryContext SlabContextCreate(MemoryContext parent,
+ const char *name,
+ Size blockSize,
+ Size chunkSize);
+
+/* generation.c */
+extern MemoryContext GenerationContextCreate(MemoryContext parent,
+ const char *name,
+ Size minContextSize,
+ Size initBlockSize,
+ Size maxBlockSize);
+
+/*
+ * Recommended default alloc parameters, suitable for "ordinary" contexts
+ * that might hold quite a lot of data.
+ */
+#define ALLOCSET_DEFAULT_MINSIZE 0
+#define ALLOCSET_DEFAULT_INITSIZE (8 * 1024)
+#define ALLOCSET_DEFAULT_MAXSIZE (8 * 1024 * 1024)
+#define ALLOCSET_DEFAULT_SIZES \
+ ALLOCSET_DEFAULT_MINSIZE, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE
+
+/*
+ * Recommended alloc parameters for "small" contexts that are never expected
+ * to contain much data (for example, a context to contain a query plan).
+ */
+#define ALLOCSET_SMALL_MINSIZE 0
+#define ALLOCSET_SMALL_INITSIZE (1 * 1024)
+#define ALLOCSET_SMALL_MAXSIZE (8 * 1024)
+#define ALLOCSET_SMALL_SIZES \
+ ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_SMALL_MAXSIZE
+
+/*
+ * Recommended alloc parameters for contexts that should start out small,
+ * but might sometimes grow big.
+ */
+#define ALLOCSET_START_SMALL_SIZES \
+ ALLOCSET_SMALL_MINSIZE, ALLOCSET_SMALL_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE
+
+
+/*
+ * Threshold above which a request in an AllocSet context is certain to be
+ * allocated separately (and thereby have constant allocation overhead).
+ * Few callers should be interested in this, but tuplesort/tuplestore need
+ * to know it.
+ */
+#define ALLOCSET_SEPARATE_THRESHOLD 8192
+
+#define SLAB_DEFAULT_BLOCK_SIZE (8 * 1024)
+#define SLAB_LARGE_BLOCK_SIZE (8 * 1024 * 1024)
+
+#endif /* MEMUTILS_H */
diff --git a/pgsql/include/server/utils/memutils_internal.h b/pgsql/include/server/utils/memutils_internal.h
new file mode 100644
index 0000000000000000000000000000000000000000..2d107bbf9d4411b9976897f7eb8478534d97f0df
--- /dev/null
+++ b/pgsql/include/server/utils/memutils_internal.h
@@ -0,0 +1,136 @@
+/*-------------------------------------------------------------------------
+ *
+ * memutils_internal.h
+ * This file contains declarations for memory allocation utility
+ * functions for internal use.
+ *
+ *
+ * Portions Copyright (c) 2022-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/memutils_internal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef MEMUTILS_INTERNAL_H
+#define MEMUTILS_INTERNAL_H
+
+#include "utils/memutils.h"
+
+/* These functions implement the MemoryContext API for AllocSet context. */
+extern void *AllocSetAlloc(MemoryContext context, Size size);
+extern void AllocSetFree(void *pointer);
+extern void *AllocSetRealloc(void *pointer, Size size);
+extern void AllocSetReset(MemoryContext context);
+extern void AllocSetDelete(MemoryContext context);
+extern MemoryContext AllocSetGetChunkContext(void *pointer);
+extern Size AllocSetGetChunkSpace(void *pointer);
+extern bool AllocSetIsEmpty(MemoryContext context);
+extern void AllocSetStats(MemoryContext context,
+ MemoryStatsPrintFunc printfunc, void *passthru,
+ MemoryContextCounters *totals,
+ bool print_to_stderr);
+#ifdef MEMORY_CONTEXT_CHECKING
+extern void AllocSetCheck(MemoryContext context);
+#endif
+
+/* These functions implement the MemoryContext API for Generation context. */
+extern void *GenerationAlloc(MemoryContext context, Size size);
+extern void GenerationFree(void *pointer);
+extern void *GenerationRealloc(void *pointer, Size size);
+extern void GenerationReset(MemoryContext context);
+extern void GenerationDelete(MemoryContext context);
+extern MemoryContext GenerationGetChunkContext(void *pointer);
+extern Size GenerationGetChunkSpace(void *pointer);
+extern bool GenerationIsEmpty(MemoryContext context);
+extern void GenerationStats(MemoryContext context,
+ MemoryStatsPrintFunc printfunc, void *passthru,
+ MemoryContextCounters *totals,
+ bool print_to_stderr);
+#ifdef MEMORY_CONTEXT_CHECKING
+extern void GenerationCheck(MemoryContext context);
+#endif
+
+
+/* These functions implement the MemoryContext API for Slab context. */
+extern void *SlabAlloc(MemoryContext context, Size size);
+extern void SlabFree(void *pointer);
+extern void *SlabRealloc(void *pointer, Size size);
+extern void SlabReset(MemoryContext context);
+extern void SlabDelete(MemoryContext context);
+extern MemoryContext SlabGetChunkContext(void *pointer);
+extern Size SlabGetChunkSpace(void *pointer);
+extern bool SlabIsEmpty(MemoryContext context);
+extern void SlabStats(MemoryContext context,
+ MemoryStatsPrintFunc printfunc, void *passthru,
+ MemoryContextCounters *totals,
+ bool print_to_stderr);
+#ifdef MEMORY_CONTEXT_CHECKING
+extern void SlabCheck(MemoryContext context);
+#endif
+
+/*
+ * These functions support the implementation of palloc_aligned() and are not
+ * part of a fully-fledged MemoryContext type.
+ */
+extern void AlignedAllocFree(void *pointer);
+extern void *AlignedAllocRealloc(void *pointer, Size size);
+extern MemoryContext AlignedAllocGetChunkContext(void *pointer);
+extern Size AlignedAllocGetChunkSpace(void *pointer);
+
+/*
+ * How many extra bytes do we need to request in order to ensure that we can
+ * align a pointer to 'alignto'. Since palloc'd pointers are already aligned
+ * to MAXIMUM_ALIGNOF we can subtract that amount. We also need to make sure
+ * there is enough space for the redirection MemoryChunk.
+ */
+#define PallocAlignedExtraBytes(alignto) \
+ ((alignto) + (sizeof(MemoryChunk) - MAXIMUM_ALIGNOF))
+
+/*
+ * MemoryContextMethodID
+ * A unique identifier for each MemoryContext implementation which
+ * indicates the index into the mcxt_methods[] array. See mcxt.c.
+ *
+ * For robust error detection, ensure that MemoryContextMethodID has a value
+ * for each possible bit-pattern of MEMORY_CONTEXT_METHODID_MASK, and make
+ * dummy entries for unused IDs in the mcxt_methods[] array. We also try
+ * to avoid using bit-patterns as valid IDs if they are likely to occur in
+ * garbage data, or if they could falsely match on chunks that are really from
+ * malloc not palloc. (We can't tell that for most malloc implementations,
+ * but it happens that glibc stores flag bits in the same place where we put
+ * the MemoryContextMethodID, so the possible values are predictable for it.)
+ */
+typedef enum MemoryContextMethodID
+{
+ MCTX_UNUSED1_ID, /* 000 occurs in never-used memory */
+ MCTX_UNUSED2_ID, /* glibc malloc'd chunks usually match 001 */
+ MCTX_UNUSED3_ID, /* glibc malloc'd chunks > 128kB match 010 */
+ MCTX_ASET_ID,
+ MCTX_GENERATION_ID,
+ MCTX_SLAB_ID,
+ MCTX_ALIGNED_REDIRECT_ID,
+ MCTX_UNUSED4_ID /* 111 occurs in wipe_mem'd memory */
+} MemoryContextMethodID;
+
+/*
+ * The number of bits that 8-byte memory chunk headers can use to encode the
+ * MemoryContextMethodID.
+ */
+#define MEMORY_CONTEXT_METHODID_BITS 3
+#define MEMORY_CONTEXT_METHODID_MASK \
+ ((((uint64) 1) << MEMORY_CONTEXT_METHODID_BITS) - 1)
+
+/*
+ * This routine handles the context-type-independent part of memory
+ * context creation. It's intended to be called from context-type-
+ * specific creation routines, and noplace else.
+ */
+extern void MemoryContextCreate(MemoryContext node,
+ NodeTag tag,
+ MemoryContextMethodID method_id,
+ MemoryContext parent,
+ const char *name);
+
+#endif /* MEMUTILS_INTERNAL_H */
diff --git a/pgsql/include/server/utils/memutils_memorychunk.h b/pgsql/include/server/utils/memutils_memorychunk.h
new file mode 100644
index 0000000000000000000000000000000000000000..ffa91131c88e2e3aad6fd531b187e938b7cf519a
--- /dev/null
+++ b/pgsql/include/server/utils/memutils_memorychunk.h
@@ -0,0 +1,237 @@
+/*-------------------------------------------------------------------------
+ *
+ * memutils_memorychunk.h
+ * Here we define a struct named MemoryChunk which implementations of
+ * MemoryContexts may use as a header for chunks of memory they allocate.
+ *
+ * MemoryChunk provides a lightweight header that a MemoryContext can use to
+ * store a reference back to the block which the given chunk is allocated on
+ * and also an additional 30-bits to store another value such as the size of
+ * the allocated chunk.
+ *
+ * Although MemoryChunks are used by each of our MemoryContexts, future
+ * implementations may choose to implement their own method for storing chunk
+ * headers. The only requirement is that the header ends with an 8-byte value
+ * which the least significant 3-bits of are set to the MemoryContextMethodID
+ * of the given context.
+ *
+ * By default, a MemoryChunk is 8 bytes in size, however, when
+ * MEMORY_CONTEXT_CHECKING is defined the header becomes 16 bytes in size due
+ * to the additional requested_size field. The MemoryContext may use this
+ * field for whatever they wish, but it is intended to be used for additional
+ * checks which are only done in MEMORY_CONTEXT_CHECKING builds.
+ *
+ * The MemoryChunk contains a uint64 field named 'hdrmask'. This field is
+ * used to encode 4 separate pieces of information. Starting with the least
+ * significant bits of 'hdrmask', the bit space is reserved as follows:
+ *
+ * 1. 3-bits to indicate the MemoryContextMethodID as defined by
+ * MEMORY_CONTEXT_METHODID_MASK
+ * 2. 1-bit to denote an "external" chunk (see below)
+ * 3. 30-bits reserved for the MemoryContext to use for anything it
+ * requires. Most MemoryContext likely want to store the size of the
+ * chunk here.
+ * 4. 30-bits for the number of bytes that must be subtracted from the chunk
+ * to obtain the address of the block that the chunk is stored on.
+ *
+ * In some cases, for example when memory allocations become large, it's
+ * possible fields 3 and 4 above are not large enough to store the values
+ * required for the chunk. In this case, the MemoryContext can choose to mark
+ * the chunk as "external" by calling the MemoryChunkSetHdrMaskExternal()
+ * function. When this is done, fields 3 and 4 are unavailable for use by the
+ * MemoryContext and it's up to the MemoryContext itself to devise its own
+ * method for getting the reference to the block.
+ *
+ * Interface:
+ *
+ * MemoryChunkSetHdrMask:
+ * Used to set up a non-external MemoryChunk.
+ *
+ * MemoryChunkSetHdrMaskExternal:
+ * Used to set up an externally managed MemoryChunk.
+ *
+ * MemoryChunkIsExternal:
+ * Determine if the given MemoryChunk is externally managed, i.e.
+ * MemoryChunkSetHdrMaskExternal() was called on the chunk.
+ *
+ * MemoryChunkGetValue:
+ * For non-external chunks, return the stored 30-bit value as it was set
+ * in the call to MemoryChunkSetHdrMask().
+ *
+ * MemoryChunkGetBlock:
+ * For non-external chunks, return a pointer to the block as it was set
+ * in the call to MemoryChunkSetHdrMask().
+ *
+ * Also exports:
+ * MEMORYCHUNK_MAX_VALUE
+ * MEMORYCHUNK_MAX_BLOCKOFFSET
+ * PointerGetMemoryChunk
+ * MemoryChunkGetPointer
+ *
+ * Portions Copyright (c) 2022-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/memutils_memorychunk.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef MEMUTILS_MEMORYCHUNK_H
+#define MEMUTILS_MEMORYCHUNK_H
+
+#include "utils/memutils_internal.h"
+
+ /*
+ * The maximum allowed value that MemoryContexts can store in the value
+ * field. Must be 1 less than a power of 2.
+ */
+#define MEMORYCHUNK_MAX_VALUE UINT64CONST(0x3FFFFFFF)
+
+/*
+ * The maximum distance in bytes that a MemoryChunk can be offset from the
+ * block that is storing the chunk. Must be 1 less than a power of 2.
+ */
+#define MEMORYCHUNK_MAX_BLOCKOFFSET UINT64CONST(0x3FFFFFFF)
+
+/* define the least significant base-0 bit of each portion of the hdrmask */
+#define MEMORYCHUNK_EXTERNAL_BASEBIT MEMORY_CONTEXT_METHODID_BITS
+#define MEMORYCHUNK_VALUE_BASEBIT (MEMORYCHUNK_EXTERNAL_BASEBIT + 1)
+#define MEMORYCHUNK_BLOCKOFFSET_BASEBIT (MEMORYCHUNK_VALUE_BASEBIT + 30)
+
+/*
+ * A magic number for storing in the free bits of an external chunk. This
+ * must mask out the bits used for storing the MemoryContextMethodID and the
+ * external bit.
+ */
+#define MEMORYCHUNK_MAGIC (UINT64CONST(0xB1A8DB858EB6EFBA) >> \
+ MEMORYCHUNK_VALUE_BASEBIT << \
+ MEMORYCHUNK_VALUE_BASEBIT)
+
+typedef struct MemoryChunk
+{
+#ifdef MEMORY_CONTEXT_CHECKING
+ Size requested_size;
+#endif
+
+ /* bitfield for storing details about the chunk */
+ uint64 hdrmask; /* must be last */
+} MemoryChunk;
+
+/* Get the MemoryChunk from the pointer */
+#define PointerGetMemoryChunk(p) \
+ ((MemoryChunk *) ((char *) (p) - sizeof(MemoryChunk)))
+/* Get the pointer from the MemoryChunk */
+#define MemoryChunkGetPointer(c) \
+ ((void *) ((char *) (c) + sizeof(MemoryChunk)))
+
+/* private macros for making the inline functions below more simple */
+#define HdrMaskIsExternal(hdrmask) \
+ ((hdrmask) & (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT))
+#define HdrMaskGetValue(hdrmask) \
+ (((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT) & MEMORYCHUNK_MAX_VALUE)
+
+/*
+ * We should have used up all the bits here, so the compiler is likely to
+ * optimize out the & MEMORYCHUNK_MAX_BLOCKOFFSET.
+ */
+#define HdrMaskBlockOffset(hdrmask) \
+ (((hdrmask) >> MEMORYCHUNK_BLOCKOFFSET_BASEBIT) & MEMORYCHUNK_MAX_BLOCKOFFSET)
+
+/* For external chunks only, check the magic number matches */
+#define HdrMaskCheckMagic(hdrmask) \
+ (MEMORYCHUNK_MAGIC == \
+ ((hdrmask) >> MEMORYCHUNK_VALUE_BASEBIT << MEMORYCHUNK_VALUE_BASEBIT))
+/*
+ * MemoryChunkSetHdrMask
+ * Store the given 'block', 'chunk_size' and 'methodid' in the given
+ * MemoryChunk.
+ *
+ * The number of bytes between 'block' and 'chunk' must be <=
+ * MEMORYCHUNK_MAX_BLOCKOFFSET.
+ * 'value' must be <= MEMORYCHUNK_MAX_VALUE.
+ */
+static inline void
+MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block,
+ Size value, MemoryContextMethodID methodid)
+{
+ Size blockoffset = (char *) chunk - (char *) block;
+
+ Assert((char *) chunk >= (char *) block);
+ Assert(blockoffset <= MEMORYCHUNK_MAX_BLOCKOFFSET);
+ Assert(value <= MEMORYCHUNK_MAX_VALUE);
+ Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK);
+
+ chunk->hdrmask = (((uint64) blockoffset) << MEMORYCHUNK_BLOCKOFFSET_BASEBIT) |
+ (((uint64) value) << MEMORYCHUNK_VALUE_BASEBIT) |
+ methodid;
+}
+
+/*
+ * MemoryChunkSetHdrMaskExternal
+ * Set 'chunk' as an externally managed chunk. Here we only record the
+ * MemoryContextMethodID and set the external chunk bit.
+ */
+static inline void
+MemoryChunkSetHdrMaskExternal(MemoryChunk *chunk,
+ MemoryContextMethodID methodid)
+{
+ Assert((int) methodid <= MEMORY_CONTEXT_METHODID_MASK);
+
+ chunk->hdrmask = MEMORYCHUNK_MAGIC | (((uint64) 1) << MEMORYCHUNK_EXTERNAL_BASEBIT) |
+ methodid;
+}
+
+/*
+ * MemoryChunkIsExternal
+ * Return true if 'chunk' is marked as external.
+ */
+static inline bool
+MemoryChunkIsExternal(MemoryChunk *chunk)
+{
+ /*
+ * External chunks should always store MEMORYCHUNK_MAGIC in the upper
+ * portion of the hdrmask, check that nothing has stomped on that.
+ */
+ Assert(!HdrMaskIsExternal(chunk->hdrmask) ||
+ HdrMaskCheckMagic(chunk->hdrmask));
+
+ return HdrMaskIsExternal(chunk->hdrmask);
+}
+
+/*
+ * MemoryChunkGetValue
+ * For non-external chunks, returns the value field as it was set in
+ * MemoryChunkSetHdrMask.
+ */
+static inline Size
+MemoryChunkGetValue(MemoryChunk *chunk)
+{
+ Assert(!HdrMaskIsExternal(chunk->hdrmask));
+
+ return HdrMaskGetValue(chunk->hdrmask);
+}
+
+/*
+ * MemoryChunkGetBlock
+ * For non-external chunks, returns the pointer to the block as was set
+ * in MemoryChunkSetHdrMask.
+ */
+static inline void *
+MemoryChunkGetBlock(MemoryChunk *chunk)
+{
+ Assert(!HdrMaskIsExternal(chunk->hdrmask));
+
+ return (void *) ((char *) chunk - HdrMaskBlockOffset(chunk->hdrmask));
+}
+
+/* cleanup all internal definitions */
+#undef MEMORYCHUNK_EXTERNAL_BASEBIT
+#undef MEMORYCHUNK_VALUE_BASEBIT
+#undef MEMORYCHUNK_BLOCKOFFSET_BASEBIT
+#undef MEMORYCHUNK_MAGIC
+#undef HdrMaskIsExternal
+#undef HdrMaskGetValue
+#undef HdrMaskBlockOffset
+#undef HdrMaskCheckMagic
+
+#endif /* MEMUTILS_MEMORYCHUNK_H */
diff --git a/pgsql/include/server/utils/multirangetypes.h b/pgsql/include/server/utils/multirangetypes.h
new file mode 100644
index 0000000000000000000000000000000000000000..7663d35d56a6dd3e84ae05e4da37f06cbff42795
--- /dev/null
+++ b/pgsql/include/server/utils/multirangetypes.h
@@ -0,0 +1,150 @@
+/*-------------------------------------------------------------------------
+ *
+ * multirangetypes.h
+ * Declarations for Postgres multirange types.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/multirangetypes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef MULTIRANGETYPES_H
+#define MULTIRANGETYPES_H
+
+#include "utils/rangetypes.h"
+#include "utils/typcache.h"
+
+
+/*
+ * Multiranges are varlena objects, so must meet the varlena convention that
+ * the first int32 of the object contains the total object size in bytes.
+ * Be sure to use VARSIZE() and SET_VARSIZE() to access it, though!
+ */
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ Oid multirangetypid; /* multirange type's own OID */
+ uint32 rangeCount; /* the number of ranges */
+
+ /*
+ * Following the count are the range objects themselves, as ShortRangeType
+ * structs. Note that ranges are varlena too, depending on whether they
+ * have lower/upper bounds and because even their base types can be
+ * varlena. So we can't really index into this list.
+ */
+} MultirangeType;
+
+/* Use these macros in preference to accessing these fields directly */
+#define MultirangeTypeGetOid(mr) ((mr)->multirangetypid)
+#define MultirangeIsEmpty(mr) ((mr)->rangeCount == 0)
+
+/*
+ * fmgr functions for multirange type objects
+ */
+static inline MultirangeType *
+DatumGetMultirangeTypeP(Datum X)
+{
+ return (MultirangeType *) PG_DETOAST_DATUM(X);
+}
+
+static inline MultirangeType *
+DatumGetMultirangeTypePCopy(Datum X)
+{
+ return (MultirangeType *) PG_DETOAST_DATUM_COPY(X);
+}
+
+static inline Datum
+MultirangeTypePGetDatum(const MultirangeType *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_MULTIRANGE_P(n) DatumGetMultirangeTypeP(PG_GETARG_DATUM(n))
+#define PG_GETARG_MULTIRANGE_P_COPY(n) DatumGetMultirangeTypePCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_MULTIRANGE_P(x) return MultirangeTypePGetDatum(x)
+
+/*
+ * prototypes for functions defined in multirangetypes.c
+ */
+
+/* internal versions of the above */
+extern bool multirange_eq_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr1,
+ const MultirangeType *mr2);
+extern bool multirange_ne_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr1,
+ const MultirangeType *mr2);
+extern bool multirange_contains_elem_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr,
+ Datum val);
+extern bool multirange_contains_range_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr,
+ const RangeType *r);
+extern bool range_contains_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool multirange_contains_multirange_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr1,
+ const MultirangeType *mr2);
+extern bool range_overlaps_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool multirange_overlaps_multirange_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr1,
+ const MultirangeType *mr2);
+extern bool range_overleft_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool range_overright_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool range_before_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool range_after_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool range_adjacent_multirange_internal(TypeCacheEntry *rangetyp,
+ const RangeType *r,
+ const MultirangeType *mr);
+extern bool multirange_before_multirange_internal(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr1,
+ const MultirangeType *mr2);
+extern MultirangeType *multirange_minus_internal(Oid mltrngtypoid,
+ TypeCacheEntry *rangetyp,
+ int32 range_count1,
+ RangeType **ranges1,
+ int32 range_count2,
+ RangeType **ranges2);
+extern MultirangeType *multirange_intersect_internal(Oid mltrngtypoid,
+ TypeCacheEntry *rangetyp,
+ int32 range_count1,
+ RangeType **ranges1,
+ int32 range_count2,
+ RangeType **ranges2);
+
+/* assorted support functions */
+extern TypeCacheEntry *multirange_get_typcache(FunctionCallInfo fcinfo,
+ Oid mltrngtypid);
+extern void multirange_deserialize(TypeCacheEntry *rangetyp,
+ const MultirangeType *multirange,
+ int32 *range_count,
+ RangeType ***ranges);
+extern MultirangeType *make_multirange(Oid mltrngtypoid,
+ TypeCacheEntry *rangetyp,
+ int32 range_count, RangeType **ranges);
+extern MultirangeType *make_empty_multirange(Oid mltrngtypoid,
+ TypeCacheEntry *rangetyp);
+extern void multirange_get_bounds(TypeCacheEntry *rangetyp,
+ const MultirangeType *multirange,
+ uint32 i,
+ RangeBound *lower, RangeBound *upper);
+extern RangeType *multirange_get_range(TypeCacheEntry *rangetyp,
+ const MultirangeType *multirange, int i);
+extern RangeType *multirange_get_union_range(TypeCacheEntry *rangetyp,
+ const MultirangeType *mr);
+
+#endif /* MULTIRANGETYPES_H */
diff --git a/pgsql/include/server/utils/numeric.h b/pgsql/include/server/utils/numeric.h
new file mode 100644
index 0000000000000000000000000000000000000000..08e4f8c217de7221ad8da8d0f156a9f2e03b9c65
--- /dev/null
+++ b/pgsql/include/server/utils/numeric.h
@@ -0,0 +1,105 @@
+/*-------------------------------------------------------------------------
+ *
+ * numeric.h
+ * Definitions for the exact numeric data type of Postgres
+ *
+ * Original coding 1998, Jan Wieck. Heavily revised 2003, Tom Lane.
+ *
+ * Copyright (c) 1998-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/numeric.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef _PG_NUMERIC_H_
+#define _PG_NUMERIC_H_
+
+#include "fmgr.h"
+
+/*
+ * Limits on the precision and scale specifiable in a NUMERIC typmod. The
+ * precision is strictly positive, but the scale may be positive or negative.
+ * A negative scale implies rounding before the decimal point.
+ *
+ * Note that the minimum display scale defined below is zero --- we always
+ * display all digits before the decimal point, even when the scale is
+ * negative.
+ *
+ * Note that the implementation limits on the precision and display scale of a
+ * numeric value are much larger --- beware of what you use these for!
+ */
+#define NUMERIC_MAX_PRECISION 1000
+
+#define NUMERIC_MIN_SCALE (-1000)
+#define NUMERIC_MAX_SCALE 1000
+
+/*
+ * Internal limits on the scales chosen for calculation results
+ */
+#define NUMERIC_MAX_DISPLAY_SCALE NUMERIC_MAX_PRECISION
+#define NUMERIC_MIN_DISPLAY_SCALE 0
+
+#define NUMERIC_MAX_RESULT_SCALE (NUMERIC_MAX_PRECISION * 2)
+
+/*
+ * For inherently inexact calculations such as division and square root,
+ * we try to get at least this many significant digits; the idea is to
+ * deliver a result no worse than float8 would.
+ */
+#define NUMERIC_MIN_SIG_DIGITS 16
+
+/* The actual contents of Numeric are private to numeric.c */
+struct NumericData;
+typedef struct NumericData *Numeric;
+
+/*
+ * fmgr interface macros
+ */
+
+static inline Numeric
+DatumGetNumeric(Datum X)
+{
+ return (Numeric) PG_DETOAST_DATUM(X);
+}
+
+static inline Numeric
+DatumGetNumericCopy(Datum X)
+{
+ return (Numeric) PG_DETOAST_DATUM_COPY(X);
+}
+
+static inline Datum
+NumericGetDatum(Numeric X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_NUMERIC(n) DatumGetNumeric(PG_GETARG_DATUM(n))
+#define PG_GETARG_NUMERIC_COPY(n) DatumGetNumericCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_NUMERIC(x) return NumericGetDatum(x)
+
+/*
+ * Utility functions in numeric.c
+ */
+extern bool numeric_is_nan(Numeric num);
+extern bool numeric_is_inf(Numeric num);
+extern int32 numeric_maximum_size(int32 typmod);
+extern char *numeric_out_sci(Numeric num, int scale);
+extern char *numeric_normalize(Numeric num);
+
+extern Numeric int64_to_numeric(int64 val);
+extern Numeric int64_div_fast_to_numeric(int64 val1, int log10val2);
+
+extern Numeric numeric_add_opt_error(Numeric num1, Numeric num2,
+ bool *have_error);
+extern Numeric numeric_sub_opt_error(Numeric num1, Numeric num2,
+ bool *have_error);
+extern Numeric numeric_mul_opt_error(Numeric num1, Numeric num2,
+ bool *have_error);
+extern Numeric numeric_div_opt_error(Numeric num1, Numeric num2,
+ bool *have_error);
+extern Numeric numeric_mod_opt_error(Numeric num1, Numeric num2,
+ bool *have_error);
+extern int32 numeric_int4_opt_error(Numeric num, bool *have_error);
+
+#endif /* _PG_NUMERIC_H_ */
diff --git a/pgsql/include/server/utils/old_snapshot.h b/pgsql/include/server/utils/old_snapshot.h
new file mode 100644
index 0000000000000000000000000000000000000000..f1978a28e1c94e168ecb42fc0da7af4a7f036d2e
--- /dev/null
+++ b/pgsql/include/server/utils/old_snapshot.h
@@ -0,0 +1,75 @@
+/*-------------------------------------------------------------------------
+ *
+ * old_snapshot.h
+ * Data structures for 'snapshot too old'
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ * src/include/utils/old_snapshot.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef OLD_SNAPSHOT_H
+#define OLD_SNAPSHOT_H
+
+#include "datatype/timestamp.h"
+#include "storage/s_lock.h"
+
+/*
+ * Structure for dealing with old_snapshot_threshold implementation.
+ */
+typedef struct OldSnapshotControlData
+{
+ /*
+ * Variables for old snapshot handling are shared among processes and are
+ * only allowed to move forward.
+ */
+ slock_t mutex_current; /* protect current_timestamp */
+ TimestampTz current_timestamp; /* latest snapshot timestamp */
+ slock_t mutex_latest_xmin; /* protect latest_xmin and next_map_update */
+ TransactionId latest_xmin; /* latest snapshot xmin */
+ TimestampTz next_map_update; /* latest snapshot valid up to */
+ slock_t mutex_threshold; /* protect threshold fields */
+ TimestampTz threshold_timestamp; /* earlier snapshot is old */
+ TransactionId threshold_xid; /* earlier xid may be gone */
+
+ /*
+ * Keep one xid per minute for old snapshot error handling.
+ *
+ * Use a circular buffer with a head offset, a count of entries currently
+ * used, and a timestamp corresponding to the xid at the head offset. A
+ * count_used value of zero means that there are no times stored; a
+ * count_used value of OLD_SNAPSHOT_TIME_MAP_ENTRIES means that the buffer
+ * is full and the head must be advanced to add new entries. Use
+ * timestamps aligned to minute boundaries, since that seems less
+ * surprising than aligning based on the first usage timestamp. The
+ * latest bucket is effectively stored within latest_xmin. The circular
+ * buffer is updated when we get a new xmin value that doesn't fall into
+ * the same interval.
+ *
+ * It is OK if the xid for a given time slot is from earlier than
+ * calculated by adding the number of minutes corresponding to the
+ * (possibly wrapped) distance from the head offset to the time of the
+ * head entry, since that just results in the vacuuming of old tuples
+ * being slightly less aggressive. It would not be OK for it to be off in
+ * the other direction, since it might result in vacuuming tuples that are
+ * still expected to be there.
+ *
+ * Use of an SLRU was considered but not chosen because it is more
+ * heavyweight than is needed for this, and would probably not be any less
+ * code to implement.
+ *
+ * Persistence is not needed.
+ */
+ int head_offset; /* subscript of oldest tracked time */
+ TimestampTz head_timestamp; /* time corresponding to head xid */
+ int count_used; /* how many slots are in use */
+ TransactionId xid_by_minute[FLEXIBLE_ARRAY_MEMBER];
+} OldSnapshotControlData;
+
+extern PGDLLIMPORT volatile OldSnapshotControlData *oldSnapshotControl;
+
+#endif
diff --git a/pgsql/include/server/utils/palloc.h b/pgsql/include/server/utils/palloc.h
new file mode 100644
index 0000000000000000000000000000000000000000..d1146c123510436f5264e5d6cfff39e86347ab78
--- /dev/null
+++ b/pgsql/include/server/utils/palloc.h
@@ -0,0 +1,165 @@
+/*-------------------------------------------------------------------------
+ *
+ * palloc.h
+ * POSTGRES memory allocator definitions.
+ *
+ * This file contains the basic memory allocation interface that is
+ * needed by almost every backend module. It is included directly by
+ * postgres.h, so the definitions here are automatically available
+ * everywhere. Keep it lean!
+ *
+ * Memory allocation occurs within "contexts". Every chunk obtained from
+ * palloc()/MemoryContextAlloc() is allocated within a specific context.
+ * The entire contents of a context can be freed easily and quickly by
+ * resetting or deleting the context --- this is both faster and less
+ * prone to memory-leakage bugs than releasing chunks individually.
+ * We organize contexts into context trees to allow fine-grain control
+ * over chunk lifetime while preserving the certainty that we will free
+ * everything that should be freed. See utils/mmgr/README for more info.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/palloc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PALLOC_H
+#define PALLOC_H
+
+/*
+ * Type MemoryContextData is declared in nodes/memnodes.h. Most users
+ * of memory allocation should just treat it as an abstract type, so we
+ * do not provide the struct contents here.
+ */
+typedef struct MemoryContextData *MemoryContext;
+
+/*
+ * A memory context can have callback functions registered on it. Any such
+ * function will be called once just before the context is next reset or
+ * deleted. The MemoryContextCallback struct describing such a callback
+ * typically would be allocated within the context itself, thereby avoiding
+ * any need to manage it explicitly (the reset/delete action will free it).
+ */
+typedef void (*MemoryContextCallbackFunction) (void *arg);
+
+typedef struct MemoryContextCallback
+{
+ MemoryContextCallbackFunction func; /* function to call */
+ void *arg; /* argument to pass it */
+ struct MemoryContextCallback *next; /* next in list of callbacks */
+} MemoryContextCallback;
+
+/*
+ * CurrentMemoryContext is the default allocation context for palloc().
+ * Avoid accessing it directly! Instead, use MemoryContextSwitchTo()
+ * to change the setting.
+ */
+extern PGDLLIMPORT MemoryContext CurrentMemoryContext;
+
+/*
+ * Flags for MemoryContextAllocExtended.
+ */
+#define MCXT_ALLOC_HUGE 0x01 /* allow huge allocation (> 1 GB) */
+#define MCXT_ALLOC_NO_OOM 0x02 /* no failure if out-of-memory */
+#define MCXT_ALLOC_ZERO 0x04 /* zero allocated memory */
+
+/*
+ * Fundamental memory-allocation operations (more are in utils/memutils.h)
+ */
+extern void *MemoryContextAlloc(MemoryContext context, Size size);
+extern void *MemoryContextAllocZero(MemoryContext context, Size size);
+extern void *MemoryContextAllocZeroAligned(MemoryContext context, Size size);
+extern void *MemoryContextAllocExtended(MemoryContext context,
+ Size size, int flags);
+extern void *MemoryContextAllocAligned(MemoryContext context,
+ Size size, Size alignto, int flags);
+
+extern void *palloc(Size size);
+extern void *palloc0(Size size);
+extern void *palloc_extended(Size size, int flags);
+extern void *palloc_aligned(Size size, Size alignto, int flags);
+extern pg_nodiscard void *repalloc(void *pointer, Size size);
+extern pg_nodiscard void *repalloc_extended(void *pointer,
+ Size size, int flags);
+extern pg_nodiscard void *repalloc0(void *pointer, Size oldsize, Size size);
+extern void pfree(void *pointer);
+
+/*
+ * Variants with easier notation and more type safety
+ */
+
+/*
+ * Allocate space for one object of type "type"
+ */
+#define palloc_object(type) ((type *) palloc(sizeof(type)))
+#define palloc0_object(type) ((type *) palloc0(sizeof(type)))
+
+/*
+ * Allocate space for "count" objects of type "type"
+ */
+#define palloc_array(type, count) ((type *) palloc(sizeof(type) * (count)))
+#define palloc0_array(type, count) ((type *) palloc0(sizeof(type) * (count)))
+
+/*
+ * Change size of allocation pointed to by "pointer" to have space for "count"
+ * objects of type "type"
+ */
+#define repalloc_array(pointer, type, count) ((type *) repalloc(pointer, sizeof(type) * (count)))
+#define repalloc0_array(pointer, type, oldcount, count) ((type *) repalloc0(pointer, sizeof(type) * (oldcount), sizeof(type) * (count)))
+
+/*
+ * The result of palloc() is always word-aligned, so we can skip testing
+ * alignment of the pointer when deciding which MemSet variant to use.
+ * Note that this variant does not offer any advantage, and should not be
+ * used, unless its "sz" argument is a compile-time constant; therefore, the
+ * issue that it evaluates the argument multiple times isn't a problem in
+ * practice.
+ */
+#define palloc0fast(sz) \
+ ( MemSetTest(0, sz) ? \
+ MemoryContextAllocZeroAligned(CurrentMemoryContext, sz) : \
+ MemoryContextAllocZero(CurrentMemoryContext, sz) )
+
+/* Higher-limit allocators. */
+extern void *MemoryContextAllocHuge(MemoryContext context, Size size);
+extern pg_nodiscard void *repalloc_huge(void *pointer, Size size);
+
+/*
+ * Although this header file is nominally backend-only, certain frontend
+ * programs like pg_controldata include it via postgres.h. For some compilers
+ * it's necessary to hide the inline definition of MemoryContextSwitchTo in
+ * this scenario; hence the #ifndef FRONTEND.
+ */
+
+#ifndef FRONTEND
+static inline MemoryContext
+MemoryContextSwitchTo(MemoryContext context)
+{
+ MemoryContext old = CurrentMemoryContext;
+
+ CurrentMemoryContext = context;
+ return old;
+}
+#endif /* FRONTEND */
+
+/* Registration of memory context reset/delete callbacks */
+extern void MemoryContextRegisterResetCallback(MemoryContext context,
+ MemoryContextCallback *cb);
+
+/*
+ * These are like standard strdup() except the copied string is
+ * allocated in a context, not with malloc().
+ */
+extern char *MemoryContextStrdup(MemoryContext context, const char *string);
+extern char *pstrdup(const char *in);
+extern char *pnstrdup(const char *in, Size len);
+
+extern char *pchomp(const char *in);
+
+/* sprintf into a palloc'd buffer --- these are in psprintf.c */
+extern char *psprintf(const char *fmt,...) pg_attribute_printf(1, 2);
+extern size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args) pg_attribute_printf(3, 0);
+
+#endif /* PALLOC_H */
diff --git a/pgsql/include/server/utils/partcache.h b/pgsql/include/server/utils/partcache.h
new file mode 100644
index 0000000000000000000000000000000000000000..eb9bc4b0dcf5936b8882ce760100c26cdddea7ec
--- /dev/null
+++ b/pgsql/include/server/utils/partcache.h
@@ -0,0 +1,103 @@
+/*-------------------------------------------------------------------------
+ *
+ * partcache.h
+ *
+ * Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/partcache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PARTCACHE_H
+#define PARTCACHE_H
+
+#include "access/attnum.h"
+#include "fmgr.h"
+#include "nodes/parsenodes.h"
+#include "nodes/pg_list.h"
+#include "nodes/primnodes.h"
+#include "partitioning/partdefs.h"
+#include "utils/relcache.h"
+
+/*
+ * Information about the partition key of a relation
+ */
+typedef struct PartitionKeyData
+{
+ PartitionStrategy strategy; /* partitioning strategy */
+ int16 partnatts; /* number of columns in the partition key */
+ AttrNumber *partattrs; /* attribute numbers of columns in the
+ * partition key or 0 if it's an expr */
+ List *partexprs; /* list of expressions in the partitioning
+ * key, one for each zero-valued partattrs */
+
+ Oid *partopfamily; /* OIDs of operator families */
+ Oid *partopcintype; /* OIDs of opclass declared input data types */
+ FmgrInfo *partsupfunc; /* lookup info for support funcs */
+
+ /* Partitioning collation per attribute */
+ Oid *partcollation;
+
+ /* Type information per attribute */
+ Oid *parttypid;
+ int32 *parttypmod;
+ int16 *parttyplen;
+ bool *parttypbyval;
+ char *parttypalign;
+ Oid *parttypcoll;
+} PartitionKeyData;
+
+
+extern PartitionKey RelationGetPartitionKey(Relation rel);
+extern List *RelationGetPartitionQual(Relation rel);
+extern Expr *get_partition_qual_relid(Oid relid);
+
+/*
+ * PartitionKey inquiry functions
+ */
+static inline int
+get_partition_strategy(PartitionKey key)
+{
+ return key->strategy;
+}
+
+static inline int
+get_partition_natts(PartitionKey key)
+{
+ return key->partnatts;
+}
+
+static inline List *
+get_partition_exprs(PartitionKey key)
+{
+ return key->partexprs;
+}
+
+/*
+ * PartitionKey inquiry functions - one column
+ */
+static inline int16
+get_partition_col_attnum(PartitionKey key, int col)
+{
+ return key->partattrs[col];
+}
+
+static inline Oid
+get_partition_col_typid(PartitionKey key, int col)
+{
+ return key->parttypid[col];
+}
+
+static inline int32
+get_partition_col_typmod(PartitionKey key, int col)
+{
+ return key->parttypmod[col];
+}
+
+static inline Oid
+get_partition_col_collation(PartitionKey key, int col)
+{
+ return key->partcollation[col];
+}
+
+#endif /* PARTCACHE_H */
diff --git a/pgsql/include/server/utils/pg_crc.h b/pgsql/include/server/utils/pg_crc.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0369c647173d0dd8dc3a7729c2cd3302b54cdbc
--- /dev/null
+++ b/pgsql/include/server/utils/pg_crc.h
@@ -0,0 +1,107 @@
+/*
+ * pg_crc.h
+ *
+ * PostgreSQL CRC support
+ *
+ * See Ross Williams' excellent introduction
+ * A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS, available from
+ * http://ross.net/crc/ or several other net sites.
+ *
+ * We have three slightly different variants of a 32-bit CRC calculation:
+ * CRC-32C (Castagnoli polynomial), CRC-32 (Ethernet polynomial), and a legacy
+ * CRC-32 version that uses the lookup table in a funny way. They all consist
+ * of four macros:
+ *
+ * INIT_(crc)
+ * Initialize a CRC accumulator
+ *
+ * COMP_(crc, data, len)
+ * Accumulate some (more) bytes into a CRC
+ *
+ * FIN_(crc)
+ * Finish a CRC calculation
+ *
+ * EQ_(c1, c2)
+ * Check for equality of two CRCs.
+ *
+ * The CRC-32C variant is in port/pg_crc32c.h.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/pg_crc.h
+ */
+#ifndef PG_CRC_H
+#define PG_CRC_H
+
+typedef uint32 pg_crc32;
+
+/*
+ * CRC-32, the same used e.g. in Ethernet.
+ *
+ * This is currently only used in ltree and hstore contrib modules. It uses
+ * the same lookup table as the legacy algorithm below. New code should
+ * use the Castagnoli version instead.
+ */
+#define INIT_TRADITIONAL_CRC32(crc) ((crc) = 0xFFFFFFFF)
+#define FIN_TRADITIONAL_CRC32(crc) ((crc) ^= 0xFFFFFFFF)
+#define COMP_TRADITIONAL_CRC32(crc, data, len) \
+ COMP_CRC32_NORMAL_TABLE(crc, data, len, pg_crc32_table)
+#define EQ_TRADITIONAL_CRC32(c1, c2) ((c1) == (c2))
+
+/* Sarwate's algorithm, for use with a "normal" lookup table */
+#define COMP_CRC32_NORMAL_TABLE(crc, data, len, table) \
+do { \
+ const unsigned char *__data = (const unsigned char *) (data); \
+ uint32 __len = (len); \
+\
+ while (__len-- > 0) \
+ { \
+ int __tab_index = ((int) (crc) ^ *__data++) & 0xFF; \
+ (crc) = table[__tab_index] ^ ((crc) >> 8); \
+ } \
+} while (0)
+
+/*
+ * The CRC algorithm used for WAL et al in pre-9.5 versions.
+ *
+ * This closely resembles the normal CRC-32 algorithm, but is subtly
+ * different. Using Williams' terms, we use the "normal" table, but with
+ * "reflected" code. That's bogus, but it was like that for years before
+ * anyone noticed. It does not correspond to any polynomial in a normal CRC
+ * algorithm, so it's not clear what the error-detection properties of this
+ * algorithm actually are.
+ *
+ * We still need to carry this around because it is used in a few on-disk
+ * structures that need to be pg_upgradeable. It should not be used in new
+ * code.
+ */
+#define INIT_LEGACY_CRC32(crc) ((crc) = 0xFFFFFFFF)
+#define FIN_LEGACY_CRC32(crc) ((crc) ^= 0xFFFFFFFF)
+#define COMP_LEGACY_CRC32(crc, data, len) \
+ COMP_CRC32_REFLECTED_TABLE(crc, data, len, pg_crc32_table)
+#define EQ_LEGACY_CRC32(c1, c2) ((c1) == (c2))
+
+/*
+ * Sarwate's algorithm, for use with a "reflected" lookup table (but in the
+ * legacy algorithm, we actually use it on a "normal" table, see above)
+ */
+#define COMP_CRC32_REFLECTED_TABLE(crc, data, len, table) \
+do { \
+ const unsigned char *__data = (const unsigned char *) (data); \
+ uint32 __len = (len); \
+\
+ while (__len-- > 0) \
+ { \
+ int __tab_index = ((int) ((crc) >> 24) ^ *__data++) & 0xFF; \
+ (crc) = table[__tab_index] ^ ((crc) << 8); \
+ } \
+} while (0)
+
+/*
+ * Constant table for the CRC-32 polynomials. The same table is used by both
+ * the normal and traditional variants.
+ */
+extern PGDLLIMPORT const uint32 pg_crc32_table[256];
+
+#endif /* PG_CRC_H */
diff --git a/pgsql/include/server/utils/pg_locale.h b/pgsql/include/server/utils/pg_locale.h
new file mode 100644
index 0000000000000000000000000000000000000000..e2a72435427cf14dc7bb75fac1b654d14a67d4b3
--- /dev/null
+++ b/pgsql/include/server/utils/pg_locale.h
@@ -0,0 +1,135 @@
+/*-----------------------------------------------------------------------
+ *
+ * PostgreSQL locale utilities
+ *
+ * src/include/utils/pg_locale.h
+ *
+ * Copyright (c) 2002-2023, PostgreSQL Global Development Group
+ *
+ *-----------------------------------------------------------------------
+ */
+
+#ifndef _PG_LOCALE_
+#define _PG_LOCALE_
+
+#if defined(LOCALE_T_IN_XLOCALE) || defined(WCSTOMBS_L_IN_XLOCALE)
+#include
+#endif
+#ifdef USE_ICU
+#include
+#endif
+
+#ifdef USE_ICU
+/*
+ * ucol_strcollUTF8() was introduced in ICU 50, but it is buggy before ICU 53.
+ * (see
+ * )
+ */
+#if U_ICU_VERSION_MAJOR_NUM >= 53
+#define HAVE_UCOL_STRCOLLUTF8 1
+#else
+#undef HAVE_UCOL_STRCOLLUTF8
+#endif
+#endif
+
+/* use for libc locale names */
+#define LOCALE_NAME_BUFLEN 128
+
+/* GUC settings */
+extern PGDLLIMPORT char *locale_messages;
+extern PGDLLIMPORT char *locale_monetary;
+extern PGDLLIMPORT char *locale_numeric;
+extern PGDLLIMPORT char *locale_time;
+extern PGDLLIMPORT int icu_validation_level;
+
+/* lc_time localization cache */
+extern PGDLLIMPORT char *localized_abbrev_days[];
+extern PGDLLIMPORT char *localized_full_days[];
+extern PGDLLIMPORT char *localized_abbrev_months[];
+extern PGDLLIMPORT char *localized_full_months[];
+
+/* is the databases's LC_CTYPE the C locale? */
+extern PGDLLIMPORT bool database_ctype_is_c;
+
+extern bool check_locale(int category, const char *locale, char **canonname);
+extern char *pg_perm_setlocale(int category, const char *locale);
+
+extern bool lc_collate_is_c(Oid collation);
+extern bool lc_ctype_is_c(Oid collation);
+
+/*
+ * Return the POSIX lconv struct (contains number/money formatting
+ * information) with locale information for all categories.
+ */
+extern struct lconv *PGLC_localeconv(void);
+
+extern void cache_locale_time(void);
+
+
+/*
+ * We define our own wrapper around locale_t so we can keep the same
+ * function signatures for all builds, while not having to create a
+ * fake version of the standard type locale_t in the global namespace.
+ * pg_locale_t is occasionally checked for truth, so make it a pointer.
+ */
+struct pg_locale_struct
+{
+ char provider;
+ bool deterministic;
+ union
+ {
+#ifdef HAVE_LOCALE_T
+ locale_t lt;
+#endif
+#ifdef USE_ICU
+ struct
+ {
+ const char *locale;
+ UCollator *ucol;
+ } icu;
+#endif
+ int dummy; /* in case we have neither LOCALE_T nor ICU */
+ } info;
+};
+
+typedef struct pg_locale_struct *pg_locale_t;
+
+extern PGDLLIMPORT struct pg_locale_struct default_locale;
+
+extern void make_icu_collator(const char *iculocstr,
+ const char *icurules,
+ struct pg_locale_struct *resultp);
+
+extern bool pg_locale_deterministic(pg_locale_t locale);
+extern pg_locale_t pg_newlocale_from_collation(Oid collid);
+
+extern char *get_collation_actual_version(char collprovider, const char *collcollate);
+extern int pg_strcoll(const char *arg1, const char *arg2, pg_locale_t locale);
+extern int pg_strncoll(const char *arg1, size_t len1,
+ const char *arg2, size_t len2, pg_locale_t locale);
+extern bool pg_strxfrm_enabled(pg_locale_t locale);
+extern size_t pg_strxfrm(char *dest, const char *src, size_t destsize,
+ pg_locale_t locale);
+extern size_t pg_strnxfrm(char *dest, size_t destsize, const char *src,
+ size_t srclen, pg_locale_t locale);
+extern bool pg_strxfrm_prefix_enabled(pg_locale_t locale);
+extern size_t pg_strxfrm_prefix(char *dest, const char *src, size_t destsize,
+ pg_locale_t locale);
+extern size_t pg_strnxfrm_prefix(char *dest, size_t destsize, const char *src,
+ size_t srclen, pg_locale_t locale);
+
+extern void icu_validate_locale(const char *loc_str);
+extern char *icu_language_tag(const char *loc_str, int elevel);
+
+#ifdef USE_ICU
+extern int32_t icu_to_uchar(UChar **buff_uchar, const char *buff, size_t nbytes);
+extern int32_t icu_from_uchar(char **result, const UChar *buff_uchar, int32_t len_uchar);
+#endif
+
+/* These functions convert from/to libc's wchar_t, *not* pg_wchar_t */
+extern size_t wchar2char(char *to, const wchar_t *from, size_t tolen,
+ pg_locale_t locale);
+extern size_t char2wchar(wchar_t *to, size_t tolen,
+ const char *from, size_t fromlen, pg_locale_t locale);
+
+#endif /* _PG_LOCALE_ */
diff --git a/pgsql/include/server/utils/pg_lsn.h b/pgsql/include/server/utils/pg_lsn.h
new file mode 100644
index 0000000000000000000000000000000000000000..7bda26b40ac005a47d031cd98580fb604b503b1b
--- /dev/null
+++ b/pgsql/include/server/utils/pg_lsn.h
@@ -0,0 +1,38 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_lsn.h
+ * Declarations for operations on log sequence numbers (LSNs) of
+ * PostgreSQL.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/pg_lsn.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_LSN_H
+#define PG_LSN_H
+
+#include "access/xlogdefs.h"
+#include "fmgr.h"
+
+static inline XLogRecPtr
+DatumGetLSN(Datum X)
+{
+ return (XLogRecPtr) DatumGetInt64(X);
+}
+
+static inline Datum
+LSNGetDatum(XLogRecPtr X)
+{
+ return Int64GetDatum((int64) X);
+}
+
+#define PG_GETARG_LSN(n) DatumGetLSN(PG_GETARG_DATUM(n))
+#define PG_RETURN_LSN(x) return LSNGetDatum(x)
+
+extern XLogRecPtr pg_lsn_in_internal(const char *str, bool *have_error);
+
+#endif /* PG_LSN_H */
diff --git a/pgsql/include/server/utils/pg_rusage.h b/pgsql/include/server/utils/pg_rusage.h
new file mode 100644
index 0000000000000000000000000000000000000000..219ee678856ce26234e06ee9e28edb38cc734cd3
--- /dev/null
+++ b/pgsql/include/server/utils/pg_rusage.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_rusage.h
+ * header file for resource usage measurement support routines
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/pg_rusage.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_RUSAGE_H
+#define PG_RUSAGE_H
+
+#include
+#include
+
+
+/* State structure for pg_rusage_init/pg_rusage_show */
+typedef struct PGRUsage
+{
+ struct timeval tv;
+ struct rusage ru;
+} PGRUsage;
+
+
+extern void pg_rusage_init(PGRUsage *ru0);
+extern const char *pg_rusage_show(const PGRUsage *ru0);
+
+#endif /* PG_RUSAGE_H */
diff --git a/pgsql/include/server/utils/pgstat_internal.h b/pgsql/include/server/utils/pgstat_internal.h
new file mode 100644
index 0000000000000000000000000000000000000000..60fbf9394b98cc761bc2903ffdbea9d40ffbb9f4
--- /dev/null
+++ b/pgsql/include/server/utils/pgstat_internal.h
@@ -0,0 +1,814 @@
+/* ----------
+ * pgstat_internal.h
+ *
+ * Definitions for the PostgreSQL cumulative statistics system that should
+ * only be needed by files implementing statistics support (rather than ones
+ * reporting / querying stats).
+ *
+ * Copyright (c) 2001-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/pgstat_internal.h
+ * ----------
+ */
+#ifndef PGSTAT_INTERNAL_H
+#define PGSTAT_INTERNAL_H
+
+
+#include "common/hashfn.h"
+#include "lib/dshash.h"
+#include "lib/ilist.h"
+#include "pgstat.h"
+#include "storage/lwlock.h"
+#include "utils/dsa.h"
+
+
+/*
+ * Types related to shared memory storage of statistics.
+ *
+ * Per-object statistics are stored in the "shared stats" hashtable. That
+ * table's entries (PgStatShared_HashEntry) contain a pointer to the actual stats
+ * data for the object (the size of the stats data varies depending on the
+ * kind of stats). The table is keyed by PgStat_HashKey.
+ *
+ * Once a backend has a reference to a shared stats entry, it increments the
+ * entry's refcount. Even after stats data is dropped (e.g., due to a DROP
+ * TABLE), the entry itself can only be deleted once all references have been
+ * released.
+ *
+ * These refcounts, in combination with a backend local hashtable
+ * (pgStatEntryRefHash, with entries pointing to PgStat_EntryRef) in front of
+ * the shared hash table, mean that most stats work can happen without
+ * touching the shared hash table, reducing contention.
+ *
+ * Once there are pending stats updates for a table PgStat_EntryRef->pending
+ * is allocated to contain a working space for as-of-yet-unapplied stats
+ * updates. Once the stats are flushed, PgStat_EntryRef->pending is freed.
+ *
+ * Each stat kind in the shared hash table has a fixed member
+ * PgStatShared_Common as the first element.
+ */
+
+/* struct for shared statistics hash entry key. */
+typedef struct PgStat_HashKey
+{
+ PgStat_Kind kind; /* statistics entry kind */
+ Oid dboid; /* database ID. InvalidOid for shared objects. */
+ Oid objoid; /* object ID, either table or function. */
+} PgStat_HashKey;
+
+/*
+ * Shared statistics hash entry. Doesn't itself contain any stats, but points
+ * to them (with ->body). That allows the stats entries themselves to be of
+ * variable size.
+ */
+typedef struct PgStatShared_HashEntry
+{
+ PgStat_HashKey key; /* hash key */
+
+ /*
+ * If dropped is set, backends need to release their references so that
+ * the memory for the entry can be freed. No new references may be made
+ * once marked as dropped.
+ */
+ bool dropped;
+
+ /*
+ * Refcount managing lifetime of the entry itself (as opposed to the
+ * dshash entry pointing to it). The stats lifetime has to be separate
+ * from the hash table entry lifetime because we allow backends to point
+ * to a stats entry without holding a hash table lock (and some other
+ * reasons).
+ *
+ * As long as the entry is not dropped, 1 is added to the refcount
+ * representing that the entry should not be dropped. In addition each
+ * backend that has a reference to the entry needs to increment the
+ * refcount as long as it does.
+ *
+ * May only be incremented / decremented while holding at least a shared
+ * lock on the dshash partition containing the entry. It needs to be an
+ * atomic variable because multiple backends can increment the refcount
+ * with just a shared lock.
+ *
+ * When the refcount reaches 0 the entry needs to be freed.
+ */
+ pg_atomic_uint32 refcount;
+
+ /*
+ * Pointer to shared stats. The stats entry always starts with
+ * PgStatShared_Common, embedded in a larger struct containing the
+ * PgStat_Kind specific stats fields.
+ */
+ dsa_pointer body;
+} PgStatShared_HashEntry;
+
+/*
+ * Common header struct for PgStatShared_*.
+ */
+typedef struct PgStatShared_Common
+{
+ uint32 magic; /* just a validity cross-check */
+ /* lock protecting stats contents (i.e. data following the header) */
+ LWLock lock;
+} PgStatShared_Common;
+
+/*
+ * A backend local reference to a shared stats entry. As long as at least one
+ * such reference exists, the shared stats entry will not be released.
+ *
+ * If there are pending stats update to the shared stats, these are stored in
+ * ->pending.
+ */
+typedef struct PgStat_EntryRef
+{
+ /*
+ * Pointer to the PgStatShared_HashEntry entry in the shared stats
+ * hashtable.
+ */
+ PgStatShared_HashEntry *shared_entry;
+
+ /*
+ * Pointer to the stats data (i.e. PgStatShared_HashEntry->body), resolved
+ * as a local pointer, to avoid repeated dsa_get_address() calls.
+ */
+ PgStatShared_Common *shared_stats;
+
+ /*
+ * Pending statistics data that will need to be flushed to shared memory
+ * stats eventually. Each stats kind utilizing pending data defines what
+ * format its pending data has and needs to provide a
+ * PgStat_KindInfo->flush_pending_cb callback to merge pending into shared
+ * stats.
+ */
+ void *pending;
+ dlist_node pending_node; /* membership in pgStatPending list */
+} PgStat_EntryRef;
+
+
+/*
+ * Some stats changes are transactional. To maintain those, a stack of
+ * PgStat_SubXactStatus entries is maintained, which contain data pertaining
+ * to the current transaction and its active subtransactions.
+ */
+typedef struct PgStat_SubXactStatus
+{
+ int nest_level; /* subtransaction nest level */
+
+ struct PgStat_SubXactStatus *prev; /* higher-level subxact if any */
+
+ /*
+ * Statistics for transactionally dropped objects need to be
+ * transactionally dropped as well. Collect the stats dropped in the
+ * current (sub-)transaction and only execute the stats drop when we know
+ * if the transaction commits/aborts. To handle replicas and crashes,
+ * stats drops are included in commit / abort records.
+ */
+ dclist_head pending_drops;
+
+ /*
+ * Tuple insertion/deletion counts for an open transaction can't be
+ * propagated into PgStat_TableStatus counters until we know if it is
+ * going to commit or abort. Hence, we keep these counts in per-subxact
+ * structs that live in TopTransactionContext. This data structure is
+ * designed on the assumption that subxacts won't usually modify very many
+ * tables.
+ */
+ PgStat_TableXactStatus *first; /* head of list for this subxact */
+} PgStat_SubXactStatus;
+
+
+/*
+ * Metadata for a specific kind of statistics.
+ */
+typedef struct PgStat_KindInfo
+{
+ /*
+ * Do a fixed number of stats objects exist for this kind of stats (e.g.
+ * bgwriter stats) or not (e.g. tables).
+ */
+ bool fixed_amount:1;
+
+ /*
+ * Can stats of this kind be accessed from another database? Determines
+ * whether a stats object gets included in stats snapshots.
+ */
+ bool accessed_across_databases:1;
+
+ /*
+ * For variable-numbered stats: Identified on-disk using a name, rather
+ * than PgStat_HashKey. Probably only needed for replication slot stats.
+ */
+ bool named_on_disk:1;
+
+ /*
+ * The size of an entry in the shared stats hash table (pointed to by
+ * PgStatShared_HashEntry->body).
+ */
+ uint32 shared_size;
+
+ /*
+ * The offset/size of statistics inside the shared stats entry. Used when
+ * [de-]serializing statistics to / from disk respectively. Separate from
+ * shared_size because [de-]serialization may not include in-memory state
+ * like lwlocks.
+ */
+ uint32 shared_data_off;
+ uint32 shared_data_len;
+
+ /*
+ * The size of the pending data for this kind. E.g. how large
+ * PgStat_EntryRef->pending is. Used for allocations.
+ *
+ * 0 signals that an entry of this kind should never have a pending entry.
+ */
+ uint32 pending_size;
+
+ /*
+ * For variable-numbered stats: flush pending stats. Required if pending
+ * data is used.
+ */
+ bool (*flush_pending_cb) (PgStat_EntryRef *sr, bool nowait);
+
+ /*
+ * For variable-numbered stats: delete pending stats. Optional.
+ */
+ void (*delete_pending_cb) (PgStat_EntryRef *sr);
+
+ /*
+ * For variable-numbered stats: reset the reset timestamp. Optional.
+ */
+ void (*reset_timestamp_cb) (PgStatShared_Common *header, TimestampTz ts);
+
+ /*
+ * For variable-numbered stats with named_on_disk. Optional.
+ */
+ void (*to_serialized_name) (const PgStat_HashKey *key,
+ const PgStatShared_Common *header, NameData *name);
+ bool (*from_serialized_name) (const NameData *name, PgStat_HashKey *key);
+
+ /*
+ * For fixed-numbered statistics: Reset All.
+ */
+ void (*reset_all_cb) (TimestampTz ts);
+
+ /*
+ * For fixed-numbered statistics: Build snapshot for entry
+ */
+ void (*snapshot_cb) (void);
+
+ /* name of the kind of stats */
+ const char *const name;
+} PgStat_KindInfo;
+
+
+/*
+ * List of SLRU names that we keep stats for. There is no central registry of
+ * SLRUs, so we use this fixed list instead. The "other" entry is used for
+ * all SLRUs without an explicit entry (e.g. SLRUs in extensions).
+ *
+ * This is only defined here so that SLRU_NUM_ELEMENTS is known for later type
+ * definitions.
+ */
+static const char *const slru_names[] = {
+ "CommitTs",
+ "MultiXactMember",
+ "MultiXactOffset",
+ "Notify",
+ "Serial",
+ "Subtrans",
+ "Xact",
+ "other" /* has to be last */
+};
+
+#define SLRU_NUM_ELEMENTS lengthof(slru_names)
+
+
+/* ----------
+ * Types and definitions for different kinds of fixed-amount stats.
+ *
+ * Single-writer stats use the changecount mechanism to achieve low-overhead
+ * writes - they're obviously more performance critical than reads. Check the
+ * definition of struct PgBackendStatus for some explanation of the
+ * changecount mechanism.
+ *
+ * Because the obvious implementation of resetting single-writer stats isn't
+ * compatible with that (another backend needs to write), we don't scribble on
+ * shared stats while resetting. Instead, just record the current counter
+ * values in a copy of the stats data, which is protected by ->lock. See
+ * pgstat_fetch_stat_(archiver|bgwriter|checkpointer) for the reader side.
+ *
+ * The only exception to that is the stat_reset_timestamp in these structs,
+ * which is protected by ->lock, because it has to be written by another
+ * backend while resetting.
+ * ----------
+ */
+
+typedef struct PgStatShared_Archiver
+{
+ /* lock protects ->reset_offset as well as stats->stat_reset_timestamp */
+ LWLock lock;
+ uint32 changecount;
+ PgStat_ArchiverStats stats;
+ PgStat_ArchiverStats reset_offset;
+} PgStatShared_Archiver;
+
+typedef struct PgStatShared_BgWriter
+{
+ /* lock protects ->reset_offset as well as stats->stat_reset_timestamp */
+ LWLock lock;
+ uint32 changecount;
+ PgStat_BgWriterStats stats;
+ PgStat_BgWriterStats reset_offset;
+} PgStatShared_BgWriter;
+
+typedef struct PgStatShared_Checkpointer
+{
+ /* lock protects ->reset_offset as well as stats->stat_reset_timestamp */
+ LWLock lock;
+ uint32 changecount;
+ PgStat_CheckpointerStats stats;
+ PgStat_CheckpointerStats reset_offset;
+} PgStatShared_Checkpointer;
+
+/* Shared-memory ready PgStat_IO */
+typedef struct PgStatShared_IO
+{
+ /*
+ * locks[i] protects stats.stats[i]. locks[0] also protects
+ * stats.stat_reset_timestamp.
+ */
+ LWLock locks[BACKEND_NUM_TYPES];
+ PgStat_IO stats;
+} PgStatShared_IO;
+
+typedef struct PgStatShared_SLRU
+{
+ /* lock protects ->stats */
+ LWLock lock;
+ PgStat_SLRUStats stats[SLRU_NUM_ELEMENTS];
+} PgStatShared_SLRU;
+
+typedef struct PgStatShared_Wal
+{
+ /* lock protects ->stats */
+ LWLock lock;
+ PgStat_WalStats stats;
+} PgStatShared_Wal;
+
+
+
+/* ----------
+ * Types and definitions for different kinds of variable-amount stats.
+ *
+ * Each struct has to start with PgStatShared_Common, containing information
+ * common across the different types of stats. Kind-specific data follows.
+ * ----------
+ */
+
+typedef struct PgStatShared_Database
+{
+ PgStatShared_Common header;
+ PgStat_StatDBEntry stats;
+} PgStatShared_Database;
+
+typedef struct PgStatShared_Relation
+{
+ PgStatShared_Common header;
+ PgStat_StatTabEntry stats;
+} PgStatShared_Relation;
+
+typedef struct PgStatShared_Function
+{
+ PgStatShared_Common header;
+ PgStat_StatFuncEntry stats;
+} PgStatShared_Function;
+
+typedef struct PgStatShared_Subscription
+{
+ PgStatShared_Common header;
+ PgStat_StatSubEntry stats;
+} PgStatShared_Subscription;
+
+typedef struct PgStatShared_ReplSlot
+{
+ PgStatShared_Common header;
+ PgStat_StatReplSlotEntry stats;
+} PgStatShared_ReplSlot;
+
+
+/*
+ * Central shared memory entry for the cumulative stats system.
+ *
+ * Fixed amount stats, the dynamic shared memory hash table for
+ * non-fixed-amount stats, as well as remaining bits and pieces are all
+ * reached from here.
+ */
+typedef struct PgStat_ShmemControl
+{
+ void *raw_dsa_area;
+
+ /*
+ * Stats for variable-numbered objects are kept in this shared hash table.
+ * See comment above PgStat_Kind for details.
+ */
+ dshash_table_handle hash_handle; /* shared dbstat hash */
+
+ /* Has the stats system already been shut down? Just a debugging check. */
+ bool is_shutdown;
+
+ /*
+ * Whenever statistics for dropped objects could not be freed - because
+ * backends still have references - the dropping backend calls
+ * pgstat_request_entry_refs_gc() incrementing this counter. Eventually
+ * that causes backends to run pgstat_gc_entry_refs(), allowing memory to
+ * be reclaimed.
+ */
+ pg_atomic_uint64 gc_request_count;
+
+ /*
+ * Stats data for fixed-numbered objects.
+ */
+ PgStatShared_Archiver archiver;
+ PgStatShared_BgWriter bgwriter;
+ PgStatShared_Checkpointer checkpointer;
+ PgStatShared_IO io;
+ PgStatShared_SLRU slru;
+ PgStatShared_Wal wal;
+} PgStat_ShmemControl;
+
+
+/*
+ * Cached statistics snapshot
+ */
+typedef struct PgStat_Snapshot
+{
+ PgStat_FetchConsistency mode;
+
+ /* time at which snapshot was taken */
+ TimestampTz snapshot_timestamp;
+
+ bool fixed_valid[PGSTAT_NUM_KINDS];
+
+ PgStat_ArchiverStats archiver;
+
+ PgStat_BgWriterStats bgwriter;
+
+ PgStat_CheckpointerStats checkpointer;
+
+ PgStat_IO io;
+
+ PgStat_SLRUStats slru[SLRU_NUM_ELEMENTS];
+
+ PgStat_WalStats wal;
+
+ /* to free snapshot in bulk */
+ MemoryContext context;
+ struct pgstat_snapshot_hash *stats;
+} PgStat_Snapshot;
+
+
+/*
+ * Collection of backend-local stats state.
+ */
+typedef struct PgStat_LocalState
+{
+ PgStat_ShmemControl *shmem;
+ dsa_area *dsa;
+ dshash_table *shared_hash;
+
+ /* the current statistics snapshot */
+ PgStat_Snapshot snapshot;
+} PgStat_LocalState;
+
+
+/*
+ * Inline functions defined further below.
+ */
+
+static inline void pgstat_begin_changecount_write(uint32 *cc);
+static inline void pgstat_end_changecount_write(uint32 *cc);
+static inline uint32 pgstat_begin_changecount_read(uint32 *cc);
+static inline bool pgstat_end_changecount_read(uint32 *cc, uint32 cc_before);
+
+static inline void pgstat_copy_changecounted_stats(void *dst, void *src, size_t len,
+ uint32 *cc);
+
+static inline int pgstat_cmp_hash_key(const void *a, const void *b, size_t size, void *arg);
+static inline uint32 pgstat_hash_hash_key(const void *d, size_t size, void *arg);
+static inline size_t pgstat_get_entry_len(PgStat_Kind kind);
+static inline void *pgstat_get_entry_data(PgStat_Kind kind, PgStatShared_Common *entry);
+
+
+/*
+ * Functions in pgstat.c
+ */
+
+extern const PgStat_KindInfo *pgstat_get_kind_info(PgStat_Kind kind);
+
+#ifdef USE_ASSERT_CHECKING
+extern void pgstat_assert_is_up(void);
+#else
+#define pgstat_assert_is_up() ((void)true)
+#endif
+
+extern void pgstat_delete_pending_entry(PgStat_EntryRef *entry_ref);
+extern PgStat_EntryRef *pgstat_prep_pending_entry(PgStat_Kind kind, Oid dboid, Oid objoid, bool *created_entry);
+extern PgStat_EntryRef *pgstat_fetch_pending_entry(PgStat_Kind kind, Oid dboid, Oid objoid);
+
+extern void *pgstat_fetch_entry(PgStat_Kind kind, Oid dboid, Oid objoid);
+extern void pgstat_snapshot_fixed(PgStat_Kind kind);
+
+
+/*
+ * Functions in pgstat_archiver.c
+ */
+
+extern void pgstat_archiver_reset_all_cb(TimestampTz ts);
+extern void pgstat_archiver_snapshot_cb(void);
+
+
+/*
+ * Functions in pgstat_bgwriter.c
+ */
+
+extern void pgstat_bgwriter_reset_all_cb(TimestampTz ts);
+extern void pgstat_bgwriter_snapshot_cb(void);
+
+
+/*
+ * Functions in pgstat_checkpointer.c
+ */
+
+extern void pgstat_checkpointer_reset_all_cb(TimestampTz ts);
+extern void pgstat_checkpointer_snapshot_cb(void);
+
+
+/*
+ * Functions in pgstat_database.c
+ */
+
+extern void pgstat_report_disconnect(Oid dboid);
+extern void pgstat_update_dbstats(TimestampTz ts);
+extern void AtEOXact_PgStat_Database(bool isCommit, bool parallel);
+
+extern PgStat_StatDBEntry *pgstat_prep_database_pending(Oid dboid);
+extern void pgstat_reset_database_timestamp(Oid dboid, TimestampTz ts);
+extern bool pgstat_database_flush_cb(PgStat_EntryRef *entry_ref, bool nowait);
+extern void pgstat_database_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts);
+
+
+/*
+ * Functions in pgstat_function.c
+ */
+
+extern bool pgstat_function_flush_cb(PgStat_EntryRef *entry_ref, bool nowait);
+
+
+/*
+ * Functions in pgstat_io.c
+ */
+
+extern bool pgstat_flush_io(bool nowait);
+extern void pgstat_io_reset_all_cb(TimestampTz ts);
+extern void pgstat_io_snapshot_cb(void);
+
+
+/*
+ * Functions in pgstat_relation.c
+ */
+
+extern void AtEOXact_PgStat_Relations(PgStat_SubXactStatus *xact_state, bool isCommit);
+extern void AtEOSubXact_PgStat_Relations(PgStat_SubXactStatus *xact_state, bool isCommit, int nestDepth);
+extern void AtPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state);
+extern void PostPrepare_PgStat_Relations(PgStat_SubXactStatus *xact_state);
+
+extern bool pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait);
+extern void pgstat_relation_delete_pending_cb(PgStat_EntryRef *entry_ref);
+
+
+/*
+ * Functions in pgstat_replslot.c
+ */
+
+extern void pgstat_replslot_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts);
+extern void pgstat_replslot_to_serialized_name_cb(const PgStat_HashKey *key, const PgStatShared_Common *header, NameData *name);
+extern bool pgstat_replslot_from_serialized_name_cb(const NameData *name, PgStat_HashKey *key);
+
+
+/*
+ * Functions in pgstat_shmem.c
+ */
+
+extern void pgstat_attach_shmem(void);
+extern void pgstat_detach_shmem(void);
+
+extern PgStat_EntryRef *pgstat_get_entry_ref(PgStat_Kind kind, Oid dboid, Oid objoid,
+ bool create, bool *created_entry);
+extern bool pgstat_lock_entry(PgStat_EntryRef *entry_ref, bool nowait);
+extern bool pgstat_lock_entry_shared(PgStat_EntryRef *entry_ref, bool nowait);
+extern void pgstat_unlock_entry(PgStat_EntryRef *entry_ref);
+extern bool pgstat_drop_entry(PgStat_Kind kind, Oid dboid, Oid objoid);
+extern void pgstat_drop_all_entries(void);
+extern PgStat_EntryRef *pgstat_get_entry_ref_locked(PgStat_Kind kind, Oid dboid, Oid objoid,
+ bool nowait);
+extern void pgstat_reset_entry(PgStat_Kind kind, Oid dboid, Oid objoid, TimestampTz ts);
+extern void pgstat_reset_entries_of_kind(PgStat_Kind kind, TimestampTz ts);
+extern void pgstat_reset_matching_entries(bool (*do_reset) (PgStatShared_HashEntry *, Datum),
+ Datum match_data,
+ TimestampTz ts);
+
+extern void pgstat_request_entry_refs_gc(void);
+extern PgStatShared_Common *pgstat_init_entry(PgStat_Kind kind,
+ PgStatShared_HashEntry *shhashent);
+
+
+/*
+ * Functions in pgstat_slru.c
+ */
+
+extern bool pgstat_slru_flush(bool nowait);
+extern void pgstat_slru_reset_all_cb(TimestampTz ts);
+extern void pgstat_slru_snapshot_cb(void);
+
+
+/*
+ * Functions in pgstat_wal.c
+ */
+
+extern bool pgstat_flush_wal(bool nowait);
+extern void pgstat_init_wal(void);
+extern bool pgstat_have_pending_wal(void);
+
+extern void pgstat_wal_reset_all_cb(TimestampTz ts);
+extern void pgstat_wal_snapshot_cb(void);
+
+
+/*
+ * Functions in pgstat_subscription.c
+ */
+
+extern bool pgstat_subscription_flush_cb(PgStat_EntryRef *entry_ref, bool nowait);
+extern void pgstat_subscription_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts);
+
+
+/*
+ * Functions in pgstat_xact.c
+ */
+
+extern PgStat_SubXactStatus *pgstat_get_xact_stack_level(int nest_level);
+extern void pgstat_drop_transactional(PgStat_Kind kind, Oid dboid, Oid objoid);
+extern void pgstat_create_transactional(PgStat_Kind kind, Oid dboid, Oid objoid);
+
+
+/*
+ * Variables in pgstat.c
+ */
+
+extern PGDLLIMPORT PgStat_LocalState pgStatLocal;
+
+
+/*
+ * Variables in pgstat_io.c
+ */
+
+extern PGDLLIMPORT bool have_iostats;
+
+
+/*
+ * Variables in pgstat_slru.c
+ */
+
+extern PGDLLIMPORT bool have_slrustats;
+
+
+/*
+ * Implementation of inline functions declared above.
+ */
+
+/*
+ * Helpers for changecount manipulation. See comments around struct
+ * PgBackendStatus for details.
+ */
+
+static inline void
+pgstat_begin_changecount_write(uint32 *cc)
+{
+ Assert((*cc & 1) == 0);
+
+ START_CRIT_SECTION();
+ (*cc)++;
+ pg_write_barrier();
+}
+
+static inline void
+pgstat_end_changecount_write(uint32 *cc)
+{
+ Assert((*cc & 1) == 1);
+
+ pg_write_barrier();
+
+ (*cc)++;
+
+ END_CRIT_SECTION();
+}
+
+static inline uint32
+pgstat_begin_changecount_read(uint32 *cc)
+{
+ uint32 before_cc = *cc;
+
+ CHECK_FOR_INTERRUPTS();
+
+ pg_read_barrier();
+
+ return before_cc;
+}
+
+/*
+ * Returns true if the read succeeded, false if it needs to be repeated.
+ */
+static inline bool
+pgstat_end_changecount_read(uint32 *cc, uint32 before_cc)
+{
+ uint32 after_cc;
+
+ pg_read_barrier();
+
+ after_cc = *cc;
+
+ /* was a write in progress when we started? */
+ if (before_cc & 1)
+ return false;
+
+ /* did writes start and complete while we read? */
+ return before_cc == after_cc;
+}
+
+
+/*
+ * helper function for PgStat_KindInfo->snapshot_cb
+ * PgStat_KindInfo->reset_all_cb callbacks.
+ *
+ * Copies out the specified memory area following change-count protocol.
+ */
+static inline void
+pgstat_copy_changecounted_stats(void *dst, void *src, size_t len,
+ uint32 *cc)
+{
+ uint32 cc_before;
+
+ do
+ {
+ cc_before = pgstat_begin_changecount_read(cc);
+
+ memcpy(dst, src, len);
+ }
+ while (!pgstat_end_changecount_read(cc, cc_before));
+}
+
+/* helpers for dshash / simplehash hashtables */
+static inline int
+pgstat_cmp_hash_key(const void *a, const void *b, size_t size, void *arg)
+{
+ Assert(size == sizeof(PgStat_HashKey) && arg == NULL);
+ return memcmp(a, b, sizeof(PgStat_HashKey));
+}
+
+static inline uint32
+pgstat_hash_hash_key(const void *d, size_t size, void *arg)
+{
+ const PgStat_HashKey *key = (PgStat_HashKey *) d;
+ uint32 hash;
+
+ Assert(size == sizeof(PgStat_HashKey) && arg == NULL);
+
+ hash = murmurhash32(key->kind);
+ hash = hash_combine(hash, murmurhash32(key->dboid));
+ hash = hash_combine(hash, murmurhash32(key->objoid));
+
+ return hash;
+}
+
+/*
+ * The length of the data portion of a shared memory stats entry (i.e. without
+ * transient data such as refcounts, lwlocks, ...).
+ */
+static inline size_t
+pgstat_get_entry_len(PgStat_Kind kind)
+{
+ return pgstat_get_kind_info(kind)->shared_data_len;
+}
+
+/*
+ * Returns a pointer to the data portion of a shared memory stats entry.
+ */
+static inline void *
+pgstat_get_entry_data(PgStat_Kind kind, PgStatShared_Common *entry)
+{
+ size_t off = pgstat_get_kind_info(kind)->shared_data_off;
+
+ Assert(off != 0 && off < PG_UINT32_MAX);
+
+ return ((char *) (entry)) + off;
+}
+
+#endif /* PGSTAT_INTERNAL_H */
diff --git a/pgsql/include/server/utils/pidfile.h b/pgsql/include/server/utils/pidfile.h
new file mode 100644
index 0000000000000000000000000000000000000000..1393a534f607646aaad9668488f2d645efd07674
--- /dev/null
+++ b/pgsql/include/server/utils/pidfile.h
@@ -0,0 +1,56 @@
+/*-------------------------------------------------------------------------
+ *
+ * pidfile.h
+ * Declarations describing the data directory lock file (postmaster.pid)
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/pidfile.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef UTILS_PIDFILE_H
+#define UTILS_PIDFILE_H
+
+/*
+ * As of Postgres 10, the contents of the data-directory lock file are:
+ *
+ * line #
+ * 1 postmaster PID (or negative of a standalone backend's PID)
+ * 2 data directory path
+ * 3 postmaster start timestamp (time_t representation)
+ * 4 port number
+ * 5 first Unix socket directory path (empty if none)
+ * 6 first listen_address (IP address or "*"; empty if no TCP port)
+ * 7 shared memory key (empty on Windows)
+ * 8 postmaster status (see values below)
+ *
+ * Lines 6 and up are added via AddToDataDirLockFile() after initial file
+ * creation; also, line 5 is initially empty and is changed after the first
+ * Unix socket is opened. Onlookers should not assume that lines 4 and up
+ * are filled in any particular order.
+ *
+ * Socket lock file(s), if used, have the same contents as lines 1-5, with
+ * line 5 being their own directory.
+ */
+#define LOCK_FILE_LINE_PID 1
+#define LOCK_FILE_LINE_DATA_DIR 2
+#define LOCK_FILE_LINE_START_TIME 3
+#define LOCK_FILE_LINE_PORT 4
+#define LOCK_FILE_LINE_SOCKET_DIR 5
+#define LOCK_FILE_LINE_LISTEN_ADDR 6
+#define LOCK_FILE_LINE_SHMEM_KEY 7
+#define LOCK_FILE_LINE_PM_STATUS 8
+
+/*
+ * The PM_STATUS line may contain one of these values. All these strings
+ * must be the same length, per comments for AddToDataDirLockFile().
+ * We pad with spaces as needed to make that true.
+ */
+#define PM_STATUS_STARTING "starting" /* still starting up */
+#define PM_STATUS_STOPPING "stopping" /* in shutdown sequence */
+#define PM_STATUS_READY "ready " /* ready for connections */
+#define PM_STATUS_STANDBY "standby " /* up, won't accept connections */
+
+#endif /* UTILS_PIDFILE_H */
diff --git a/pgsql/include/server/utils/plancache.h b/pgsql/include/server/utils/plancache.h
new file mode 100644
index 0000000000000000000000000000000000000000..a443181d41654e96d875f529f535666f45da1210
--- /dev/null
+++ b/pgsql/include/server/utils/plancache.h
@@ -0,0 +1,236 @@
+/*-------------------------------------------------------------------------
+ *
+ * plancache.h
+ * Plan cache definitions.
+ *
+ * See plancache.c for comments.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/plancache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PLANCACHE_H
+#define PLANCACHE_H
+
+#include "access/tupdesc.h"
+#include "lib/ilist.h"
+#include "nodes/params.h"
+#include "tcop/cmdtag.h"
+#include "utils/queryenvironment.h"
+#include "utils/resowner.h"
+
+
+/* Forward declaration, to avoid including parsenodes.h here */
+struct RawStmt;
+
+/* possible values for plan_cache_mode */
+typedef enum
+{
+ PLAN_CACHE_MODE_AUTO,
+ PLAN_CACHE_MODE_FORCE_GENERIC_PLAN,
+ PLAN_CACHE_MODE_FORCE_CUSTOM_PLAN
+} PlanCacheMode;
+
+/* GUC parameter */
+extern PGDLLIMPORT int plan_cache_mode;
+
+#define CACHEDPLANSOURCE_MAGIC 195726186
+#define CACHEDPLAN_MAGIC 953717834
+#define CACHEDEXPR_MAGIC 838275847
+
+/*
+ * CachedPlanSource (which might better have been called CachedQuery)
+ * represents a SQL query that we expect to use multiple times. It stores
+ * the query source text, the raw parse tree, and the analyzed-and-rewritten
+ * query tree, as well as adjunct data. Cache invalidation can happen as a
+ * result of DDL affecting objects used by the query. In that case we discard
+ * the analyzed-and-rewritten query tree, and rebuild it when next needed.
+ *
+ * An actual execution plan, represented by CachedPlan, is derived from the
+ * CachedPlanSource when we need to execute the query. The plan could be
+ * either generic (usable with any set of plan parameters) or custom (for a
+ * specific set of parameters). plancache.c contains the logic that decides
+ * which way to do it for any particular execution. If we are using a generic
+ * cached plan then it is meant to be re-used across multiple executions, so
+ * callers must always treat CachedPlans as read-only.
+ *
+ * Once successfully built and "saved", CachedPlanSources typically live
+ * for the life of the backend, although they can be dropped explicitly.
+ * CachedPlans are reference-counted and go away automatically when the last
+ * reference is dropped. A CachedPlan can outlive the CachedPlanSource it
+ * was created from.
+ *
+ * An "unsaved" CachedPlanSource can be used for generating plans, but it
+ * lives in transient storage and will not be updated in response to sinval
+ * events.
+ *
+ * CachedPlans made from saved CachedPlanSources are likewise in permanent
+ * storage, so to avoid memory leaks, the reference-counted references to them
+ * must be held in permanent data structures or ResourceOwners. CachedPlans
+ * made from unsaved CachedPlanSources are in children of the caller's
+ * memory context, so references to them should not be longer-lived than
+ * that context. (Reference counting is somewhat pro forma in that case,
+ * though it may be useful if the CachedPlan can be discarded early.)
+ *
+ * A CachedPlanSource has two associated memory contexts: one that holds the
+ * struct itself, the query source text and the raw parse tree, and another
+ * context that holds the rewritten query tree and associated data. This
+ * allows the query tree to be discarded easily when it is invalidated.
+ *
+ * Some callers wish to use the CachedPlan API even with one-shot queries
+ * that have no reason to be saved at all. We therefore support a "oneshot"
+ * variant that does no data copying or invalidation checking. In this case
+ * there are no separate memory contexts: the CachedPlanSource struct and
+ * all subsidiary data live in the caller's CurrentMemoryContext, and there
+ * is no way to free memory short of clearing that entire context. A oneshot
+ * plan is always treated as unsaved.
+ *
+ * Note: the string referenced by commandTag is not subsidiary storage;
+ * it is assumed to be a compile-time-constant string. As with portals,
+ * commandTag shall be NULL if and only if the original query string (before
+ * rewriting) was an empty string.
+ */
+typedef struct CachedPlanSource
+{
+ int magic; /* should equal CACHEDPLANSOURCE_MAGIC */
+ struct RawStmt *raw_parse_tree; /* output of raw_parser(), or NULL */
+ const char *query_string; /* source text of query */
+ CommandTag commandTag; /* 'nuff said */
+ Oid *param_types; /* array of parameter type OIDs, or NULL */
+ int num_params; /* length of param_types array */
+ ParserSetupHook parserSetup; /* alternative parameter spec method */
+ void *parserSetupArg;
+ int cursor_options; /* cursor options used for planning */
+ bool fixed_result; /* disallow change in result tupdesc? */
+ TupleDesc resultDesc; /* result type; NULL = doesn't return tuples */
+ MemoryContext context; /* memory context holding all above */
+ /* These fields describe the current analyzed-and-rewritten query tree: */
+ List *query_list; /* list of Query nodes, or NIL if not valid */
+ List *relationOids; /* OIDs of relations the queries depend on */
+ List *invalItems; /* other dependencies, as PlanInvalItems */
+ struct OverrideSearchPath *search_path; /* search_path used for parsing
+ * and planning */
+ MemoryContext query_context; /* context holding the above, or NULL */
+ Oid rewriteRoleId; /* Role ID we did rewriting for */
+ bool rewriteRowSecurity; /* row_security used during rewrite */
+ bool dependsOnRLS; /* is rewritten query specific to the above? */
+ /* If we have a generic plan, this is a reference-counted link to it: */
+ struct CachedPlan *gplan; /* generic plan, or NULL if not valid */
+ /* Some state flags: */
+ bool is_oneshot; /* is it a "oneshot" plan? */
+ bool is_complete; /* has CompleteCachedPlan been done? */
+ bool is_saved; /* has CachedPlanSource been "saved"? */
+ bool is_valid; /* is the query_list currently valid? */
+ int generation; /* increments each time we create a plan */
+ /* If CachedPlanSource has been saved, it is a member of a global list */
+ dlist_node node; /* list link, if is_saved */
+ /* State kept to help decide whether to use custom or generic plans: */
+ double generic_cost; /* cost of generic plan, or -1 if not known */
+ double total_custom_cost; /* total cost of custom plans so far */
+ int64 num_custom_plans; /* # of custom plans included in total */
+ int64 num_generic_plans; /* # of generic plans */
+} CachedPlanSource;
+
+/*
+ * CachedPlan represents an execution plan derived from a CachedPlanSource.
+ * The reference count includes both the link from the parent CachedPlanSource
+ * (if any), and any active plan executions, so the plan can be discarded
+ * exactly when refcount goes to zero. Both the struct itself and the
+ * subsidiary data live in the context denoted by the context field.
+ * This makes it easy to free a no-longer-needed cached plan. (However,
+ * if is_oneshot is true, the context does not belong solely to the CachedPlan
+ * so no freeing is possible.)
+ */
+typedef struct CachedPlan
+{
+ int magic; /* should equal CACHEDPLAN_MAGIC */
+ List *stmt_list; /* list of PlannedStmts */
+ bool is_oneshot; /* is it a "oneshot" plan? */
+ bool is_saved; /* is CachedPlan in a long-lived context? */
+ bool is_valid; /* is the stmt_list currently valid? */
+ Oid planRoleId; /* Role ID the plan was created for */
+ bool dependsOnRole; /* is plan specific to that role? */
+ TransactionId saved_xmin; /* if valid, replan when TransactionXmin
+ * changes from this value */
+ int generation; /* parent's generation number for this plan */
+ int refcount; /* count of live references to this struct */
+ MemoryContext context; /* context containing this CachedPlan */
+} CachedPlan;
+
+/*
+ * CachedExpression is a low-overhead mechanism for caching the planned form
+ * of standalone scalar expressions. While such expressions are not usually
+ * subject to cache invalidation events, that can happen, for example because
+ * of replacement of a SQL function that was inlined into the expression.
+ * The plancache takes care of storing the expression tree and marking it
+ * invalid if a cache invalidation occurs, but the caller must notice the
+ * !is_valid status and discard the obsolete expression without reusing it.
+ * We do not store the original parse tree, only the planned expression;
+ * this is an optimization based on the assumption that we usually will not
+ * need to replan for the life of the session.
+ */
+typedef struct CachedExpression
+{
+ int magic; /* should equal CACHEDEXPR_MAGIC */
+ Node *expr; /* planned form of expression */
+ bool is_valid; /* is the expression still valid? */
+ /* remaining fields should be treated as private to plancache.c: */
+ List *relationOids; /* OIDs of relations the expr depends on */
+ List *invalItems; /* other dependencies, as PlanInvalItems */
+ MemoryContext context; /* context containing this CachedExpression */
+ dlist_node node; /* link in global list of CachedExpressions */
+} CachedExpression;
+
+
+extern void InitPlanCache(void);
+extern void ResetPlanCache(void);
+
+extern CachedPlanSource *CreateCachedPlan(struct RawStmt *raw_parse_tree,
+ const char *query_string,
+ CommandTag commandTag);
+extern CachedPlanSource *CreateOneShotCachedPlan(struct RawStmt *raw_parse_tree,
+ const char *query_string,
+ CommandTag commandTag);
+extern void CompleteCachedPlan(CachedPlanSource *plansource,
+ List *querytree_list,
+ MemoryContext querytree_context,
+ Oid *param_types,
+ int num_params,
+ ParserSetupHook parserSetup,
+ void *parserSetupArg,
+ int cursor_options,
+ bool fixed_result);
+
+extern void SaveCachedPlan(CachedPlanSource *plansource);
+extern void DropCachedPlan(CachedPlanSource *plansource);
+
+extern void CachedPlanSetParentContext(CachedPlanSource *plansource,
+ MemoryContext newcontext);
+
+extern CachedPlanSource *CopyCachedPlan(CachedPlanSource *plansource);
+
+extern bool CachedPlanIsValid(CachedPlanSource *plansource);
+
+extern List *CachedPlanGetTargetList(CachedPlanSource *plansource,
+ QueryEnvironment *queryEnv);
+
+extern CachedPlan *GetCachedPlan(CachedPlanSource *plansource,
+ ParamListInfo boundParams,
+ ResourceOwner owner,
+ QueryEnvironment *queryEnv);
+extern void ReleaseCachedPlan(CachedPlan *plan, ResourceOwner owner);
+
+extern bool CachedPlanAllowsSimpleValidityCheck(CachedPlanSource *plansource,
+ CachedPlan *plan,
+ ResourceOwner owner);
+extern bool CachedPlanIsSimplyValid(CachedPlanSource *plansource,
+ CachedPlan *plan,
+ ResourceOwner owner);
+
+extern CachedExpression *GetCachedExpression(Node *expr);
+extern void FreeCachedExpression(CachedExpression *cexpr);
+
+#endif /* PLANCACHE_H */
diff --git a/pgsql/include/server/utils/portal.h b/pgsql/include/server/utils/portal.h
new file mode 100644
index 0000000000000000000000000000000000000000..aa08b1e0fca7d5c9223c2ab167176f88200b76ac
--- /dev/null
+++ b/pgsql/include/server/utils/portal.h
@@ -0,0 +1,252 @@
+/*-------------------------------------------------------------------------
+ *
+ * portal.h
+ * POSTGRES portal definitions.
+ *
+ * A portal is an abstraction which represents the execution state of
+ * a running or runnable query. Portals support both SQL-level CURSORs
+ * and protocol-level portals.
+ *
+ * Scrolling (nonsequential access) and suspension of execution are allowed
+ * only for portals that contain a single SELECT-type query. We do not want
+ * to let the client suspend an update-type query partway through! Because
+ * the query rewriter does not allow arbitrary ON SELECT rewrite rules,
+ * only queries that were originally update-type could produce multiple
+ * plan trees; so the restriction to a single query is not a problem
+ * in practice.
+ *
+ * For SQL cursors, we support three kinds of scroll behavior:
+ *
+ * (1) Neither NO SCROLL nor SCROLL was specified: to remain backward
+ * compatible, we allow backward fetches here, unless it would
+ * impose additional runtime overhead to do so.
+ *
+ * (2) NO SCROLL was specified: don't allow any backward fetches.
+ *
+ * (3) SCROLL was specified: allow all kinds of backward fetches, even
+ * if we need to take a performance hit to do so. (The planner sticks
+ * a Materialize node atop the query plan if needed.)
+ *
+ * Case #1 is converted to #2 or #3 by looking at the query itself and
+ * determining if scrollability can be supported without additional
+ * overhead.
+ *
+ * Protocol-level portals have no nonsequential-fetch API and so the
+ * distinction doesn't matter for them. They are always initialized
+ * to look like NO SCROLL cursors.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/portal.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PORTAL_H
+#define PORTAL_H
+
+#include "datatype/timestamp.h"
+#include "executor/execdesc.h"
+#include "tcop/cmdtag.h"
+#include "utils/plancache.h"
+#include "utils/resowner.h"
+
+/*
+ * We have several execution strategies for Portals, depending on what
+ * query or queries are to be executed. (Note: in all cases, a Portal
+ * executes just a single source-SQL query, and thus produces just a
+ * single result from the user's viewpoint. However, the rule rewriter
+ * may expand the single source query to zero or many actual queries.)
+ *
+ * PORTAL_ONE_SELECT: the portal contains one single SELECT query. We run
+ * the Executor incrementally as results are demanded. This strategy also
+ * supports holdable cursors (the Executor results can be dumped into a
+ * tuplestore for access after transaction completion).
+ *
+ * PORTAL_ONE_RETURNING: the portal contains a single INSERT/UPDATE/DELETE
+ * query with a RETURNING clause (plus possibly auxiliary queries added by
+ * rule rewriting). On first execution, we run the portal to completion
+ * and dump the primary query's results into the portal tuplestore; the
+ * results are then returned to the client as demanded. (We can't support
+ * suspension of the query partway through, because the AFTER TRIGGER code
+ * can't cope, and also because we don't want to risk failing to execute
+ * all the auxiliary queries.)
+ *
+ * PORTAL_ONE_MOD_WITH: the portal contains one single SELECT query, but
+ * it has data-modifying CTEs. This is currently treated the same as the
+ * PORTAL_ONE_RETURNING case because of the possibility of needing to fire
+ * triggers. It may act more like PORTAL_ONE_SELECT in future.
+ *
+ * PORTAL_UTIL_SELECT: the portal contains a utility statement that returns
+ * a SELECT-like result (for example, EXPLAIN or SHOW). On first execution,
+ * we run the statement and dump its results into the portal tuplestore;
+ * the results are then returned to the client as demanded.
+ *
+ * PORTAL_MULTI_QUERY: all other cases. Here, we do not support partial
+ * execution: the portal's queries will be run to completion on first call.
+ */
+typedef enum PortalStrategy
+{
+ PORTAL_ONE_SELECT,
+ PORTAL_ONE_RETURNING,
+ PORTAL_ONE_MOD_WITH,
+ PORTAL_UTIL_SELECT,
+ PORTAL_MULTI_QUERY
+} PortalStrategy;
+
+/*
+ * A portal is always in one of these states. It is possible to transit
+ * from ACTIVE back to READY if the query is not run to completion;
+ * otherwise we never back up in status.
+ */
+typedef enum PortalStatus
+{
+ PORTAL_NEW, /* freshly created */
+ PORTAL_DEFINED, /* PortalDefineQuery done */
+ PORTAL_READY, /* PortalStart complete, can run it */
+ PORTAL_ACTIVE, /* portal is running (can't delete it) */
+ PORTAL_DONE, /* portal is finished (don't re-run it) */
+ PORTAL_FAILED /* portal got error (can't re-run it) */
+} PortalStatus;
+
+typedef struct PortalData *Portal;
+
+typedef struct PortalData
+{
+ /* Bookkeeping data */
+ const char *name; /* portal's name */
+ const char *prepStmtName; /* source prepared statement (NULL if none) */
+ MemoryContext portalContext; /* subsidiary memory for portal */
+ ResourceOwner resowner; /* resources owned by portal */
+ void (*cleanup) (Portal portal); /* cleanup hook */
+
+ /*
+ * State data for remembering which subtransaction(s) the portal was
+ * created or used in. If the portal is held over from a previous
+ * transaction, both subxids are InvalidSubTransactionId. Otherwise,
+ * createSubid is the creating subxact and activeSubid is the last subxact
+ * in which we ran the portal.
+ */
+ SubTransactionId createSubid; /* the creating subxact */
+ SubTransactionId activeSubid; /* the last subxact with activity */
+ int createLevel; /* creating subxact's nesting level */
+
+ /* The query or queries the portal will execute */
+ const char *sourceText; /* text of query (as of 8.4, never NULL) */
+ CommandTag commandTag; /* command tag for original query */
+ QueryCompletion qc; /* command completion data for executed query */
+ List *stmts; /* list of PlannedStmts */
+ CachedPlan *cplan; /* CachedPlan, if stmts are from one */
+
+ ParamListInfo portalParams; /* params to pass to query */
+ QueryEnvironment *queryEnv; /* environment for query */
+
+ /* Features/options */
+ PortalStrategy strategy; /* see above */
+ int cursorOptions; /* DECLARE CURSOR option bits */
+ bool run_once; /* portal will only be run once */
+
+ /* Status data */
+ PortalStatus status; /* see above */
+ bool portalPinned; /* a pinned portal can't be dropped */
+ bool autoHeld; /* was automatically converted from pinned to
+ * held (see HoldPinnedPortals()) */
+
+ /* If not NULL, Executor is active; call ExecutorEnd eventually: */
+ QueryDesc *queryDesc; /* info needed for executor invocation */
+
+ /* If portal returns tuples, this is their tupdesc: */
+ TupleDesc tupDesc; /* descriptor for result tuples */
+ /* and these are the format codes to use for the columns: */
+ int16 *formats; /* a format code for each column */
+
+ /*
+ * Outermost ActiveSnapshot for execution of the portal's queries. For
+ * all but a few utility commands, we require such a snapshot to exist.
+ * This ensures that TOAST references in query results can be detoasted,
+ * and helps to reduce thrashing of the process's exposed xmin.
+ */
+ Snapshot portalSnapshot; /* active snapshot, or NULL if none */
+
+ /*
+ * Where we store tuples for a held cursor or a PORTAL_ONE_RETURNING or
+ * PORTAL_UTIL_SELECT query. (A cursor held past the end of its
+ * transaction no longer has any active executor state.)
+ */
+ Tuplestorestate *holdStore; /* store for holdable cursors */
+ MemoryContext holdContext; /* memory containing holdStore */
+
+ /*
+ * Snapshot under which tuples in the holdStore were read. We must keep a
+ * reference to this snapshot if there is any possibility that the tuples
+ * contain TOAST references, because releasing the snapshot could allow
+ * recently-dead rows to be vacuumed away, along with any toast data
+ * belonging to them. In the case of a held cursor, we avoid needing to
+ * keep such a snapshot by forcibly detoasting the data.
+ */
+ Snapshot holdSnapshot; /* registered snapshot, or NULL if none */
+
+ /*
+ * atStart, atEnd and portalPos indicate the current cursor position.
+ * portalPos is zero before the first row, N after fetching N'th row of
+ * query. After we run off the end, portalPos = # of rows in query, and
+ * atEnd is true. Note that atStart implies portalPos == 0, but not the
+ * reverse: we might have backed up only as far as the first row, not to
+ * the start. Also note that various code inspects atStart and atEnd, but
+ * only the portal movement routines should touch portalPos.
+ */
+ bool atStart;
+ bool atEnd;
+ uint64 portalPos;
+
+ /* Presentation data, primarily used by the pg_cursors system view */
+ TimestampTz creation_time; /* time at which this portal was defined */
+ bool visible; /* include this portal in pg_cursors? */
+} PortalData;
+
+/*
+ * PortalIsValid
+ * True iff portal is valid.
+ */
+#define PortalIsValid(p) PointerIsValid(p)
+
+
+/* Prototypes for functions in utils/mmgr/portalmem.c */
+extern void EnablePortalManager(void);
+extern bool PreCommit_Portals(bool isPrepare);
+extern void AtAbort_Portals(void);
+extern void AtCleanup_Portals(void);
+extern void PortalErrorCleanup(void);
+extern void AtSubCommit_Portals(SubTransactionId mySubid,
+ SubTransactionId parentSubid,
+ int parentLevel,
+ ResourceOwner parentXactOwner);
+extern void AtSubAbort_Portals(SubTransactionId mySubid,
+ SubTransactionId parentSubid,
+ ResourceOwner myXactOwner,
+ ResourceOwner parentXactOwner);
+extern void AtSubCleanup_Portals(SubTransactionId mySubid);
+extern Portal CreatePortal(const char *name, bool allowDup, bool dupSilent);
+extern Portal CreateNewPortal(void);
+extern void PinPortal(Portal portal);
+extern void UnpinPortal(Portal portal);
+extern void MarkPortalActive(Portal portal);
+extern void MarkPortalDone(Portal portal);
+extern void MarkPortalFailed(Portal portal);
+extern void PortalDrop(Portal portal, bool isTopCommit);
+extern Portal GetPortalByName(const char *name);
+extern void PortalDefineQuery(Portal portal,
+ const char *prepStmtName,
+ const char *sourceText,
+ CommandTag commandTag,
+ List *stmts,
+ CachedPlan *cplan);
+extern PlannedStmt *PortalGetPrimaryStmt(Portal portal);
+extern void PortalCreateHoldStore(Portal portal);
+extern void PortalHashTableDeleteAll(void);
+extern bool ThereAreNoReadyPortals(void);
+extern void HoldPinnedPortals(void);
+extern void ForgetPortalSnapshots(void);
+
+#endif /* PORTAL_H */
diff --git a/pgsql/include/server/utils/probes.h b/pgsql/include/server/utils/probes.h
new file mode 100644
index 0000000000000000000000000000000000000000..d0cc274aeb7ba3ddad5fd7e138b83882889be0c6
--- /dev/null
+++ b/pgsql/include/server/utils/probes.h
@@ -0,0 +1,114 @@
+#define TRACE_POSTGRESQL_TRANSACTION_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_TRANSACTION_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_TRANSACTION_COMMIT(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_TRANSACTION_COMMIT_ENABLED() (0)
+#define TRACE_POSTGRESQL_TRANSACTION_ABORT(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_TRANSACTION_ABORT_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_ACQUIRE(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_ACQUIRE_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_RELEASE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_RELEASE_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_WAIT_START(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_WAIT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_WAIT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_ENABLED() (0)
+#define TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL_ENABLED() (0)
+#define TRACE_POSTGRESQL_LOCK_WAIT_START(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_LOCK_WAIT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_LOCK_WAIT_DONE(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_LOCK_WAIT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_PARSE_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_PARSE_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_PARSE_DONE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_PARSE_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_REWRITE_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_REWRITE_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_REWRITE_DONE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_REWRITE_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_PLAN_START() do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_PLAN_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_PLAN_DONE() do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_PLAN_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_EXECUTE_START() do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_EXECUTE_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_EXECUTE_DONE() do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_EXECUTE_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_QUERY_DONE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_QUERY_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_STATEMENT_STATUS(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_STATEMENT_STATUS_ENABLED() (0)
+#define TRACE_POSTGRESQL_SORT_START(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_SORT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_SORT_DONE(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_SORT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_READ_START(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_READ_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_READ_DONE(INT1, INT2, INT3, INT4, INT5, INT6, INT7) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_READ_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_FLUSH_START(INT1, INT2, INT3, INT4, INT5) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_FLUSH_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(INT1, INT2, INT3, INT4, INT5) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_FLUSH_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_EXTEND_START(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_EXTEND_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_EXTEND_DONE(INT1, INT2, INT3, INT4, INT5, INT6, INT7) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_EXTEND_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START() do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE() do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_SYNC_START(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_SYNC_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN_ENABLED() (0)
+#define TRACE_POSTGRESQL_BUFFER_SYNC_DONE(INT1, INT2, INT3) do {} while (0)
+#define TRACE_POSTGRESQL_BUFFER_SYNC_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_DEADLOCK_FOUND() do {} while (0)
+#define TRACE_POSTGRESQL_DEADLOCK_FOUND_ENABLED() (0)
+#define TRACE_POSTGRESQL_CHECKPOINT_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_CHECKPOINT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_CHECKPOINT_DONE(INT1, INT2, INT3, INT4, INT5) do {} while (0)
+#define TRACE_POSTGRESQL_CHECKPOINT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_CLOG_CHECKPOINT_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_CLOG_CHECKPOINT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_CLOG_CHECKPOINT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_SUBTRANS_CHECKPOINT_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_SUBTRANS_CHECKPOINT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_SUBTRANS_CHECKPOINT_DONE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_SUBTRANS_CHECKPOINT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE(INT1) do {} while (0)
+#define TRACE_POSTGRESQL_MULTIXACT_CHECKPOINT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START() do {} while (0)
+#define TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE() do {} while (0)
+#define TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_SMGR_MD_READ_START(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_SMGR_MD_READ_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_SMGR_MD_READ_DONE(INT1, INT2, INT3, INT4, INT5, INT6, INT7, INT8) do {} while (0)
+#define TRACE_POSTGRESQL_SMGR_MD_READ_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_SMGR_MD_WRITE_START(INT1, INT2, INT3, INT4, INT5, INT6) do {} while (0)
+#define TRACE_POSTGRESQL_SMGR_MD_WRITE_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(INT1, INT2, INT3, INT4, INT5, INT6, INT7, INT8) do {} while (0)
+#define TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE_ENABLED() (0)
+#define TRACE_POSTGRESQL_WAL_INSERT(INT1, INT2) do {} while (0)
+#define TRACE_POSTGRESQL_WAL_INSERT_ENABLED() (0)
+#define TRACE_POSTGRESQL_WAL_SWITCH() do {} while (0)
+#define TRACE_POSTGRESQL_WAL_SWITCH_ENABLED() (0)
+#define TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START() do {} while (0)
+#define TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START_ENABLED() (0)
+#define TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE() do {} while (0)
+#define TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE_ENABLED() (0)
diff --git a/pgsql/include/server/utils/ps_status.h b/pgsql/include/server/utils/ps_status.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff5a2b2b8a2274c562c3b2ef62d0011d3591a0b4
--- /dev/null
+++ b/pgsql/include/server/utils/ps_status.h
@@ -0,0 +1,47 @@
+/*-------------------------------------------------------------------------
+ *
+ * ps_status.h
+ *
+ * Declarations for backend/utils/misc/ps_status.c
+ *
+ * src/include/utils/ps_status.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef PS_STATUS_H
+#define PS_STATUS_H
+
+/* disabled on Windows as the performance overhead can be significant */
+#ifdef WIN32
+#define DEFAULT_UPDATE_PROCESS_TITLE false
+#else
+#define DEFAULT_UPDATE_PROCESS_TITLE true
+#endif
+
+extern PGDLLIMPORT bool update_process_title;
+
+extern char **save_ps_display_args(int argc, char **argv);
+
+extern void init_ps_display(const char *fixed_part);
+
+extern void set_ps_display_suffix(const char *suffix);
+
+extern void set_ps_display_remove_suffix(void);
+
+extern void set_ps_display_with_len(const char *activity, size_t len);
+
+/*
+ * set_ps_display
+ * inlined to allow strlen to be evaluated during compilation when
+ * passing string constants.
+ */
+static inline void
+set_ps_display(const char *activity)
+{
+ set_ps_display_with_len(activity, strlen(activity));
+}
+
+extern const char *get_ps_display(int *displen);
+
+#endif /* PS_STATUS_H */
diff --git a/pgsql/include/server/utils/queryenvironment.h b/pgsql/include/server/utils/queryenvironment.h
new file mode 100644
index 0000000000000000000000000000000000000000..532219ade23925beb37c67cccf24aa7f780ca4cb
--- /dev/null
+++ b/pgsql/include/server/utils/queryenvironment.h
@@ -0,0 +1,74 @@
+/*-------------------------------------------------------------------------
+ *
+ * queryenvironment.h
+ * Access to functions to mutate the query environment and retrieve the
+ * actual data related to entries (if any).
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/queryenvironment.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef QUERYENVIRONMENT_H
+#define QUERYENVIRONMENT_H
+
+#include "access/tupdesc.h"
+
+
+typedef enum EphemeralNameRelationType
+{
+ ENR_NAMED_TUPLESTORE /* named tuplestore relation; e.g., deltas */
+} EphemeralNameRelationType;
+
+/*
+ * Some ephemeral named relations must match some relation (e.g., trigger
+ * transition tables), so to properly handle cached plans and DDL, we should
+ * carry the OID of that relation. In other cases an ENR might be independent
+ * of any relation which is stored in the system catalogs, so we need to be
+ * able to directly store the TupleDesc. We never need both.
+ */
+typedef struct EphemeralNamedRelationMetadataData
+{
+ char *name; /* name used to identify the relation */
+
+ /* only one of the next two fields should be used */
+ Oid reliddesc; /* oid of relation to get tupdesc */
+ TupleDesc tupdesc; /* description of result rows */
+
+ EphemeralNameRelationType enrtype; /* to identify type of relation */
+ double enrtuples; /* estimated number of tuples */
+} EphemeralNamedRelationMetadataData;
+
+typedef EphemeralNamedRelationMetadataData *EphemeralNamedRelationMetadata;
+
+/*
+ * Ephemeral Named Relation data; used for parsing named relations not in the
+ * catalog, like transition tables in AFTER triggers.
+ */
+typedef struct EphemeralNamedRelationData
+{
+ EphemeralNamedRelationMetadataData md;
+ void *reldata; /* structure for execution-time access to data */
+} EphemeralNamedRelationData;
+
+typedef EphemeralNamedRelationData *EphemeralNamedRelation;
+
+/*
+ * This is an opaque structure outside of queryenvironment.c itself. The
+ * intention is to be able to change the implementation or add new context
+ * features without needing to change existing code for use of existing
+ * features.
+ */
+typedef struct QueryEnvironment QueryEnvironment;
+
+
+extern QueryEnvironment *create_queryEnv(void);
+extern EphemeralNamedRelationMetadata get_visible_ENR_metadata(QueryEnvironment *queryEnv, const char *refname);
+extern void register_ENR(QueryEnvironment *queryEnv, EphemeralNamedRelation enr);
+extern void unregister_ENR(QueryEnvironment *queryEnv, const char *name);
+extern EphemeralNamedRelation get_ENR(QueryEnvironment *queryEnv, const char *name);
+extern TupleDesc ENRMetadataGetTupDesc(EphemeralNamedRelationMetadata enrmd);
+
+#endif /* QUERYENVIRONMENT_H */
diff --git a/pgsql/include/server/utils/rangetypes.h b/pgsql/include/server/utils/rangetypes.h
new file mode 100644
index 0000000000000000000000000000000000000000..6b420a8618d5554b40472aefd888ab1204f1d270
--- /dev/null
+++ b/pgsql/include/server/utils/rangetypes.h
@@ -0,0 +1,168 @@
+/*-------------------------------------------------------------------------
+ *
+ * rangetypes.h
+ * Declarations for Postgres range types.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/rangetypes.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RANGETYPES_H
+#define RANGETYPES_H
+
+#include "utils/typcache.h"
+
+
+/*
+ * Ranges are varlena objects, so must meet the varlena convention that
+ * the first int32 of the object contains the total object size in bytes.
+ * Be sure to use VARSIZE() and SET_VARSIZE() to access it, though!
+ */
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ Oid rangetypid; /* range type's own OID */
+ /* Following the OID are zero to two bound values, then a flags byte */
+} RangeType;
+
+#define RANGE_EMPTY_LITERAL "empty"
+
+/* Use this macro in preference to fetching rangetypid field directly */
+#define RangeTypeGetOid(r) ((r)->rangetypid)
+
+/* A range's flags byte contains these bits: */
+#define RANGE_EMPTY 0x01 /* range is empty */
+#define RANGE_LB_INC 0x02 /* lower bound is inclusive */
+#define RANGE_UB_INC 0x04 /* upper bound is inclusive */
+#define RANGE_LB_INF 0x08 /* lower bound is -infinity */
+#define RANGE_UB_INF 0x10 /* upper bound is +infinity */
+#define RANGE_LB_NULL 0x20 /* lower bound is null (NOT USED) */
+#define RANGE_UB_NULL 0x40 /* upper bound is null (NOT USED) */
+#define RANGE_CONTAIN_EMPTY 0x80 /* marks a GiST internal-page entry whose
+ * subtree contains some empty ranges */
+
+#define RANGE_HAS_LBOUND(flags) (!((flags) & (RANGE_EMPTY | \
+ RANGE_LB_NULL | \
+ RANGE_LB_INF)))
+
+#define RANGE_HAS_UBOUND(flags) (!((flags) & (RANGE_EMPTY | \
+ RANGE_UB_NULL | \
+ RANGE_UB_INF)))
+
+#define RangeIsEmpty(r) ((range_get_flags(r) & RANGE_EMPTY) != 0)
+#define RangeIsOrContainsEmpty(r) \
+ ((range_get_flags(r) & (RANGE_EMPTY | RANGE_CONTAIN_EMPTY)) != 0)
+
+
+/* Internal representation of either bound of a range (not what's on disk) */
+typedef struct
+{
+ Datum val; /* the bound value, if any */
+ bool infinite; /* bound is +/- infinity */
+ bool inclusive; /* bound is inclusive (vs exclusive) */
+ bool lower; /* this is the lower (vs upper) bound */
+} RangeBound;
+
+/*
+ * fmgr functions for range type objects
+ */
+static inline RangeType *
+DatumGetRangeTypeP(Datum X)
+{
+ return (RangeType *) PG_DETOAST_DATUM(X);
+}
+
+static inline RangeType *
+DatumGetRangeTypePCopy(Datum X)
+{
+ return (RangeType *) PG_DETOAST_DATUM_COPY(X);
+}
+
+static inline Datum
+RangeTypePGetDatum(const RangeType *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_RANGE_P(n) DatumGetRangeTypeP(PG_GETARG_DATUM(n))
+#define PG_GETARG_RANGE_P_COPY(n) DatumGetRangeTypePCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_RANGE_P(x) return RangeTypePGetDatum(x)
+
+/* Operator strategy numbers used in the GiST and SP-GiST range opclasses */
+/* Numbers are chosen to match up operator names with existing usages */
+#define RANGESTRAT_BEFORE RTLeftStrategyNumber
+#define RANGESTRAT_OVERLEFT RTOverLeftStrategyNumber
+#define RANGESTRAT_OVERLAPS RTOverlapStrategyNumber
+#define RANGESTRAT_OVERRIGHT RTOverRightStrategyNumber
+#define RANGESTRAT_AFTER RTRightStrategyNumber
+#define RANGESTRAT_ADJACENT RTSameStrategyNumber
+#define RANGESTRAT_CONTAINS RTContainsStrategyNumber
+#define RANGESTRAT_CONTAINED_BY RTContainedByStrategyNumber
+#define RANGESTRAT_CONTAINS_ELEM RTContainsElemStrategyNumber
+#define RANGESTRAT_EQ RTEqualStrategyNumber
+
+/*
+ * prototypes for functions defined in rangetypes.c
+ */
+
+extern bool range_contains_elem_internal(TypeCacheEntry *typcache, const RangeType *r, Datum val);
+
+/* internal versions of the above */
+extern bool range_eq_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_ne_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_contains_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_contained_by_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_before_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_after_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_adjacent_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_overlaps_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_overleft_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern bool range_overright_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+extern RangeType *range_union_internal(TypeCacheEntry *typcache, RangeType *r1,
+ RangeType *r2, bool strict);
+extern RangeType *range_minus_internal(TypeCacheEntry *typcache, RangeType *r1,
+ RangeType *r2);
+extern RangeType *range_intersect_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2);
+
+/* assorted support functions */
+extern TypeCacheEntry *range_get_typcache(FunctionCallInfo fcinfo,
+ Oid rngtypid);
+extern RangeType *range_serialize(TypeCacheEntry *typcache, RangeBound *lower,
+ RangeBound *upper, bool empty,
+ struct Node *escontext);
+extern void range_deserialize(TypeCacheEntry *typcache, const RangeType *range,
+ RangeBound *lower, RangeBound *upper,
+ bool *empty);
+extern char range_get_flags(const RangeType *range);
+extern void range_set_contain_empty(RangeType *range);
+extern RangeType *make_range(TypeCacheEntry *typcache, RangeBound *lower,
+ RangeBound *upper, bool empty,
+ struct Node *escontext);
+extern int range_cmp_bounds(TypeCacheEntry *typcache, const RangeBound *b1,
+ const RangeBound *b2);
+extern int range_cmp_bound_values(TypeCacheEntry *typcache, const RangeBound *b1,
+ const RangeBound *b2);
+extern int range_compare(const void *key1, const void *key2, void *arg);
+extern bool bounds_adjacent(TypeCacheEntry *typcache, RangeBound boundA,
+ RangeBound boundB);
+extern RangeType *make_empty_range(TypeCacheEntry *typcache);
+extern bool range_split_internal(TypeCacheEntry *typcache, const RangeType *r1,
+ const RangeType *r2, RangeType **output1,
+ RangeType **output2);
+
+#endif /* RANGETYPES_H */
diff --git a/pgsql/include/server/utils/regproc.h b/pgsql/include/server/utils/regproc.h
new file mode 100644
index 0000000000000000000000000000000000000000..a1f7c6b0cdc3e3835233fc975945f16aafb0e8be
--- /dev/null
+++ b/pgsql/include/server/utils/regproc.h
@@ -0,0 +1,39 @@
+/*-------------------------------------------------------------------------
+ *
+ * regproc.h
+ * Functions for the built-in types regproc, regclass, regtype, etc.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/regproc.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REGPROC_H
+#define REGPROC_H
+
+#include "nodes/pg_list.h"
+
+/* Control flags for format_procedure_extended */
+#define FORMAT_PROC_INVALID_AS_NULL 0x01 /* NULL if undefined */
+#define FORMAT_PROC_FORCE_QUALIFY 0x02 /* force qualification */
+extern char *format_procedure_extended(Oid procedure_oid, bits16 flags);
+
+/* Control flags for format_operator_extended */
+#define FORMAT_OPERATOR_INVALID_AS_NULL 0x01 /* NULL if undefined */
+#define FORMAT_OPERATOR_FORCE_QUALIFY 0x02 /* force qualification */
+extern char *format_operator_extended(Oid operator_oid, bits16 flags);
+
+extern List *stringToQualifiedNameList(const char *string, Node *escontext);
+extern char *format_procedure(Oid procedure_oid);
+extern char *format_procedure_qualified(Oid procedure_oid);
+extern void format_procedure_parts(Oid procedure_oid, List **objnames,
+ List **objargs, bool missing_ok);
+
+extern char *format_operator(Oid operator_oid);
+extern char *format_operator_qualified(Oid operator_oid);
+extern void format_operator_parts(Oid operator_oid, List **objnames,
+ List **objargs, bool missing_ok);
+
+#endif
diff --git a/pgsql/include/server/utils/rel.h b/pgsql/include/server/utils/rel.h
new file mode 100644
index 0000000000000000000000000000000000000000..1426a353cd01c91b981e968b01a6713dbeebd807
--- /dev/null
+++ b/pgsql/include/server/utils/rel.h
@@ -0,0 +1,712 @@
+/*-------------------------------------------------------------------------
+ *
+ * rel.h
+ * POSTGRES relation descriptor (a/k/a relcache entry) definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/rel.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef REL_H
+#define REL_H
+
+#include "access/tupdesc.h"
+#include "access/xlog.h"
+#include "catalog/catalog.h"
+#include "catalog/pg_class.h"
+#include "catalog/pg_index.h"
+#include "catalog/pg_publication.h"
+#include "nodes/bitmapset.h"
+#include "partitioning/partdefs.h"
+#include "rewrite/prs2lock.h"
+#include "storage/block.h"
+#include "storage/relfilelocator.h"
+#include "storage/smgr.h"
+#include "utils/relcache.h"
+#include "utils/reltrigger.h"
+
+
+/*
+ * LockRelId and LockInfo really belong to lmgr.h, but it's more convenient
+ * to declare them here so we can have a LockInfoData field in a Relation.
+ */
+
+typedef struct LockRelId
+{
+ Oid relId; /* a relation identifier */
+ Oid dbId; /* a database identifier */
+} LockRelId;
+
+typedef struct LockInfoData
+{
+ LockRelId lockRelId;
+} LockInfoData;
+
+typedef LockInfoData *LockInfo;
+
+/*
+ * Here are the contents of a relation cache entry.
+ */
+
+typedef struct RelationData
+{
+ RelFileLocator rd_locator; /* relation physical identifier */
+ SMgrRelation rd_smgr; /* cached file handle, or NULL */
+ int rd_refcnt; /* reference count */
+ BackendId rd_backend; /* owning backend id, if temporary relation */
+ bool rd_islocaltemp; /* rel is a temp rel of this session */
+ bool rd_isnailed; /* rel is nailed in cache */
+ bool rd_isvalid; /* relcache entry is valid */
+ bool rd_indexvalid; /* is rd_indexlist valid? (also rd_pkindex and
+ * rd_replidindex) */
+ bool rd_statvalid; /* is rd_statlist valid? */
+
+ /*----------
+ * rd_createSubid is the ID of the highest subtransaction the rel has
+ * survived into or zero if the rel or its storage was created before the
+ * current top transaction. (IndexStmt.oldNumber leads to the case of a new
+ * rel with an old rd_locator.) rd_firstRelfilelocatorSubid is the ID of the
+ * highest subtransaction an rd_locator change has survived into or zero if
+ * rd_locator matches the value it had at the start of the current top
+ * transaction. (Rolling back the subtransaction that
+ * rd_firstRelfilelocatorSubid denotes would restore rd_locator to the value it
+ * had at the start of the current top transaction. Rolling back any
+ * lower subtransaction would not.) Their accuracy is critical to
+ * RelationNeedsWAL().
+ *
+ * rd_newRelfilelocatorSubid is the ID of the highest subtransaction the
+ * most-recent relfilenumber change has survived into or zero if not changed
+ * in the current transaction (or we have forgotten changing it). This
+ * field is accurate when non-zero, but it can be zero when a relation has
+ * multiple new relfilenumbers within a single transaction, with one of them
+ * occurring in a subsequently aborted subtransaction, e.g.
+ * BEGIN;
+ * TRUNCATE t;
+ * SAVEPOINT save;
+ * TRUNCATE t;
+ * ROLLBACK TO save;
+ * -- rd_newRelfilelocatorSubid is now forgotten
+ *
+ * If every rd_*Subid field is zero, they are read-only outside
+ * relcache.c. Files that trigger rd_locator changes by updating
+ * pg_class.reltablespace and/or pg_class.relfilenode call
+ * RelationAssumeNewRelfilelocator() to update rd_*Subid.
+ *
+ * rd_droppedSubid is the ID of the highest subtransaction that a drop of
+ * the rel has survived into. In entries visible outside relcache.c, this
+ * is always zero.
+ */
+ SubTransactionId rd_createSubid; /* rel was created in current xact */
+ SubTransactionId rd_newRelfilelocatorSubid; /* highest subxact changing
+ * rd_locator to current value */
+ SubTransactionId rd_firstRelfilelocatorSubid; /* highest subxact
+ * changing rd_locator to
+ * any value */
+ SubTransactionId rd_droppedSubid; /* dropped with another Subid set */
+
+ Form_pg_class rd_rel; /* RELATION tuple */
+ TupleDesc rd_att; /* tuple descriptor */
+ Oid rd_id; /* relation's object id */
+ LockInfoData rd_lockInfo; /* lock mgr's info for locking relation */
+ RuleLock *rd_rules; /* rewrite rules */
+ MemoryContext rd_rulescxt; /* private memory cxt for rd_rules, if any */
+ TriggerDesc *trigdesc; /* Trigger info, or NULL if rel has none */
+ /* use "struct" here to avoid needing to include rowsecurity.h: */
+ struct RowSecurityDesc *rd_rsdesc; /* row security policies, or NULL */
+
+ /* data managed by RelationGetFKeyList: */
+ List *rd_fkeylist; /* list of ForeignKeyCacheInfo (see below) */
+ bool rd_fkeyvalid; /* true if list has been computed */
+
+ /* data managed by RelationGetPartitionKey: */
+ PartitionKey rd_partkey; /* partition key, or NULL */
+ MemoryContext rd_partkeycxt; /* private context for rd_partkey, if any */
+
+ /* data managed by RelationGetPartitionDesc: */
+ PartitionDesc rd_partdesc; /* partition descriptor, or NULL */
+ MemoryContext rd_pdcxt; /* private context for rd_partdesc, if any */
+
+ /* Same as above, for partdescs that omit detached partitions */
+ PartitionDesc rd_partdesc_nodetached; /* partdesc w/o detached parts */
+ MemoryContext rd_pddcxt; /* for rd_partdesc_nodetached, if any */
+
+ /*
+ * pg_inherits.xmin of the partition that was excluded in
+ * rd_partdesc_nodetached. This informs a future user of that partdesc:
+ * if this value is not in progress for the active snapshot, then the
+ * partdesc can be used, otherwise they have to build a new one. (This
+ * matches what find_inheritance_children_extended would do).
+ */
+ TransactionId rd_partdesc_nodetached_xmin;
+
+ /* data managed by RelationGetPartitionQual: */
+ List *rd_partcheck; /* partition CHECK quals */
+ bool rd_partcheckvalid; /* true if list has been computed */
+ MemoryContext rd_partcheckcxt; /* private cxt for rd_partcheck, if any */
+
+ /* data managed by RelationGetIndexList: */
+ List *rd_indexlist; /* list of OIDs of indexes on relation */
+ Oid rd_pkindex; /* OID of primary key, if any */
+ Oid rd_replidindex; /* OID of replica identity index, if any */
+
+ /* data managed by RelationGetStatExtList: */
+ List *rd_statlist; /* list of OIDs of extended stats */
+
+ /* data managed by RelationGetIndexAttrBitmap: */
+ bool rd_attrsvalid; /* are bitmaps of attrs valid? */
+ Bitmapset *rd_keyattr; /* cols that can be ref'd by foreign keys */
+ Bitmapset *rd_pkattr; /* cols included in primary key */
+ Bitmapset *rd_idattr; /* included in replica identity index */
+ Bitmapset *rd_hotblockingattr; /* cols blocking HOT update */
+ Bitmapset *rd_summarizedattr; /* cols indexed by summarizing indexes */
+
+ PublicationDesc *rd_pubdesc; /* publication descriptor, or NULL */
+
+ /*
+ * rd_options is set whenever rd_rel is loaded into the relcache entry.
+ * Note that you can NOT look into rd_rel for this data. NULL means "use
+ * defaults".
+ */
+ bytea *rd_options; /* parsed pg_class.reloptions */
+
+ /*
+ * Oid of the handler for this relation. For an index this is a function
+ * returning IndexAmRoutine, for table like relations a function returning
+ * TableAmRoutine. This is stored separately from rd_indam, rd_tableam as
+ * its lookup requires syscache access, but during relcache bootstrap we
+ * need to be able to initialize rd_tableam without syscache lookups.
+ */
+ Oid rd_amhandler; /* OID of index AM's handler function */
+
+ /*
+ * Table access method.
+ */
+ const struct TableAmRoutine *rd_tableam;
+
+ /* These are non-NULL only for an index relation: */
+ Form_pg_index rd_index; /* pg_index tuple describing this index */
+ /* use "struct" here to avoid needing to include htup.h: */
+ struct HeapTupleData *rd_indextuple; /* all of pg_index tuple */
+
+ /*
+ * index access support info (used only for an index relation)
+ *
+ * Note: only default support procs for each opclass are cached, namely
+ * those with lefttype and righttype equal to the opclass's opcintype. The
+ * arrays are indexed by support function number, which is a sufficient
+ * identifier given that restriction.
+ */
+ MemoryContext rd_indexcxt; /* private memory cxt for this stuff */
+ /* use "struct" here to avoid needing to include amapi.h: */
+ struct IndexAmRoutine *rd_indam; /* index AM's API struct */
+ Oid *rd_opfamily; /* OIDs of op families for each index col */
+ Oid *rd_opcintype; /* OIDs of opclass declared input data types */
+ RegProcedure *rd_support; /* OIDs of support procedures */
+ struct FmgrInfo *rd_supportinfo; /* lookup info for support procedures */
+ int16 *rd_indoption; /* per-column AM-specific flags */
+ List *rd_indexprs; /* index expression trees, if any */
+ List *rd_indpred; /* index predicate tree, if any */
+ Oid *rd_exclops; /* OIDs of exclusion operators, if any */
+ Oid *rd_exclprocs; /* OIDs of exclusion ops' procs, if any */
+ uint16 *rd_exclstrats; /* exclusion ops' strategy numbers, if any */
+ Oid *rd_indcollation; /* OIDs of index collations */
+ bytea **rd_opcoptions; /* parsed opclass-specific options */
+
+ /*
+ * rd_amcache is available for index and table AMs to cache private data
+ * about the relation. This must be just a cache since it may get reset
+ * at any time (in particular, it will get reset by a relcache inval
+ * message for the relation). If used, it must point to a single memory
+ * chunk palloc'd in CacheMemoryContext, or in rd_indexcxt for an index
+ * relation. A relcache reset will include freeing that chunk and setting
+ * rd_amcache = NULL.
+ */
+ void *rd_amcache; /* available for use by index/table AM */
+
+ /*
+ * foreign-table support
+ *
+ * rd_fdwroutine must point to a single memory chunk palloc'd in
+ * CacheMemoryContext. It will be freed and reset to NULL on a relcache
+ * reset.
+ */
+
+ /* use "struct" here to avoid needing to include fdwapi.h: */
+ struct FdwRoutine *rd_fdwroutine; /* cached function pointers, or NULL */
+
+ /*
+ * Hack for CLUSTER, rewriting ALTER TABLE, etc: when writing a new
+ * version of a table, we need to make any toast pointers inserted into it
+ * have the existing toast table's OID, not the OID of the transient toast
+ * table. If rd_toastoid isn't InvalidOid, it is the OID to place in
+ * toast pointers inserted into this rel. (Note it's set on the new
+ * version of the main heap, not the toast table itself.) This also
+ * causes toast_save_datum() to try to preserve toast value OIDs.
+ */
+ Oid rd_toastoid; /* Real TOAST table's OID, or InvalidOid */
+
+ bool pgstat_enabled; /* should relation stats be counted */
+ /* use "struct" here to avoid needing to include pgstat.h: */
+ struct PgStat_TableStatus *pgstat_info; /* statistics collection area */
+} RelationData;
+
+
+/*
+ * ForeignKeyCacheInfo
+ * Information the relcache can cache about foreign key constraints
+ *
+ * This is basically just an image of relevant columns from pg_constraint.
+ * We make it a subclass of Node so that copyObject() can be used on a list
+ * of these, but we also ensure it is a "flat" object without substructure,
+ * so that list_free_deep() is sufficient to free such a list.
+ * The per-FK-column arrays can be fixed-size because we allow at most
+ * INDEX_MAX_KEYS columns in a foreign key constraint.
+ *
+ * Currently, we mostly cache fields of interest to the planner, but the set
+ * of fields has already grown the constraint OID for other uses.
+ */
+typedef struct ForeignKeyCacheInfo
+{
+ pg_node_attr(no_equal, no_read, no_query_jumble)
+
+ NodeTag type;
+ /* oid of the constraint itself */
+ Oid conoid;
+ /* relation constrained by the foreign key */
+ Oid conrelid;
+ /* relation referenced by the foreign key */
+ Oid confrelid;
+ /* number of columns in the foreign key */
+ int nkeys;
+
+ /*
+ * these arrays each have nkeys valid entries:
+ */
+ /* cols in referencing table */
+ AttrNumber conkey[INDEX_MAX_KEYS] pg_node_attr(array_size(nkeys));
+ /* cols in referenced table */
+ AttrNumber confkey[INDEX_MAX_KEYS] pg_node_attr(array_size(nkeys));
+ /* PK = FK operator OIDs */
+ Oid conpfeqop[INDEX_MAX_KEYS] pg_node_attr(array_size(nkeys));
+} ForeignKeyCacheInfo;
+
+
+/*
+ * StdRdOptions
+ * Standard contents of rd_options for heaps.
+ *
+ * RelationGetFillFactor() and RelationGetTargetPageFreeSpace() can only
+ * be applied to relations that use this format or a superset for
+ * private options data.
+ */
+ /* autovacuum-related reloptions. */
+typedef struct AutoVacOpts
+{
+ bool enabled;
+ int vacuum_threshold;
+ int vacuum_ins_threshold;
+ int analyze_threshold;
+ int vacuum_cost_limit;
+ int freeze_min_age;
+ int freeze_max_age;
+ int freeze_table_age;
+ int multixact_freeze_min_age;
+ int multixact_freeze_max_age;
+ int multixact_freeze_table_age;
+ int log_min_duration;
+ float8 vacuum_cost_delay;
+ float8 vacuum_scale_factor;
+ float8 vacuum_ins_scale_factor;
+ float8 analyze_scale_factor;
+} AutoVacOpts;
+
+/* StdRdOptions->vacuum_index_cleanup values */
+typedef enum StdRdOptIndexCleanup
+{
+ STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO = 0,
+ STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF,
+ STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON
+} StdRdOptIndexCleanup;
+
+typedef struct StdRdOptions
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int fillfactor; /* page fill factor in percent (0..100) */
+ int toast_tuple_target; /* target for tuple toasting */
+ AutoVacOpts autovacuum; /* autovacuum-related options */
+ bool user_catalog_table; /* use as an additional catalog relation */
+ int parallel_workers; /* max number of parallel workers */
+ StdRdOptIndexCleanup vacuum_index_cleanup; /* controls index vacuuming */
+ bool vacuum_truncate; /* enables vacuum to truncate a relation */
+} StdRdOptions;
+
+#define HEAP_MIN_FILLFACTOR 10
+#define HEAP_DEFAULT_FILLFACTOR 100
+
+/*
+ * RelationGetToastTupleTarget
+ * Returns the relation's toast_tuple_target. Note multiple eval of argument!
+ */
+#define RelationGetToastTupleTarget(relation, defaulttarg) \
+ ((relation)->rd_options ? \
+ ((StdRdOptions *) (relation)->rd_options)->toast_tuple_target : (defaulttarg))
+
+/*
+ * RelationGetFillFactor
+ * Returns the relation's fillfactor. Note multiple eval of argument!
+ */
+#define RelationGetFillFactor(relation, defaultff) \
+ ((relation)->rd_options ? \
+ ((StdRdOptions *) (relation)->rd_options)->fillfactor : (defaultff))
+
+/*
+ * RelationGetTargetPageUsage
+ * Returns the relation's desired space usage per page in bytes.
+ */
+#define RelationGetTargetPageUsage(relation, defaultff) \
+ (BLCKSZ * RelationGetFillFactor(relation, defaultff) / 100)
+
+/*
+ * RelationGetTargetPageFreeSpace
+ * Returns the relation's desired freespace per page in bytes.
+ */
+#define RelationGetTargetPageFreeSpace(relation, defaultff) \
+ (BLCKSZ * (100 - RelationGetFillFactor(relation, defaultff)) / 100)
+
+/*
+ * RelationIsUsedAsCatalogTable
+ * Returns whether the relation should be treated as a catalog table
+ * from the pov of logical decoding. Note multiple eval of argument!
+ */
+#define RelationIsUsedAsCatalogTable(relation) \
+ ((relation)->rd_options && \
+ ((relation)->rd_rel->relkind == RELKIND_RELATION || \
+ (relation)->rd_rel->relkind == RELKIND_MATVIEW) ? \
+ ((StdRdOptions *) (relation)->rd_options)->user_catalog_table : false)
+
+/*
+ * RelationGetParallelWorkers
+ * Returns the relation's parallel_workers reloption setting.
+ * Note multiple eval of argument!
+ */
+#define RelationGetParallelWorkers(relation, defaultpw) \
+ ((relation)->rd_options ? \
+ ((StdRdOptions *) (relation)->rd_options)->parallel_workers : (defaultpw))
+
+/* ViewOptions->check_option values */
+typedef enum ViewOptCheckOption
+{
+ VIEW_OPTION_CHECK_OPTION_NOT_SET,
+ VIEW_OPTION_CHECK_OPTION_LOCAL,
+ VIEW_OPTION_CHECK_OPTION_CASCADED
+} ViewOptCheckOption;
+
+/*
+ * ViewOptions
+ * Contents of rd_options for views
+ */
+typedef struct ViewOptions
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ bool security_barrier;
+ bool security_invoker;
+ ViewOptCheckOption check_option;
+} ViewOptions;
+
+/*
+ * RelationIsSecurityView
+ * Returns whether the relation is security view, or not. Note multiple
+ * eval of argument!
+ */
+#define RelationIsSecurityView(relation) \
+ (AssertMacro(relation->rd_rel->relkind == RELKIND_VIEW), \
+ (relation)->rd_options ? \
+ ((ViewOptions *) (relation)->rd_options)->security_barrier : false)
+
+/*
+ * RelationHasSecurityInvoker
+ * Returns true if the relation has the security_invoker property set.
+ * Note multiple eval of argument!
+ */
+#define RelationHasSecurityInvoker(relation) \
+ (AssertMacro(relation->rd_rel->relkind == RELKIND_VIEW), \
+ (relation)->rd_options ? \
+ ((ViewOptions *) (relation)->rd_options)->security_invoker : false)
+
+/*
+ * RelationHasCheckOption
+ * Returns true if the relation is a view defined with either the local
+ * or the cascaded check option. Note multiple eval of argument!
+ */
+#define RelationHasCheckOption(relation) \
+ (AssertMacro(relation->rd_rel->relkind == RELKIND_VIEW), \
+ (relation)->rd_options && \
+ ((ViewOptions *) (relation)->rd_options)->check_option != \
+ VIEW_OPTION_CHECK_OPTION_NOT_SET)
+
+/*
+ * RelationHasLocalCheckOption
+ * Returns true if the relation is a view defined with the local check
+ * option. Note multiple eval of argument!
+ */
+#define RelationHasLocalCheckOption(relation) \
+ (AssertMacro(relation->rd_rel->relkind == RELKIND_VIEW), \
+ (relation)->rd_options && \
+ ((ViewOptions *) (relation)->rd_options)->check_option == \
+ VIEW_OPTION_CHECK_OPTION_LOCAL)
+
+/*
+ * RelationHasCascadedCheckOption
+ * Returns true if the relation is a view defined with the cascaded check
+ * option. Note multiple eval of argument!
+ */
+#define RelationHasCascadedCheckOption(relation) \
+ (AssertMacro(relation->rd_rel->relkind == RELKIND_VIEW), \
+ (relation)->rd_options && \
+ ((ViewOptions *) (relation)->rd_options)->check_option == \
+ VIEW_OPTION_CHECK_OPTION_CASCADED)
+
+/*
+ * RelationIsValid
+ * True iff relation descriptor is valid.
+ */
+#define RelationIsValid(relation) PointerIsValid(relation)
+
+#define InvalidRelation ((Relation) NULL)
+
+/*
+ * RelationHasReferenceCountZero
+ * True iff relation reference count is zero.
+ *
+ * Note:
+ * Assumes relation descriptor is valid.
+ */
+#define RelationHasReferenceCountZero(relation) \
+ ((bool)((relation)->rd_refcnt == 0))
+
+/*
+ * RelationGetForm
+ * Returns pg_class tuple for a relation.
+ *
+ * Note:
+ * Assumes relation descriptor is valid.
+ */
+#define RelationGetForm(relation) ((relation)->rd_rel)
+
+/*
+ * RelationGetRelid
+ * Returns the OID of the relation
+ */
+#define RelationGetRelid(relation) ((relation)->rd_id)
+
+/*
+ * RelationGetNumberOfAttributes
+ * Returns the total number of attributes in a relation.
+ */
+#define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts)
+
+/*
+ * IndexRelationGetNumberOfAttributes
+ * Returns the number of attributes in an index.
+ */
+#define IndexRelationGetNumberOfAttributes(relation) \
+ ((relation)->rd_index->indnatts)
+
+/*
+ * IndexRelationGetNumberOfKeyAttributes
+ * Returns the number of key attributes in an index.
+ */
+#define IndexRelationGetNumberOfKeyAttributes(relation) \
+ ((relation)->rd_index->indnkeyatts)
+
+/*
+ * RelationGetDescr
+ * Returns tuple descriptor for a relation.
+ */
+#define RelationGetDescr(relation) ((relation)->rd_att)
+
+/*
+ * RelationGetRelationName
+ * Returns the rel's name.
+ *
+ * Note that the name is only unique within the containing namespace.
+ */
+#define RelationGetRelationName(relation) \
+ (NameStr((relation)->rd_rel->relname))
+
+/*
+ * RelationGetNamespace
+ * Returns the rel's namespace OID.
+ */
+#define RelationGetNamespace(relation) \
+ ((relation)->rd_rel->relnamespace)
+
+/*
+ * RelationIsMapped
+ * True if the relation uses the relfilenumber map. Note multiple eval
+ * of argument!
+ */
+#define RelationIsMapped(relation) \
+ (RELKIND_HAS_STORAGE((relation)->rd_rel->relkind) && \
+ ((relation)->rd_rel->relfilenode == InvalidRelFileNumber))
+
+#ifndef FRONTEND
+/*
+ * RelationGetSmgr
+ * Returns smgr file handle for a relation, opening it if needed.
+ *
+ * Very little code is authorized to touch rel->rd_smgr directly. Instead
+ * use this function to fetch its value.
+ *
+ * Note: since a relcache flush can cause the file handle to be closed again,
+ * it's unwise to hold onto the pointer returned by this function for any
+ * long period. Recommended practice is to just re-execute RelationGetSmgr
+ * each time you need to access the SMgrRelation. It's quite cheap in
+ * comparison to whatever an smgr function is going to do.
+ */
+static inline SMgrRelation
+RelationGetSmgr(Relation rel)
+{
+ if (unlikely(rel->rd_smgr == NULL))
+ smgrsetowner(&(rel->rd_smgr), smgropen(rel->rd_locator, rel->rd_backend));
+ return rel->rd_smgr;
+}
+
+/*
+ * RelationCloseSmgr
+ * Close the relation at the smgr level, if not already done.
+ */
+static inline void
+RelationCloseSmgr(Relation relation)
+{
+ if (relation->rd_smgr != NULL)
+ smgrclose(relation->rd_smgr);
+
+ /* smgrclose should unhook from owner pointer */
+ Assert(relation->rd_smgr == NULL);
+}
+#endif /* !FRONTEND */
+
+/*
+ * RelationGetTargetBlock
+ * Fetch relation's current insertion target block.
+ *
+ * Returns InvalidBlockNumber if there is no current target block. Note
+ * that the target block status is discarded on any smgr-level invalidation,
+ * so there's no need to re-open the smgr handle if it's not currently open.
+ */
+#define RelationGetTargetBlock(relation) \
+ ( (relation)->rd_smgr != NULL ? (relation)->rd_smgr->smgr_targblock : InvalidBlockNumber )
+
+/*
+ * RelationSetTargetBlock
+ * Set relation's current insertion target block.
+ */
+#define RelationSetTargetBlock(relation, targblock) \
+ do { \
+ RelationGetSmgr(relation)->smgr_targblock = (targblock); \
+ } while (0)
+
+/*
+ * RelationIsPermanent
+ * True if relation is permanent.
+ */
+#define RelationIsPermanent(relation) \
+ ((relation)->rd_rel->relpersistence == RELPERSISTENCE_PERMANENT)
+
+/*
+ * RelationNeedsWAL
+ * True if relation needs WAL.
+ *
+ * Returns false if wal_level = minimal and this relation is created or
+ * truncated in the current transaction. See "Skipping WAL for New
+ * RelFileLocator" in src/backend/access/transam/README.
+ */
+#define RelationNeedsWAL(relation) \
+ (RelationIsPermanent(relation) && (XLogIsNeeded() || \
+ (relation->rd_createSubid == InvalidSubTransactionId && \
+ relation->rd_firstRelfilelocatorSubid == InvalidSubTransactionId)))
+
+/*
+ * RelationUsesLocalBuffers
+ * True if relation's pages are stored in local buffers.
+ */
+#define RelationUsesLocalBuffers(relation) \
+ ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP)
+
+/*
+ * RELATION_IS_LOCAL
+ * If a rel is either temp or newly created in the current transaction,
+ * it can be assumed to be accessible only to the current backend.
+ * This is typically used to decide that we can skip acquiring locks.
+ *
+ * Beware of multiple eval of argument
+ */
+#define RELATION_IS_LOCAL(relation) \
+ ((relation)->rd_islocaltemp || \
+ (relation)->rd_createSubid != InvalidSubTransactionId)
+
+/*
+ * RELATION_IS_OTHER_TEMP
+ * Test for a temporary relation that belongs to some other session.
+ *
+ * Beware of multiple eval of argument
+ */
+#define RELATION_IS_OTHER_TEMP(relation) \
+ ((relation)->rd_rel->relpersistence == RELPERSISTENCE_TEMP && \
+ !(relation)->rd_islocaltemp)
+
+
+/*
+ * RelationIsScannable
+ * Currently can only be false for a materialized view which has not been
+ * populated by its query. This is likely to get more complicated later,
+ * so use a macro which looks like a function.
+ */
+#define RelationIsScannable(relation) ((relation)->rd_rel->relispopulated)
+
+/*
+ * RelationIsPopulated
+ * Currently, we don't physically distinguish the "populated" and
+ * "scannable" properties of matviews, but that may change later.
+ * Hence, use the appropriate one of these macros in code tests.
+ */
+#define RelationIsPopulated(relation) ((relation)->rd_rel->relispopulated)
+
+/*
+ * RelationIsAccessibleInLogicalDecoding
+ * True if we need to log enough information to have access via
+ * decoding snapshot.
+ */
+#define RelationIsAccessibleInLogicalDecoding(relation) \
+ (XLogLogicalInfoActive() && \
+ RelationNeedsWAL(relation) && \
+ (IsCatalogRelation(relation) || RelationIsUsedAsCatalogTable(relation)))
+
+/*
+ * RelationIsLogicallyLogged
+ * True if we need to log enough information to extract the data from the
+ * WAL stream.
+ *
+ * We don't log information for unlogged tables (since they don't WAL log
+ * anyway), for foreign tables (since they don't WAL log, either),
+ * and for system tables (their content is hard to make sense of, and
+ * it would complicate decoding slightly for little gain). Note that we *do*
+ * log information for user defined catalog tables since they presumably are
+ * interesting to the user...
+ */
+#define RelationIsLogicallyLogged(relation) \
+ (XLogLogicalInfoActive() && \
+ RelationNeedsWAL(relation) && \
+ (relation)->rd_rel->relkind != RELKIND_FOREIGN_TABLE && \
+ !IsCatalogRelation(relation))
+
+/* routines in utils/cache/relcache.c */
+extern void RelationIncrementReferenceCount(Relation rel);
+extern void RelationDecrementReferenceCount(Relation rel);
+
+#endif /* REL_H */
diff --git a/pgsql/include/server/utils/relcache.h b/pgsql/include/server/utils/relcache.h
new file mode 100644
index 0000000000000000000000000000000000000000..38524641f470414ef4a9f844d2702b1b55677c8b
--- /dev/null
+++ b/pgsql/include/server/utils/relcache.h
@@ -0,0 +1,158 @@
+/*-------------------------------------------------------------------------
+ *
+ * relcache.h
+ * Relation descriptor cache definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/relcache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RELCACHE_H
+#define RELCACHE_H
+
+#include "access/tupdesc.h"
+#include "common/relpath.h"
+#include "nodes/bitmapset.h"
+
+
+/*
+ * Name of relcache init file(s), used to speed up backend startup
+ */
+#define RELCACHE_INIT_FILENAME "pg_internal.init"
+
+typedef struct RelationData *Relation;
+
+/* ----------------
+ * RelationPtr is used in the executor to support index scans
+ * where we have to keep track of several index relations in an
+ * array. -cim 9/10/89
+ * ----------------
+ */
+typedef Relation *RelationPtr;
+
+/*
+ * Routines to open (lookup) and close a relcache entry
+ */
+extern Relation RelationIdGetRelation(Oid relationId);
+extern void RelationClose(Relation relation);
+
+/*
+ * Routines to compute/retrieve additional cached information
+ */
+extern List *RelationGetFKeyList(Relation relation);
+extern List *RelationGetIndexList(Relation relation);
+extern List *RelationGetStatExtList(Relation relation);
+extern Oid RelationGetPrimaryKeyIndex(Relation relation);
+extern Oid RelationGetReplicaIndex(Relation relation);
+extern List *RelationGetIndexExpressions(Relation relation);
+extern List *RelationGetDummyIndexExpressions(Relation relation);
+extern List *RelationGetIndexPredicate(Relation relation);
+extern Datum *RelationGetIndexRawAttOptions(Relation indexrel);
+extern bytea **RelationGetIndexAttOptions(Relation relation, bool copy);
+
+/*
+ * Which set of columns to return by RelationGetIndexAttrBitmap.
+ */
+typedef enum IndexAttrBitmapKind
+{
+ INDEX_ATTR_BITMAP_KEY,
+ INDEX_ATTR_BITMAP_PRIMARY_KEY,
+ INDEX_ATTR_BITMAP_IDENTITY_KEY,
+ INDEX_ATTR_BITMAP_HOT_BLOCKING,
+ INDEX_ATTR_BITMAP_SUMMARIZED
+} IndexAttrBitmapKind;
+
+extern Bitmapset *RelationGetIndexAttrBitmap(Relation relation,
+ IndexAttrBitmapKind attrKind);
+
+extern Bitmapset *RelationGetIdentityKeyBitmap(Relation relation);
+
+extern void RelationGetExclusionInfo(Relation indexRelation,
+ Oid **operators,
+ Oid **procs,
+ uint16 **strategies);
+
+extern void RelationInitIndexAccessInfo(Relation relation);
+
+/* caller must include pg_publication.h */
+struct PublicationDesc;
+extern void RelationBuildPublicationDesc(Relation relation,
+ struct PublicationDesc *pubdesc);
+
+extern void RelationInitTableAccessMethod(Relation relation);
+
+/*
+ * Routines to support ereport() reports of relation-related errors
+ */
+extern int errtable(Relation rel);
+extern int errtablecol(Relation rel, int attnum);
+extern int errtablecolname(Relation rel, const char *colname);
+extern int errtableconstraint(Relation rel, const char *conname);
+
+/*
+ * Routines for backend startup
+ */
+extern void RelationCacheInitialize(void);
+extern void RelationCacheInitializePhase2(void);
+extern void RelationCacheInitializePhase3(void);
+
+/*
+ * Routine to create a relcache entry for an about-to-be-created relation
+ */
+extern Relation RelationBuildLocalRelation(const char *relname,
+ Oid relnamespace,
+ TupleDesc tupDesc,
+ Oid relid,
+ Oid accessmtd,
+ RelFileNumber relfilenumber,
+ Oid reltablespace,
+ bool shared_relation,
+ bool mapped_relation,
+ char relpersistence,
+ char relkind);
+
+/*
+ * Routines to manage assignment of new relfilenumber to a relation
+ */
+extern void RelationSetNewRelfilenumber(Relation relation, char persistence);
+extern void RelationAssumeNewRelfilelocator(Relation relation);
+
+/*
+ * Routines for flushing/rebuilding relcache entries in various scenarios
+ */
+extern void RelationForgetRelation(Oid rid);
+
+extern void RelationCacheInvalidateEntry(Oid relationId);
+
+extern void RelationCacheInvalidate(bool debug_discard);
+
+extern void RelationCloseSmgrByOid(Oid relationId);
+
+#ifdef USE_ASSERT_CHECKING
+extern void AssertPendingSyncs_RelationCache(void);
+#else
+#define AssertPendingSyncs_RelationCache() do {} while (0)
+#endif
+extern void AtEOXact_RelationCache(bool isCommit);
+extern void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid,
+ SubTransactionId parentSubid);
+
+/*
+ * Routines to help manage rebuilding of relcache init files
+ */
+extern bool RelationIdIsInInitFile(Oid relationId);
+extern void RelationCacheInitFilePreInvalidate(void);
+extern void RelationCacheInitFilePostInvalidate(void);
+extern void RelationCacheInitFileRemove(void);
+
+/* should be used only by relcache.c and catcache.c */
+extern PGDLLIMPORT bool criticalRelcachesBuilt;
+
+/* should be used only by relcache.c and postinit.c */
+extern PGDLLIMPORT bool criticalSharedRelcachesBuilt;
+
+#endif /* RELCACHE_H */
diff --git a/pgsql/include/server/utils/relfilenumbermap.h b/pgsql/include/server/utils/relfilenumbermap.h
new file mode 100644
index 0000000000000000000000000000000000000000..d9b280d3a1077666971b5cb21549935742bec4fc
--- /dev/null
+++ b/pgsql/include/server/utils/relfilenumbermap.h
@@ -0,0 +1,21 @@
+/*-------------------------------------------------------------------------
+ *
+ * relfilenumbermap.h
+ * relfilenumber to oid mapping cache.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/relfilenumbermap.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RELFILENUMBERMAP_H
+#define RELFILENUMBERMAP_H
+
+#include "common/relpath.h"
+
+extern Oid RelidByRelfilenumber(Oid reltablespace,
+ RelFileNumber relfilenumber);
+
+#endif /* RELFILENUMBERMAP_H */
diff --git a/pgsql/include/server/utils/relmapper.h b/pgsql/include/server/utils/relmapper.h
new file mode 100644
index 0000000000000000000000000000000000000000..5c173bdbb3ca9bbadf421b229afc148732ab340f
--- /dev/null
+++ b/pgsql/include/server/utils/relmapper.h
@@ -0,0 +1,73 @@
+/*-------------------------------------------------------------------------
+ *
+ * relmapper.h
+ * Catalog-to-filenumber mapping
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/relmapper.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RELMAPPER_H
+#define RELMAPPER_H
+
+#include "access/xlogreader.h"
+#include "lib/stringinfo.h"
+
+/* ----------------
+ * relmap-related XLOG entries
+ * ----------------
+ */
+
+#define XLOG_RELMAP_UPDATE 0x00
+
+typedef struct xl_relmap_update
+{
+ Oid dbid; /* database ID, or 0 for shared map */
+ Oid tsid; /* database's tablespace, or pg_global */
+ int32 nbytes; /* size of relmap data */
+ char data[FLEXIBLE_ARRAY_MEMBER];
+} xl_relmap_update;
+
+#define MinSizeOfRelmapUpdate offsetof(xl_relmap_update, data)
+
+
+extern RelFileNumber RelationMapOidToFilenumber(Oid relationId, bool shared);
+
+extern Oid RelationMapFilenumberToOid(RelFileNumber filenumber, bool shared);
+extern RelFileNumber RelationMapOidToFilenumberForDatabase(char *dbpath,
+ Oid relationId);
+extern void RelationMapCopy(Oid dbid, Oid tsid, char *srcdbpath,
+ char *dstdbpath);
+extern void RelationMapUpdateMap(Oid relationId, RelFileNumber fileNumber,
+ bool shared, bool immediate);
+
+extern void RelationMapRemoveMapping(Oid relationId);
+
+extern void RelationMapInvalidate(bool shared);
+extern void RelationMapInvalidateAll(void);
+
+extern void AtCCI_RelationMap(void);
+extern void AtEOXact_RelationMap(bool isCommit, bool isParallelWorker);
+extern void AtPrepare_RelationMap(void);
+
+extern void CheckPointRelationMap(void);
+
+extern void RelationMapFinishBootstrap(void);
+
+extern void RelationMapInitialize(void);
+extern void RelationMapInitializePhase2(void);
+extern void RelationMapInitializePhase3(void);
+
+extern Size EstimateRelationMapSpace(void);
+extern void SerializeRelationMap(Size maxSize, char *startAddress);
+extern void RestoreRelationMap(char *startAddress);
+
+extern void relmap_redo(XLogReaderState *record);
+extern void relmap_desc(StringInfo buf, XLogReaderState *record);
+extern const char *relmap_identify(uint8 info);
+
+#endif /* RELMAPPER_H */
diff --git a/pgsql/include/server/utils/relptr.h b/pgsql/include/server/utils/relptr.h
new file mode 100644
index 0000000000000000000000000000000000000000..365cea14b93ed7ed8eb959a6de16faf2f5fc49d2
--- /dev/null
+++ b/pgsql/include/server/utils/relptr.h
@@ -0,0 +1,93 @@
+/*-------------------------------------------------------------------------
+ *
+ * relptr.h
+ * This file contains basic declarations for relative pointers.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/relptr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef RELPTR_H
+#define RELPTR_H
+
+/*
+ * Relative pointers are intended to be used when storing an address that may
+ * be relative either to the base of the process's address space or some
+ * dynamic shared memory segment mapped therein.
+ *
+ * The idea here is that you declare a relative pointer as relptr(type)
+ * and then use relptr_access to dereference it and relptr_store to change
+ * it. The use of a union here is a hack, because what's stored in the
+ * relptr is always a Size, never an actual pointer. But including a pointer
+ * in the union allows us to use stupid macro tricks to provide some measure
+ * of type-safety.
+ */
+#define relptr(type) union { type *relptr_type; Size relptr_off; }
+
+/*
+ * pgindent gets confused by declarations that use "relptr(type)" directly,
+ * so preferred style is to write
+ * typedef struct ... SomeStruct;
+ * relptr_declare(SomeStruct, RelptrSomeStruct);
+ * and then declare pointer variables as "RelptrSomeStruct someptr".
+ */
+#define relptr_declare(type, relptrtype) \
+ typedef relptr(type) relptrtype
+
+#ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
+#define relptr_access(base, rp) \
+ (AssertVariableIsOfTypeMacro(base, char *), \
+ (__typeof__((rp).relptr_type)) ((rp).relptr_off == 0 ? NULL : \
+ (base) + (rp).relptr_off - 1))
+#else
+/*
+ * If we don't have __builtin_types_compatible_p, assume we might not have
+ * __typeof__ either.
+ */
+#define relptr_access(base, rp) \
+ (AssertVariableIsOfTypeMacro(base, char *), \
+ (void *) ((rp).relptr_off == 0 ? NULL : (base) + (rp).relptr_off - 1))
+#endif
+
+#define relptr_is_null(rp) \
+ ((rp).relptr_off == 0)
+
+#define relptr_offset(rp) \
+ ((rp).relptr_off - 1)
+
+/* We use this inline to avoid double eval of "val" in relptr_store */
+static inline Size
+relptr_store_eval(char *base, char *val)
+{
+ if (val == NULL)
+ return 0;
+ else
+ {
+ Assert(val >= base);
+ return val - base + 1;
+ }
+}
+
+#ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
+#define relptr_store(base, rp, val) \
+ (AssertVariableIsOfTypeMacro(base, char *), \
+ AssertVariableIsOfTypeMacro(val, __typeof__((rp).relptr_type)), \
+ (rp).relptr_off = relptr_store_eval((base), (char *) (val)))
+#else
+/*
+ * If we don't have __builtin_types_compatible_p, assume we might not have
+ * __typeof__ either.
+ */
+#define relptr_store(base, rp, val) \
+ (AssertVariableIsOfTypeMacro(base, char *), \
+ (rp).relptr_off = relptr_store_eval((base), (char *) (val)))
+#endif
+
+#define relptr_copy(rp1, rp2) \
+ ((rp1).relptr_off = (rp2).relptr_off)
+
+#endif /* RELPTR_H */
diff --git a/pgsql/include/server/utils/reltrigger.h b/pgsql/include/server/utils/reltrigger.h
new file mode 100644
index 0000000000000000000000000000000000000000..df9a2fb690ea7dac4171f4224a8ed331df8f606a
--- /dev/null
+++ b/pgsql/include/server/utils/reltrigger.h
@@ -0,0 +1,81 @@
+/*-------------------------------------------------------------------------
+ *
+ * reltrigger.h
+ * POSTGRES relation trigger definitions.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/reltrigger.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RELTRIGGER_H
+#define RELTRIGGER_H
+
+
+/*
+ * These struct really belongs to trigger.h, but we put it separately so that
+ * it can be cleanly included in rel.h and other places.
+ */
+
+typedef struct Trigger
+{
+ Oid tgoid; /* OID of trigger (pg_trigger row) */
+ /* Remaining fields are copied from pg_trigger, see pg_trigger.h */
+ char *tgname;
+ Oid tgfoid;
+ int16 tgtype;
+ char tgenabled;
+ bool tgisinternal;
+ bool tgisclone;
+ Oid tgconstrrelid;
+ Oid tgconstrindid;
+ Oid tgconstraint;
+ bool tgdeferrable;
+ bool tginitdeferred;
+ int16 tgnargs;
+ int16 tgnattr;
+ int16 *tgattr;
+ char **tgargs;
+ char *tgqual;
+ char *tgoldtable;
+ char *tgnewtable;
+} Trigger;
+
+typedef struct TriggerDesc
+{
+ Trigger *triggers; /* array of Trigger structs */
+ int numtriggers; /* number of array entries */
+
+ /*
+ * These flags indicate whether the array contains at least one of each
+ * type of trigger. We use these to skip searching the array if not.
+ */
+ bool trig_insert_before_row;
+ bool trig_insert_after_row;
+ bool trig_insert_instead_row;
+ bool trig_insert_before_statement;
+ bool trig_insert_after_statement;
+ bool trig_update_before_row;
+ bool trig_update_after_row;
+ bool trig_update_instead_row;
+ bool trig_update_before_statement;
+ bool trig_update_after_statement;
+ bool trig_delete_before_row;
+ bool trig_delete_after_row;
+ bool trig_delete_instead_row;
+ bool trig_delete_before_statement;
+ bool trig_delete_after_statement;
+ /* there are no row-level truncate triggers */
+ bool trig_truncate_before_statement;
+ bool trig_truncate_after_statement;
+ /* Is there at least one trigger specifying each transition relation? */
+ bool trig_insert_new_table;
+ bool trig_update_old_table;
+ bool trig_update_new_table;
+ bool trig_delete_old_table;
+} TriggerDesc;
+
+#endif /* RELTRIGGER_H */
diff --git a/pgsql/include/server/utils/resowner.h b/pgsql/include/server/utils/resowner.h
new file mode 100644
index 0000000000000000000000000000000000000000..cd070b6080eaea5df21abfc99c77e4f78cfb6dc4
--- /dev/null
+++ b/pgsql/include/server/utils/resowner.h
@@ -0,0 +1,86 @@
+/*-------------------------------------------------------------------------
+ *
+ * resowner.h
+ * POSTGRES resource owner definitions.
+ *
+ * Query-lifespan resources are tracked by associating them with
+ * ResourceOwner objects. This provides a simple mechanism for ensuring
+ * that such resources are freed at the right time.
+ * See utils/resowner/README for more info.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/resowner.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RESOWNER_H
+#define RESOWNER_H
+
+
+/*
+ * ResourceOwner objects are an opaque data structure known only within
+ * resowner.c.
+ */
+typedef struct ResourceOwnerData *ResourceOwner;
+
+
+/*
+ * Globally known ResourceOwners
+ */
+extern PGDLLIMPORT ResourceOwner CurrentResourceOwner;
+extern PGDLLIMPORT ResourceOwner CurTransactionResourceOwner;
+extern PGDLLIMPORT ResourceOwner TopTransactionResourceOwner;
+extern PGDLLIMPORT ResourceOwner AuxProcessResourceOwner;
+
+/*
+ * Resource releasing is done in three phases: pre-locks, locks, and
+ * post-locks. The pre-lock phase must release any resources that are
+ * visible to other backends (such as pinned buffers); this ensures that
+ * when we release a lock that another backend may be waiting on, it will
+ * see us as being fully out of our transaction. The post-lock phase
+ * should be used for backend-internal cleanup.
+ */
+typedef enum
+{
+ RESOURCE_RELEASE_BEFORE_LOCKS,
+ RESOURCE_RELEASE_LOCKS,
+ RESOURCE_RELEASE_AFTER_LOCKS
+} ResourceReleasePhase;
+
+/*
+ * Dynamically loaded modules can get control during ResourceOwnerRelease
+ * by providing a callback of this form.
+ */
+typedef void (*ResourceReleaseCallback) (ResourceReleasePhase phase,
+ bool isCommit,
+ bool isTopLevel,
+ void *arg);
+
+
+/*
+ * Functions in resowner.c
+ */
+
+/* generic routines */
+extern ResourceOwner ResourceOwnerCreate(ResourceOwner parent,
+ const char *name);
+extern void ResourceOwnerRelease(ResourceOwner owner,
+ ResourceReleasePhase phase,
+ bool isCommit,
+ bool isTopLevel);
+extern void ResourceOwnerReleaseAllPlanCacheRefs(ResourceOwner owner);
+extern void ResourceOwnerDelete(ResourceOwner owner);
+extern ResourceOwner ResourceOwnerGetParent(ResourceOwner owner);
+extern void ResourceOwnerNewParent(ResourceOwner owner,
+ ResourceOwner newparent);
+extern void RegisterResourceReleaseCallback(ResourceReleaseCallback callback,
+ void *arg);
+extern void UnregisterResourceReleaseCallback(ResourceReleaseCallback callback,
+ void *arg);
+extern void CreateAuxProcessResourceOwner(void);
+extern void ReleaseAuxProcessResources(bool isCommit);
+
+#endif /* RESOWNER_H */
diff --git a/pgsql/include/server/utils/resowner_private.h b/pgsql/include/server/utils/resowner_private.h
new file mode 100644
index 0000000000000000000000000000000000000000..ae58438ec767d7f1cdd4c14ea546031e6778b301
--- /dev/null
+++ b/pgsql/include/server/utils/resowner_private.h
@@ -0,0 +1,117 @@
+/*-------------------------------------------------------------------------
+ *
+ * resowner_private.h
+ * POSTGRES resource owner private definitions.
+ *
+ * See utils/resowner/README for more info.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/resowner_private.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RESOWNER_PRIVATE_H
+#define RESOWNER_PRIVATE_H
+
+#include "storage/dsm.h"
+#include "storage/fd.h"
+#include "storage/lock.h"
+#include "utils/catcache.h"
+#include "utils/plancache.h"
+#include "utils/resowner.h"
+#include "utils/snapshot.h"
+
+
+/* support for buffer refcount management */
+extern void ResourceOwnerEnlargeBuffers(ResourceOwner owner);
+extern void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer);
+extern void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer);
+
+/* support for IO-in-progress management */
+extern void ResourceOwnerEnlargeBufferIOs(ResourceOwner owner);
+extern void ResourceOwnerRememberBufferIO(ResourceOwner owner, Buffer buffer);
+extern void ResourceOwnerForgetBufferIO(ResourceOwner owner, Buffer buffer);
+
+/* support for local lock management */
+extern void ResourceOwnerRememberLock(ResourceOwner owner, LOCALLOCK *locallock);
+extern void ResourceOwnerForgetLock(ResourceOwner owner, LOCALLOCK *locallock);
+
+/* support for catcache refcount management */
+extern void ResourceOwnerEnlargeCatCacheRefs(ResourceOwner owner);
+extern void ResourceOwnerRememberCatCacheRef(ResourceOwner owner,
+ HeapTuple tuple);
+extern void ResourceOwnerForgetCatCacheRef(ResourceOwner owner,
+ HeapTuple tuple);
+extern void ResourceOwnerEnlargeCatCacheListRefs(ResourceOwner owner);
+extern void ResourceOwnerRememberCatCacheListRef(ResourceOwner owner,
+ CatCList *list);
+extern void ResourceOwnerForgetCatCacheListRef(ResourceOwner owner,
+ CatCList *list);
+
+/* support for relcache refcount management */
+extern void ResourceOwnerEnlargeRelationRefs(ResourceOwner owner);
+extern void ResourceOwnerRememberRelationRef(ResourceOwner owner,
+ Relation rel);
+extern void ResourceOwnerForgetRelationRef(ResourceOwner owner,
+ Relation rel);
+
+/* support for plancache refcount management */
+extern void ResourceOwnerEnlargePlanCacheRefs(ResourceOwner owner);
+extern void ResourceOwnerRememberPlanCacheRef(ResourceOwner owner,
+ CachedPlan *plan);
+extern void ResourceOwnerForgetPlanCacheRef(ResourceOwner owner,
+ CachedPlan *plan);
+
+/* support for tupledesc refcount management */
+extern void ResourceOwnerEnlargeTupleDescs(ResourceOwner owner);
+extern void ResourceOwnerRememberTupleDesc(ResourceOwner owner,
+ TupleDesc tupdesc);
+extern void ResourceOwnerForgetTupleDesc(ResourceOwner owner,
+ TupleDesc tupdesc);
+
+/* support for snapshot refcount management */
+extern void ResourceOwnerEnlargeSnapshots(ResourceOwner owner);
+extern void ResourceOwnerRememberSnapshot(ResourceOwner owner,
+ Snapshot snapshot);
+extern void ResourceOwnerForgetSnapshot(ResourceOwner owner,
+ Snapshot snapshot);
+
+/* support for temporary file management */
+extern void ResourceOwnerEnlargeFiles(ResourceOwner owner);
+extern void ResourceOwnerRememberFile(ResourceOwner owner,
+ File file);
+extern void ResourceOwnerForgetFile(ResourceOwner owner,
+ File file);
+
+/* support for dynamic shared memory management */
+extern void ResourceOwnerEnlargeDSMs(ResourceOwner owner);
+extern void ResourceOwnerRememberDSM(ResourceOwner owner,
+ dsm_segment *);
+extern void ResourceOwnerForgetDSM(ResourceOwner owner,
+ dsm_segment *);
+
+/* support for JITContext management */
+extern void ResourceOwnerEnlargeJIT(ResourceOwner owner);
+extern void ResourceOwnerRememberJIT(ResourceOwner owner,
+ Datum handle);
+extern void ResourceOwnerForgetJIT(ResourceOwner owner,
+ Datum handle);
+
+/* support for cryptohash context management */
+extern void ResourceOwnerEnlargeCryptoHash(ResourceOwner owner);
+extern void ResourceOwnerRememberCryptoHash(ResourceOwner owner,
+ Datum handle);
+extern void ResourceOwnerForgetCryptoHash(ResourceOwner owner,
+ Datum handle);
+
+/* support for HMAC context management */
+extern void ResourceOwnerEnlargeHMAC(ResourceOwner owner);
+extern void ResourceOwnerRememberHMAC(ResourceOwner owner,
+ Datum handle);
+extern void ResourceOwnerForgetHMAC(ResourceOwner owner,
+ Datum handle);
+
+#endif /* RESOWNER_PRIVATE_H */
diff --git a/pgsql/include/server/utils/rls.h b/pgsql/include/server/utils/rls.h
new file mode 100644
index 0000000000000000000000000000000000000000..1e95f83ef350f428cd0287939e004052f5068119
--- /dev/null
+++ b/pgsql/include/server/utils/rls.h
@@ -0,0 +1,50 @@
+/*-------------------------------------------------------------------------
+ *
+ * rls.h
+ * Header file for Row Level Security (RLS) utility commands to be used
+ * with the rowsecurity feature.
+ *
+ * Copyright (c) 2007-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/rls.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RLS_H
+#define RLS_H
+
+/* GUC variable */
+extern PGDLLIMPORT bool row_security;
+
+/*
+ * Used by callers of check_enable_rls.
+ *
+ * RLS could be completely disabled on the tables involved in the query,
+ * which is the simple case, or it may depend on the current environment
+ * (the role which is running the query or the value of the row_security
+ * GUC), or it might be simply enabled as usual.
+ *
+ * If RLS isn't on the table involved then RLS_NONE is returned to indicate
+ * that we don't need to worry about invalidating the query plan for RLS
+ * reasons. If RLS is on the table, but we are bypassing it for now, then
+ * we return RLS_NONE_ENV to indicate that, if the environment changes,
+ * we need to invalidate and replan. Finally, if RLS should be turned on
+ * for the query, then we return RLS_ENABLED, which means we also need to
+ * invalidate if the environment changes.
+ *
+ * Note that RLS_ENABLED will also be returned if noError is true
+ * (indicating that the caller simply want to know if RLS should be applied
+ * for this user but doesn't want an error thrown if it is; this is used
+ * by other error cases where we're just trying to decide if data from the
+ * table should be passed back to the user or not).
+ */
+enum CheckEnableRlsResult
+{
+ RLS_NONE,
+ RLS_NONE_ENV,
+ RLS_ENABLED
+};
+
+extern int check_enable_rls(Oid relid, Oid checkAsUser, bool noError);
+
+#endif /* RLS_H */
diff --git a/pgsql/include/server/utils/ruleutils.h b/pgsql/include/server/utils/ruleutils.h
new file mode 100644
index 0000000000000000000000000000000000000000..b006d9d475ebf1bcfc36b538112835fc6c522f37
--- /dev/null
+++ b/pgsql/include/server/utils/ruleutils.h
@@ -0,0 +1,52 @@
+/*-------------------------------------------------------------------------
+ *
+ * ruleutils.h
+ * Declarations for ruleutils.c
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/ruleutils.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef RULEUTILS_H
+#define RULEUTILS_H
+
+#include "nodes/nodes.h"
+#include "nodes/parsenodes.h"
+#include "nodes/pg_list.h"
+
+struct Plan; /* avoid including plannodes.h here */
+struct PlannedStmt;
+
+/* Flags for pg_get_indexdef_columns_extended() */
+#define RULE_INDEXDEF_PRETTY 0x01
+#define RULE_INDEXDEF_KEYS_ONLY 0x02 /* ignore included attributes */
+
+extern char *pg_get_indexdef_string(Oid indexrelid);
+extern char *pg_get_indexdef_columns(Oid indexrelid, bool pretty);
+extern char *pg_get_indexdef_columns_extended(Oid indexrelid,
+ bits16 flags);
+extern char *pg_get_querydef(Query *query, bool pretty);
+
+extern char *pg_get_partkeydef_columns(Oid relid, bool pretty);
+extern char *pg_get_partconstrdef_string(Oid partitionId, char *aliasname);
+
+extern char *pg_get_constraintdef_command(Oid constraintId);
+extern char *deparse_expression(Node *expr, List *dpcontext,
+ bool forceprefix, bool showimplicit);
+extern List *deparse_context_for(const char *aliasname, Oid relid);
+extern List *deparse_context_for_plan_tree(struct PlannedStmt *pstmt,
+ List *rtable_names);
+extern List *set_deparse_context_plan(List *dpcontext,
+ struct Plan *plan, List *ancestors);
+extern List *select_rtable_names_for_explain(List *rtable,
+ Bitmapset *rels_used);
+extern char *generate_collation_name(Oid collid);
+extern char *generate_opclass_name(Oid opclass);
+extern char *get_range_partbound_string(List *bound_datums);
+
+extern char *pg_get_statisticsobjdef_string(Oid statextid);
+
+#endif /* RULEUTILS_H */
diff --git a/pgsql/include/server/utils/sampling.h b/pgsql/include/server/utils/sampling.h
new file mode 100644
index 0000000000000000000000000000000000000000..e26944887ebc4336bdc6714c9bfbd931e1c1f67d
--- /dev/null
+++ b/pgsql/include/server/utils/sampling.h
@@ -0,0 +1,64 @@
+/*-------------------------------------------------------------------------
+ *
+ * sampling.h
+ * definitions for sampling functions
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/sampling.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SAMPLING_H
+#define SAMPLING_H
+
+#include "common/pg_prng.h"
+#include "storage/block.h" /* for typedef BlockNumber */
+
+
+/* Random generator for sampling code */
+extern void sampler_random_init_state(uint32 seed,
+ pg_prng_state *randstate);
+extern double sampler_random_fract(pg_prng_state *randstate);
+
+/* Block sampling methods */
+
+/* Data structure for Algorithm S from Knuth 3.4.2 */
+typedef struct
+{
+ BlockNumber N; /* number of blocks, known in advance */
+ int n; /* desired sample size */
+ BlockNumber t; /* current block number */
+ int m; /* blocks selected so far */
+ pg_prng_state randstate; /* random generator state */
+} BlockSamplerData;
+
+typedef BlockSamplerData *BlockSampler;
+
+extern BlockNumber BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
+ int samplesize, uint32 randseed);
+extern bool BlockSampler_HasMore(BlockSampler bs);
+extern BlockNumber BlockSampler_Next(BlockSampler bs);
+
+/* Reservoir sampling methods */
+
+typedef struct
+{
+ double W;
+ pg_prng_state randstate; /* random generator state */
+} ReservoirStateData;
+
+typedef ReservoirStateData *ReservoirState;
+
+extern void reservoir_init_selection_state(ReservoirState rs, int n);
+extern double reservoir_get_next_S(ReservoirState rs, double t, int n);
+
+/* Old API, still in use by assorted FDWs */
+/* For backwards compatibility, these declarations are duplicated in vacuum.h */
+
+extern double anl_random_fract(void);
+extern double anl_init_selection_state(int n);
+extern double anl_get_next_S(double t, int n, double *stateptr);
+
+#endif /* SAMPLING_H */
diff --git a/pgsql/include/server/utils/selfuncs.h b/pgsql/include/server/utils/selfuncs.h
new file mode 100644
index 0000000000000000000000000000000000000000..2f76c473db41812fb13d3f46a2d7fe14a2aa097b
--- /dev/null
+++ b/pgsql/include/server/utils/selfuncs.h
@@ -0,0 +1,241 @@
+/*-------------------------------------------------------------------------
+ *
+ * selfuncs.h
+ * Selectivity functions for standard operators, and assorted
+ * infrastructure for selectivity and cost estimation.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/selfuncs.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SELFUNCS_H
+#define SELFUNCS_H
+
+#include "access/htup.h"
+#include "fmgr.h"
+#include "nodes/pathnodes.h"
+
+
+/*
+ * Note: the default selectivity estimates are not chosen entirely at random.
+ * We want them to be small enough to ensure that indexscans will be used if
+ * available, for typical table densities of ~100 tuples/page. Thus, for
+ * example, 0.01 is not quite small enough, since that makes it appear that
+ * nearly all pages will be hit anyway. Also, since we sometimes estimate
+ * eqsel as 1/num_distinct, we probably want DEFAULT_NUM_DISTINCT to equal
+ * 1/DEFAULT_EQ_SEL.
+ */
+
+/* default selectivity estimate for equalities such as "A = b" */
+#define DEFAULT_EQ_SEL 0.005
+
+/* default selectivity estimate for inequalities such as "A < b" */
+#define DEFAULT_INEQ_SEL 0.3333333333333333
+
+/* default selectivity estimate for range inequalities "A > b AND A < c" */
+#define DEFAULT_RANGE_INEQ_SEL 0.005
+
+/* default selectivity estimate for multirange inequalities "A > b AND A < c" */
+#define DEFAULT_MULTIRANGE_INEQ_SEL 0.005
+
+/* default selectivity estimate for pattern-match operators such as LIKE */
+#define DEFAULT_MATCH_SEL 0.005
+
+/* default selectivity estimate for other matching operators */
+#define DEFAULT_MATCHING_SEL 0.010
+
+/* default number of distinct values in a table */
+#define DEFAULT_NUM_DISTINCT 200
+
+/* default selectivity estimate for boolean and null test nodes */
+#define DEFAULT_UNK_SEL 0.005
+#define DEFAULT_NOT_UNK_SEL (1.0 - DEFAULT_UNK_SEL)
+
+
+/*
+ * Clamp a computed probability estimate (which may suffer from roundoff or
+ * estimation errors) to valid range. Argument must be a float variable.
+ */
+#define CLAMP_PROBABILITY(p) \
+ do { \
+ if (p < 0.0) \
+ p = 0.0; \
+ else if (p > 1.0) \
+ p = 1.0; \
+ } while (0)
+
+/*
+ * A set of flags which some selectivity estimation functions can pass back to
+ * callers to provide further details about some assumptions which were made
+ * during the estimation.
+ */
+#define SELFLAG_USED_DEFAULT (1 << 0) /* Estimation fell back on one
+ * of the DEFAULTs as defined
+ * above. */
+
+typedef struct EstimationInfo
+{
+ uint32 flags; /* Flags, as defined above to mark special
+ * properties of the estimation. */
+} EstimationInfo;
+
+/* Return data from examine_variable and friends */
+typedef struct VariableStatData
+{
+ Node *var; /* the Var or expression tree */
+ RelOptInfo *rel; /* Relation, or NULL if not identifiable */
+ HeapTuple statsTuple; /* pg_statistic tuple, or NULL if none */
+ /* NB: if statsTuple!=NULL, it must be freed when caller is done */
+ void (*freefunc) (HeapTuple tuple); /* how to free statsTuple */
+ Oid vartype; /* exposed type of expression */
+ Oid atttype; /* actual type (after stripping relabel) */
+ int32 atttypmod; /* actual typmod (after stripping relabel) */
+ bool isunique; /* matches unique index or DISTINCT clause */
+ bool acl_ok; /* result of ACL check on table or column */
+} VariableStatData;
+
+#define ReleaseVariableStats(vardata) \
+ do { \
+ if (HeapTupleIsValid((vardata).statsTuple)) \
+ (vardata).freefunc((vardata).statsTuple); \
+ } while(0)
+
+
+/*
+ * genericcostestimate is a general-purpose estimator that can be used for
+ * most index types. In some cases we use genericcostestimate as the base
+ * code and then incorporate additional index-type-specific knowledge in
+ * the type-specific calling function. To avoid code duplication, we make
+ * genericcostestimate return a number of intermediate values as well as
+ * its preliminary estimates of the output cost values. The GenericCosts
+ * struct includes all these values.
+ *
+ * Callers should initialize all fields of GenericCosts to zero. In addition,
+ * they can set numIndexTuples to some positive value if they have a better
+ * than default way of estimating the number of leaf index tuples visited.
+ */
+typedef struct
+{
+ /* These are the values the cost estimator must return to the planner */
+ Cost indexStartupCost; /* index-related startup cost */
+ Cost indexTotalCost; /* total index-related scan cost */
+ Selectivity indexSelectivity; /* selectivity of index */
+ double indexCorrelation; /* order correlation of index */
+
+ /* Intermediate values we obtain along the way */
+ double numIndexPages; /* number of leaf pages visited */
+ double numIndexTuples; /* number of leaf tuples visited */
+ double spc_random_page_cost; /* relevant random_page_cost value */
+ double num_sa_scans; /* # indexscans from ScalarArrayOpExprs */
+} GenericCosts;
+
+/* Hooks for plugins to get control when we ask for stats */
+typedef bool (*get_relation_stats_hook_type) (PlannerInfo *root,
+ RangeTblEntry *rte,
+ AttrNumber attnum,
+ VariableStatData *vardata);
+extern PGDLLIMPORT get_relation_stats_hook_type get_relation_stats_hook;
+typedef bool (*get_index_stats_hook_type) (PlannerInfo *root,
+ Oid indexOid,
+ AttrNumber indexattnum,
+ VariableStatData *vardata);
+extern PGDLLIMPORT get_index_stats_hook_type get_index_stats_hook;
+
+/* Functions in selfuncs.c */
+
+extern void examine_variable(PlannerInfo *root, Node *node, int varRelid,
+ VariableStatData *vardata);
+extern bool statistic_proc_security_check(VariableStatData *vardata, Oid func_oid);
+extern bool get_restriction_variable(PlannerInfo *root, List *args,
+ int varRelid,
+ VariableStatData *vardata, Node **other,
+ bool *varonleft);
+extern void get_join_variables(PlannerInfo *root, List *args,
+ SpecialJoinInfo *sjinfo,
+ VariableStatData *vardata1,
+ VariableStatData *vardata2,
+ bool *join_is_reversed);
+extern double get_variable_numdistinct(VariableStatData *vardata,
+ bool *isdefault);
+extern double mcv_selectivity(VariableStatData *vardata,
+ FmgrInfo *opproc, Oid collation,
+ Datum constval, bool varonleft,
+ double *sumcommonp);
+extern double histogram_selectivity(VariableStatData *vardata,
+ FmgrInfo *opproc, Oid collation,
+ Datum constval, bool varonleft,
+ int min_hist_size, int n_skip,
+ int *hist_size);
+extern double generic_restriction_selectivity(PlannerInfo *root,
+ Oid oproid, Oid collation,
+ List *args, int varRelid,
+ double default_selectivity);
+extern double ineq_histogram_selectivity(PlannerInfo *root,
+ VariableStatData *vardata,
+ Oid opoid, FmgrInfo *opproc,
+ bool isgt, bool iseq,
+ Oid collation,
+ Datum constval, Oid consttype);
+extern double var_eq_const(VariableStatData *vardata,
+ Oid oproid, Oid collation,
+ Datum constval, bool constisnull,
+ bool varonleft, bool negate);
+extern double var_eq_non_const(VariableStatData *vardata,
+ Oid oproid, Oid collation,
+ Node *other,
+ bool varonleft, bool negate);
+
+extern Selectivity boolvarsel(PlannerInfo *root, Node *arg, int varRelid);
+extern Selectivity booltestsel(PlannerInfo *root, BoolTestType booltesttype,
+ Node *arg, int varRelid,
+ JoinType jointype, SpecialJoinInfo *sjinfo);
+extern Selectivity nulltestsel(PlannerInfo *root, NullTestType nulltesttype,
+ Node *arg, int varRelid,
+ JoinType jointype, SpecialJoinInfo *sjinfo);
+extern Selectivity scalararraysel(PlannerInfo *root,
+ ScalarArrayOpExpr *clause,
+ bool is_join_clause,
+ int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo);
+extern int estimate_array_length(Node *arrayexpr);
+extern Selectivity rowcomparesel(PlannerInfo *root,
+ RowCompareExpr *clause,
+ int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo);
+
+extern void mergejoinscansel(PlannerInfo *root, Node *clause,
+ Oid opfamily, int strategy, bool nulls_first,
+ Selectivity *leftstart, Selectivity *leftend,
+ Selectivity *rightstart, Selectivity *rightend);
+
+extern double estimate_num_groups(PlannerInfo *root, List *groupExprs,
+ double input_rows, List **pgset,
+ EstimationInfo *estinfo);
+
+extern void estimate_hash_bucket_stats(PlannerInfo *root,
+ Node *hashkey, double nbuckets,
+ Selectivity *mcv_freq,
+ Selectivity *bucketsize_frac);
+extern double estimate_hashagg_tablesize(PlannerInfo *root, Path *path,
+ const AggClauseCosts *agg_costs,
+ double dNumGroups);
+
+extern List *get_quals_from_indexclauses(List *indexclauses);
+extern Cost index_other_operands_eval_cost(PlannerInfo *root,
+ List *indexquals);
+extern List *add_predicate_to_index_quals(IndexOptInfo *index,
+ List *indexQuals);
+extern void genericcostestimate(PlannerInfo *root, IndexPath *path,
+ double loop_count,
+ GenericCosts *costs);
+
+/* Functions in array_selfuncs.c */
+
+extern Selectivity scalararraysel_containment(PlannerInfo *root,
+ Node *leftop, Node *rightop,
+ Oid elemtype, bool isEquality, bool useOr,
+ int varRelid);
+
+#endif /* SELFUNCS_H */
diff --git a/pgsql/include/server/utils/sharedtuplestore.h b/pgsql/include/server/utils/sharedtuplestore.h
new file mode 100644
index 0000000000000000000000000000000000000000..c7075ad055d1415d22a3a4b11f40e8569cd85b89
--- /dev/null
+++ b/pgsql/include/server/utils/sharedtuplestore.h
@@ -0,0 +1,61 @@
+/*-------------------------------------------------------------------------
+ *
+ * sharedtuplestore.h
+ * Simple mechanism for sharing tuples between backends.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/sharedtuplestore.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SHAREDTUPLESTORE_H
+#define SHAREDTUPLESTORE_H
+
+#include "access/htup.h"
+#include "storage/fd.h"
+#include "storage/sharedfileset.h"
+
+struct SharedTuplestore;
+typedef struct SharedTuplestore SharedTuplestore;
+
+struct SharedTuplestoreAccessor;
+typedef struct SharedTuplestoreAccessor SharedTuplestoreAccessor;
+
+/*
+ * A flag indicating that the tuplestore will only be scanned once, so backing
+ * files can be unlinked early.
+ */
+#define SHARED_TUPLESTORE_SINGLE_PASS 0x01
+
+extern size_t sts_estimate(int participants);
+
+extern SharedTuplestoreAccessor *sts_initialize(SharedTuplestore *sts,
+ int participants,
+ int my_participant_number,
+ size_t meta_data_size,
+ int flags,
+ SharedFileSet *fileset,
+ const char *name);
+
+extern SharedTuplestoreAccessor *sts_attach(SharedTuplestore *sts,
+ int my_participant_number,
+ SharedFileSet *fileset);
+
+extern void sts_end_write(SharedTuplestoreAccessor *accessor);
+
+extern void sts_reinitialize(SharedTuplestoreAccessor *accessor);
+
+extern void sts_begin_parallel_scan(SharedTuplestoreAccessor *accessor);
+
+extern void sts_end_parallel_scan(SharedTuplestoreAccessor *accessor);
+
+extern void sts_puttuple(SharedTuplestoreAccessor *accessor,
+ void *meta_data,
+ MinimalTuple tuple);
+
+extern MinimalTuple sts_parallel_scan_next(SharedTuplestoreAccessor *accessor,
+ void *meta_data);
+
+#endif /* SHAREDTUPLESTORE_H */
diff --git a/pgsql/include/server/utils/snapmgr.h b/pgsql/include/server/utils/snapmgr.h
new file mode 100644
index 0000000000000000000000000000000000000000..980d37a1947e6e509854cfba75c17f7ab01841b2
--- /dev/null
+++ b/pgsql/include/server/utils/snapmgr.h
@@ -0,0 +1,181 @@
+/*-------------------------------------------------------------------------
+ *
+ * snapmgr.h
+ * POSTGRES snapshot manager
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/snapmgr.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SNAPMGR_H
+#define SNAPMGR_H
+
+#include "access/transam.h"
+#include "utils/relcache.h"
+#include "utils/resowner.h"
+#include "utils/snapshot.h"
+
+
+/*
+ * The structure used to map times to TransactionId values for the "snapshot
+ * too old" feature must have a few entries at the tail to hold old values;
+ * otherwise the lookup will often fail and the expected early pruning or
+ * vacuum will not usually occur. It is best if this padding is for a number
+ * of minutes greater than a thread would normally be stalled, but it's OK if
+ * early vacuum opportunities are occasionally missed, so there's no need to
+ * use an extreme value or get too fancy. 10 minutes seems plenty.
+ */
+#define OLD_SNAPSHOT_PADDING_ENTRIES 10
+#define OLD_SNAPSHOT_TIME_MAP_ENTRIES (old_snapshot_threshold + OLD_SNAPSHOT_PADDING_ENTRIES)
+
+/*
+ * Common definition of relation properties that allow early pruning/vacuuming
+ * when old_snapshot_threshold >= 0.
+ */
+#define RelationAllowsEarlyPruning(rel) \
+( \
+ RelationIsPermanent(rel) && !IsCatalogRelation(rel) \
+ && !RelationIsAccessibleInLogicalDecoding(rel) \
+)
+
+#define EarlyPruningEnabled(rel) (old_snapshot_threshold >= 0 && RelationAllowsEarlyPruning(rel))
+
+/* GUC variables */
+extern PGDLLIMPORT int old_snapshot_threshold;
+
+
+extern Size SnapMgrShmemSize(void);
+extern void SnapMgrInit(void);
+extern TimestampTz GetSnapshotCurrentTimestamp(void);
+extern TimestampTz GetOldSnapshotThresholdTimestamp(void);
+extern void SnapshotTooOldMagicForTest(void);
+
+extern PGDLLIMPORT bool FirstSnapshotSet;
+
+extern PGDLLIMPORT TransactionId TransactionXmin;
+extern PGDLLIMPORT TransactionId RecentXmin;
+
+/* Variables representing various special snapshot semantics */
+extern PGDLLIMPORT SnapshotData SnapshotSelfData;
+extern PGDLLIMPORT SnapshotData SnapshotAnyData;
+extern PGDLLIMPORT SnapshotData CatalogSnapshotData;
+
+#define SnapshotSelf (&SnapshotSelfData)
+#define SnapshotAny (&SnapshotAnyData)
+
+/*
+ * We don't provide a static SnapshotDirty variable because it would be
+ * non-reentrant. Instead, users of that snapshot type should declare a
+ * local variable of type SnapshotData, and initialize it with this macro.
+ */
+#define InitDirtySnapshot(snapshotdata) \
+ ((snapshotdata).snapshot_type = SNAPSHOT_DIRTY)
+
+/*
+ * Similarly, some initialization is required for a NonVacuumable snapshot.
+ * The caller must supply the visibility cutoff state to use (c.f.
+ * GlobalVisTestFor()).
+ */
+#define InitNonVacuumableSnapshot(snapshotdata, vistestp) \
+ ((snapshotdata).snapshot_type = SNAPSHOT_NON_VACUUMABLE, \
+ (snapshotdata).vistest = (vistestp))
+
+/*
+ * Similarly, some initialization is required for SnapshotToast. We need
+ * to set lsn and whenTaken correctly to support snapshot_too_old.
+ */
+#define InitToastSnapshot(snapshotdata, l, w) \
+ ((snapshotdata).snapshot_type = SNAPSHOT_TOAST, \
+ (snapshotdata).lsn = (l), \
+ (snapshotdata).whenTaken = (w))
+
+/* This macro encodes the knowledge of which snapshots are MVCC-safe */
+#define IsMVCCSnapshot(snapshot) \
+ ((snapshot)->snapshot_type == SNAPSHOT_MVCC || \
+ (snapshot)->snapshot_type == SNAPSHOT_HISTORIC_MVCC)
+
+#ifndef FRONTEND
+static inline bool
+OldSnapshotThresholdActive(void)
+{
+ return old_snapshot_threshold >= 0;
+}
+#endif
+
+extern Snapshot GetTransactionSnapshot(void);
+extern Snapshot GetLatestSnapshot(void);
+extern void SnapshotSetCommandId(CommandId curcid);
+extern Snapshot GetOldestSnapshot(void);
+
+extern Snapshot GetCatalogSnapshot(Oid relid);
+extern Snapshot GetNonHistoricCatalogSnapshot(Oid relid);
+extern void InvalidateCatalogSnapshot(void);
+extern void InvalidateCatalogSnapshotConditionally(void);
+
+extern void PushActiveSnapshot(Snapshot snapshot);
+extern void PushActiveSnapshotWithLevel(Snapshot snapshot, int snap_level);
+extern void PushCopiedSnapshot(Snapshot snapshot);
+extern void UpdateActiveSnapshotCommandId(void);
+extern void PopActiveSnapshot(void);
+extern Snapshot GetActiveSnapshot(void);
+extern bool ActiveSnapshotSet(void);
+
+extern Snapshot RegisterSnapshot(Snapshot snapshot);
+extern void UnregisterSnapshot(Snapshot snapshot);
+extern Snapshot RegisterSnapshotOnOwner(Snapshot snapshot, ResourceOwner owner);
+extern void UnregisterSnapshotFromOwner(Snapshot snapshot, ResourceOwner owner);
+
+extern void AtSubCommit_Snapshot(int level);
+extern void AtSubAbort_Snapshot(int level);
+extern void AtEOXact_Snapshot(bool isCommit, bool resetXmin);
+
+extern void ImportSnapshot(const char *idstr);
+extern bool XactHasExportedSnapshots(void);
+extern void DeleteAllExportedSnapshotFiles(void);
+extern void WaitForOlderSnapshots(TransactionId limitXmin, bool progress);
+extern bool ThereAreNoPriorRegisteredSnapshots(void);
+extern bool HaveRegisteredOrActiveSnapshot(void);
+extern bool TransactionIdLimitedForOldSnapshots(TransactionId recentXmin,
+ Relation relation,
+ TransactionId *limit_xid,
+ TimestampTz *limit_ts);
+extern void SetOldSnapshotThresholdTimestamp(TimestampTz ts, TransactionId xlimit);
+extern void MaintainOldSnapshotTimeMapping(TimestampTz whenTaken,
+ TransactionId xmin);
+
+extern char *ExportSnapshot(Snapshot snapshot);
+
+/*
+ * These live in procarray.c because they're intimately linked to the
+ * procarray contents, but thematically they better fit into snapmgr.h.
+ */
+typedef struct GlobalVisState GlobalVisState;
+extern GlobalVisState *GlobalVisTestFor(Relation rel);
+extern bool GlobalVisTestIsRemovableXid(GlobalVisState *state, TransactionId xid);
+extern bool GlobalVisTestIsRemovableFullXid(GlobalVisState *state, FullTransactionId fxid);
+extern FullTransactionId GlobalVisTestNonRemovableFullHorizon(GlobalVisState *state);
+extern TransactionId GlobalVisTestNonRemovableHorizon(GlobalVisState *state);
+extern bool GlobalVisCheckRemovableXid(Relation rel, TransactionId xid);
+extern bool GlobalVisCheckRemovableFullXid(Relation rel, FullTransactionId fxid);
+
+/*
+ * Utility functions for implementing visibility routines in table AMs.
+ */
+extern bool XidInMVCCSnapshot(TransactionId xid, Snapshot snapshot);
+
+/* Support for catalog timetravel for logical decoding */
+struct HTAB;
+extern struct HTAB *HistoricSnapshotGetTupleCids(void);
+extern void SetupHistoricSnapshot(Snapshot historic_snapshot, struct HTAB *tuplecids);
+extern void TeardownHistoricSnapshot(bool is_error);
+extern bool HistoricSnapshotActive(void);
+
+extern Size EstimateSnapshotSpace(Snapshot snapshot);
+extern void SerializeSnapshot(Snapshot snapshot, char *start_address);
+extern Snapshot RestoreSnapshot(char *start_address);
+extern void RestoreTransactionSnapshot(Snapshot snapshot, void *source_pgproc);
+
+#endif /* SNAPMGR_H */
diff --git a/pgsql/include/server/utils/snapshot.h b/pgsql/include/server/utils/snapshot.h
new file mode 100644
index 0000000000000000000000000000000000000000..583a667a40ab51756c83451a5aff2df471c9b091
--- /dev/null
+++ b/pgsql/include/server/utils/snapshot.h
@@ -0,0 +1,219 @@
+/*-------------------------------------------------------------------------
+ *
+ * snapshot.h
+ * POSTGRES snapshot definition
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/snapshot.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SNAPSHOT_H
+#define SNAPSHOT_H
+
+#include "access/htup.h"
+#include "access/xlogdefs.h"
+#include "datatype/timestamp.h"
+#include "lib/pairingheap.h"
+#include "storage/buf.h"
+
+
+/*
+ * The different snapshot types. We use SnapshotData structures to represent
+ * both "regular" (MVCC) snapshots and "special" snapshots that have non-MVCC
+ * semantics. The specific semantics of a snapshot are encoded by its type.
+ *
+ * The behaviour of each type of snapshot should be documented alongside its
+ * enum value, best in terms that are not specific to an individual table AM.
+ *
+ * The reason the snapshot type rather than a callback as it used to be is
+ * that that allows to use the same snapshot for different table AMs without
+ * having one callback per AM.
+ */
+typedef enum SnapshotType
+{
+ /*-------------------------------------------------------------------------
+ * A tuple is visible iff the tuple is valid for the given MVCC snapshot.
+ *
+ * Here, we consider the effects of:
+ * - all transactions committed as of the time of the given snapshot
+ * - previous commands of this transaction
+ *
+ * Does _not_ include:
+ * - transactions shown as in-progress by the snapshot
+ * - transactions started after the snapshot was taken
+ * - changes made by the current command
+ * -------------------------------------------------------------------------
+ */
+ SNAPSHOT_MVCC = 0,
+
+ /*-------------------------------------------------------------------------
+ * A tuple is visible iff the tuple is valid "for itself".
+ *
+ * Here, we consider the effects of:
+ * - all committed transactions (as of the current instant)
+ * - previous commands of this transaction
+ * - changes made by the current command
+ *
+ * Does _not_ include:
+ * - in-progress transactions (as of the current instant)
+ * -------------------------------------------------------------------------
+ */
+ SNAPSHOT_SELF,
+
+ /*
+ * Any tuple is visible.
+ */
+ SNAPSHOT_ANY,
+
+ /*
+ * A tuple is visible iff the tuple is valid as a TOAST row.
+ */
+ SNAPSHOT_TOAST,
+
+ /*-------------------------------------------------------------------------
+ * A tuple is visible iff the tuple is valid including effects of open
+ * transactions.
+ *
+ * Here, we consider the effects of:
+ * - all committed and in-progress transactions (as of the current instant)
+ * - previous commands of this transaction
+ * - changes made by the current command
+ *
+ * This is essentially like SNAPSHOT_SELF as far as effects of the current
+ * transaction and committed/aborted xacts are concerned. However, it
+ * also includes the effects of other xacts still in progress.
+ *
+ * A special hack is that when a snapshot of this type is used to
+ * determine tuple visibility, the passed-in snapshot struct is used as an
+ * output argument to return the xids of concurrent xacts that affected
+ * the tuple. snapshot->xmin is set to the tuple's xmin if that is
+ * another transaction that's still in progress; or to
+ * InvalidTransactionId if the tuple's xmin is committed good, committed
+ * dead, or my own xact. Similarly for snapshot->xmax and the tuple's
+ * xmax. If the tuple was inserted speculatively, meaning that the
+ * inserter might still back down on the insertion without aborting the
+ * whole transaction, the associated token is also returned in
+ * snapshot->speculativeToken. See also InitDirtySnapshot().
+ * -------------------------------------------------------------------------
+ */
+ SNAPSHOT_DIRTY,
+
+ /*
+ * A tuple is visible iff it follows the rules of SNAPSHOT_MVCC, but
+ * supports being called in timetravel context (for decoding catalog
+ * contents in the context of logical decoding).
+ */
+ SNAPSHOT_HISTORIC_MVCC,
+
+ /*
+ * A tuple is visible iff the tuple might be visible to some transaction;
+ * false if it's surely dead to everyone, i.e., vacuumable.
+ *
+ * For visibility checks snapshot->min must have been set up with the xmin
+ * horizon to use.
+ */
+ SNAPSHOT_NON_VACUUMABLE
+} SnapshotType;
+
+typedef struct SnapshotData *Snapshot;
+
+#define InvalidSnapshot ((Snapshot) NULL)
+
+/*
+ * Struct representing all kind of possible snapshots.
+ *
+ * There are several different kinds of snapshots:
+ * * Normal MVCC snapshots
+ * * MVCC snapshots taken during recovery (in Hot-Standby mode)
+ * * Historic MVCC snapshots used during logical decoding
+ * * snapshots passed to HeapTupleSatisfiesDirty()
+ * * snapshots passed to HeapTupleSatisfiesNonVacuumable()
+ * * snapshots used for SatisfiesAny, Toast, Self where no members are
+ * accessed.
+ *
+ * TODO: It's probably a good idea to split this struct using a NodeTag
+ * similar to how parser and executor nodes are handled, with one type for
+ * each different kind of snapshot to avoid overloading the meaning of
+ * individual fields.
+ */
+typedef struct SnapshotData
+{
+ SnapshotType snapshot_type; /* type of snapshot */
+
+ /*
+ * The remaining fields are used only for MVCC snapshots, and are normally
+ * just zeroes in special snapshots. (But xmin and xmax are used
+ * specially by HeapTupleSatisfiesDirty, and xmin is used specially by
+ * HeapTupleSatisfiesNonVacuumable.)
+ *
+ * An MVCC snapshot can never see the effects of XIDs >= xmax. It can see
+ * the effects of all older XIDs except those listed in the snapshot. xmin
+ * is stored as an optimization to avoid needing to search the XID arrays
+ * for most tuples.
+ */
+ TransactionId xmin; /* all XID < xmin are visible to me */
+ TransactionId xmax; /* all XID >= xmax are invisible to me */
+
+ /*
+ * For normal MVCC snapshot this contains the all xact IDs that are in
+ * progress, unless the snapshot was taken during recovery in which case
+ * it's empty. For historic MVCC snapshots, the meaning is inverted, i.e.
+ * it contains *committed* transactions between xmin and xmax.
+ *
+ * note: all ids in xip[] satisfy xmin <= xip[i] < xmax
+ */
+ TransactionId *xip;
+ uint32 xcnt; /* # of xact ids in xip[] */
+
+ /*
+ * For non-historic MVCC snapshots, this contains subxact IDs that are in
+ * progress (and other transactions that are in progress if taken during
+ * recovery). For historic snapshot it contains *all* xids assigned to the
+ * replayed transaction, including the toplevel xid.
+ *
+ * note: all ids in subxip[] are >= xmin, but we don't bother filtering
+ * out any that are >= xmax
+ */
+ TransactionId *subxip;
+ int32 subxcnt; /* # of xact ids in subxip[] */
+ bool suboverflowed; /* has the subxip array overflowed? */
+
+ bool takenDuringRecovery; /* recovery-shaped snapshot? */
+ bool copied; /* false if it's a static snapshot */
+
+ CommandId curcid; /* in my xact, CID < curcid are visible */
+
+ /*
+ * An extra return value for HeapTupleSatisfiesDirty, not used in MVCC
+ * snapshots.
+ */
+ uint32 speculativeToken;
+
+ /*
+ * For SNAPSHOT_NON_VACUUMABLE (and hopefully more in the future) this is
+ * used to determine whether row could be vacuumed.
+ */
+ struct GlobalVisState *vistest;
+
+ /*
+ * Book-keeping information, used by the snapshot manager
+ */
+ uint32 active_count; /* refcount on ActiveSnapshot stack */
+ uint32 regd_count; /* refcount on RegisteredSnapshots */
+ pairingheap_node ph_node; /* link in the RegisteredSnapshots heap */
+
+ TimestampTz whenTaken; /* timestamp when snapshot was taken */
+ XLogRecPtr lsn; /* position in the WAL stream when taken */
+
+ /*
+ * The transaction completion count at the time GetSnapshotData() built
+ * this snapshot. Allows to avoid re-computing static snapshots when no
+ * transactions completed since the last GetSnapshotData().
+ */
+ uint64 snapXactCompletionCount;
+} SnapshotData;
+
+#endif /* SNAPSHOT_H */
diff --git a/pgsql/include/server/utils/sortsupport.h b/pgsql/include/server/utils/sortsupport.h
new file mode 100644
index 0000000000000000000000000000000000000000..475ed1d5b82b4e1bc23ba048d0cf45cb4fbf2e3b
--- /dev/null
+++ b/pgsql/include/server/utils/sortsupport.h
@@ -0,0 +1,391 @@
+/*-------------------------------------------------------------------------
+ *
+ * sortsupport.h
+ * Framework for accelerated sorting.
+ *
+ * Traditionally, PostgreSQL has implemented sorting by repeatedly invoking
+ * an SQL-callable comparison function "cmp(x, y) returns int" on pairs of
+ * values to be compared, where the comparison function is the BTORDER_PROC
+ * pg_amproc support function of the appropriate btree index opclass.
+ *
+ * This file defines alternative APIs that allow sorting to be performed with
+ * reduced overhead. To support lower-overhead sorting, a btree opclass may
+ * provide a BTSORTSUPPORT_PROC pg_amproc entry, which must take a single
+ * argument of type internal and return void. The argument is actually a
+ * pointer to a SortSupportData struct, which is defined below.
+ *
+ * If provided, the BTSORTSUPPORT function will be called during sort setup,
+ * and it must initialize the provided struct with pointers to function(s)
+ * that can be called to perform sorting. This API is defined to allow
+ * multiple acceleration mechanisms to be supported, but no opclass is
+ * required to provide all of them. The BTSORTSUPPORT function should
+ * simply not set any function pointers for mechanisms it doesn't support.
+ * Opclasses that provide BTSORTSUPPORT and don't provide a comparator
+ * function will have a shim set up by sort support automatically. However,
+ * opclasses that support the optional additional abbreviated key capability
+ * must always provide an authoritative comparator used to tie-break
+ * inconclusive abbreviated comparisons and also used when aborting
+ * abbreviation. Furthermore, a converter and abort/costing function must be
+ * provided.
+ *
+ * All sort support functions will be passed the address of the
+ * SortSupportData struct when called, so they can use it to store
+ * additional private data as needed. In particular, for collation-aware
+ * datatypes, the ssup_collation field is set before calling BTSORTSUPPORT
+ * and is available to all support functions. Additional opclass-dependent
+ * data can be stored using the ssup_extra field. Any such data
+ * should be allocated in the ssup_cxt memory context.
+ *
+ * Note: since pg_amproc functions are indexed by (lefttype, righttype)
+ * it is possible to associate a BTSORTSUPPORT function with a cross-type
+ * comparison. This could sensibly be used to provide a fast comparator
+ * function for such cases, but probably not any other acceleration method.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/sortsupport.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SORTSUPPORT_H
+#define SORTSUPPORT_H
+
+#include "access/attnum.h"
+#include "utils/relcache.h"
+
+typedef struct SortSupportData *SortSupport;
+
+typedef struct SortSupportData
+{
+ /*
+ * These fields are initialized before calling the BTSORTSUPPORT function
+ * and should not be changed later.
+ */
+ MemoryContext ssup_cxt; /* Context containing sort info */
+ Oid ssup_collation; /* Collation to use, or InvalidOid */
+
+ /*
+ * Additional sorting parameters; but unlike ssup_collation, these can be
+ * changed after BTSORTSUPPORT is called, so don't use them in selecting
+ * sort support functions.
+ */
+ bool ssup_reverse; /* descending-order sort? */
+ bool ssup_nulls_first; /* sort nulls first? */
+
+ /*
+ * These fields are workspace for callers, and should not be touched by
+ * opclass-specific functions.
+ */
+ AttrNumber ssup_attno; /* column number to sort */
+
+ /*
+ * ssup_extra is zeroed before calling the BTSORTSUPPORT function, and is
+ * not touched subsequently by callers.
+ */
+ void *ssup_extra; /* Workspace for opclass functions */
+
+ /*
+ * Function pointers are zeroed before calling the BTSORTSUPPORT function,
+ * and must be set by it for any acceleration methods it wants to supply.
+ * The comparator pointer must be set, others are optional.
+ */
+
+ /*
+ * Comparator function has the same API as the traditional btree
+ * comparison function, ie, return <0, 0, or >0 according as x is less
+ * than, equal to, or greater than y. Note that x and y are guaranteed
+ * not null, and there is no way to return null either.
+ *
+ * This may be either the authoritative comparator, or the abbreviated
+ * comparator. Core code may switch this over the initial preference of
+ * an opclass support function despite originally indicating abbreviation
+ * was applicable, by assigning the authoritative comparator back.
+ */
+ int (*comparator) (Datum x, Datum y, SortSupport ssup);
+
+ /*
+ * "Abbreviated key" infrastructure follows.
+ *
+ * All callbacks must be set by sortsupport opclasses that make use of
+ * this optional additional infrastructure (unless for whatever reasons
+ * the opclass doesn't proceed with abbreviation, in which case
+ * abbrev_converter must not be set).
+ *
+ * This allows opclass authors to supply a conversion routine, used to
+ * create an alternative representation of the underlying type (an
+ * "abbreviated key"). This representation must be pass-by-value and
+ * typically will use some ad-hoc format that only the opclass has
+ * knowledge of. An alternative comparator, used only with this
+ * alternative representation must also be provided (which is assigned to
+ * "comparator"). This representation is a simple approximation of the
+ * original Datum. It must be possible to compare datums of this
+ * representation with each other using the supplied alternative
+ * comparator, and have any non-zero return value be a reliable proxy for
+ * what a proper comparison would indicate. Returning zero from the
+ * alternative comparator does not indicate equality, as with a
+ * conventional support routine 1, though -- it indicates that it wasn't
+ * possible to determine how the two abbreviated values compared. A
+ * proper comparison, using "abbrev_full_comparator"/
+ * ApplySortAbbrevFullComparator() is therefore required. In many cases
+ * this results in most or all comparisons only using the cheap
+ * alternative comparison func, which is typically implemented as code
+ * that compiles to just a few CPU instructions. CPU cache miss penalties
+ * are expensive; to get good overall performance, sort infrastructure
+ * must heavily weigh cache performance.
+ *
+ * Opclass authors must consider the final cardinality of abbreviated keys
+ * when devising an encoding scheme. It's possible for a strategy to work
+ * better than an alternative strategy with one usage pattern, while the
+ * reverse might be true for another usage pattern. All of these factors
+ * must be considered.
+ */
+
+ /*
+ * "abbreviate" concerns whether or not the abbreviated key optimization
+ * is applicable in principle (that is, the sortsupport routine needs to
+ * know if its dealing with a key where an abbreviated representation can
+ * usefully be packed together. Conventionally, this is the leading
+ * attribute key). Note, however, that in order to determine that
+ * abbreviation is not in play, the core code always checks whether or not
+ * the opclass has set abbrev_converter. This is a one way, one time
+ * message to the opclass.
+ */
+ bool abbreviate;
+
+ /*
+ * Converter to abbreviated format, from original representation. Core
+ * code uses this callback to convert from a pass-by-reference "original"
+ * Datum to a pass-by-value abbreviated key Datum. Note that original is
+ * guaranteed NOT NULL, because it doesn't make sense to factor NULLness
+ * into ad-hoc cost model.
+ *
+ * abbrev_converter is tested to see if abbreviation is in play. Core
+ * code may set it to NULL to indicate abbreviation should not be used
+ * (which is something sortsupport routines need not concern themselves
+ * with). However, sortsupport routines must not set it when it is
+ * immediately established that abbreviation should not proceed (e.g., for
+ * !abbreviate calls, or due to platform-specific impediments to using
+ * abbreviation).
+ */
+ Datum (*abbrev_converter) (Datum original, SortSupport ssup);
+
+ /*
+ * abbrev_abort callback allows clients to verify that the current
+ * strategy is working out, using a sortsupport routine defined ad-hoc
+ * cost model. If there is a lot of duplicate abbreviated keys in
+ * practice, it's useful to be able to abandon the strategy before paying
+ * too high a cost in conversion (perhaps certain opclass-specific
+ * adaptations are useful too).
+ */
+ bool (*abbrev_abort) (int memtupcount, SortSupport ssup);
+
+ /*
+ * Full, authoritative comparator for key that an abbreviated
+ * representation was generated for, used when an abbreviated comparison
+ * was inconclusive (by calling ApplySortAbbrevFullComparator()), or used
+ * to replace "comparator" when core system ultimately decides against
+ * abbreviation.
+ */
+ int (*abbrev_full_comparator) (Datum x, Datum y, SortSupport ssup);
+} SortSupportData;
+
+
+/*
+ * Apply a sort comparator function and return a 3-way comparison result.
+ * This takes care of handling reverse-sort and NULLs-ordering properly.
+ */
+static inline int
+ApplySortComparator(Datum datum1, bool isNull1,
+ Datum datum2, bool isNull2,
+ SortSupport ssup)
+{
+ int compare;
+
+ if (isNull1)
+ {
+ if (isNull2)
+ compare = 0; /* NULL "=" NULL */
+ else if (ssup->ssup_nulls_first)
+ compare = -1; /* NULL "<" NOT_NULL */
+ else
+ compare = 1; /* NULL ">" NOT_NULL */
+ }
+ else if (isNull2)
+ {
+ if (ssup->ssup_nulls_first)
+ compare = 1; /* NOT_NULL ">" NULL */
+ else
+ compare = -1; /* NOT_NULL "<" NULL */
+ }
+ else
+ {
+ compare = ssup->comparator(datum1, datum2, ssup);
+ if (ssup->ssup_reverse)
+ INVERT_COMPARE_RESULT(compare);
+ }
+
+ return compare;
+}
+
+static inline int
+ApplyUnsignedSortComparator(Datum datum1, bool isNull1,
+ Datum datum2, bool isNull2,
+ SortSupport ssup)
+{
+ int compare;
+
+ if (isNull1)
+ {
+ if (isNull2)
+ compare = 0; /* NULL "=" NULL */
+ else if (ssup->ssup_nulls_first)
+ compare = -1; /* NULL "<" NOT_NULL */
+ else
+ compare = 1; /* NULL ">" NOT_NULL */
+ }
+ else if (isNull2)
+ {
+ if (ssup->ssup_nulls_first)
+ compare = 1; /* NOT_NULL ">" NULL */
+ else
+ compare = -1; /* NOT_NULL "<" NULL */
+ }
+ else
+ {
+ compare = datum1 < datum2 ? -1 : datum1 > datum2 ? 1 : 0;
+ if (ssup->ssup_reverse)
+ INVERT_COMPARE_RESULT(compare);
+ }
+
+ return compare;
+}
+
+#if SIZEOF_DATUM >= 8
+static inline int
+ApplySignedSortComparator(Datum datum1, bool isNull1,
+ Datum datum2, bool isNull2,
+ SortSupport ssup)
+{
+ int compare;
+
+ if (isNull1)
+ {
+ if (isNull2)
+ compare = 0; /* NULL "=" NULL */
+ else if (ssup->ssup_nulls_first)
+ compare = -1; /* NULL "<" NOT_NULL */
+ else
+ compare = 1; /* NULL ">" NOT_NULL */
+ }
+ else if (isNull2)
+ {
+ if (ssup->ssup_nulls_first)
+ compare = 1; /* NOT_NULL ">" NULL */
+ else
+ compare = -1; /* NOT_NULL "<" NULL */
+ }
+ else
+ {
+ compare = DatumGetInt64(datum1) < DatumGetInt64(datum2) ? -1 :
+ DatumGetInt64(datum1) > DatumGetInt64(datum2) ? 1 : 0;
+ if (ssup->ssup_reverse)
+ INVERT_COMPARE_RESULT(compare);
+ }
+
+ return compare;
+}
+#endif
+
+static inline int
+ApplyInt32SortComparator(Datum datum1, bool isNull1,
+ Datum datum2, bool isNull2,
+ SortSupport ssup)
+{
+ int compare;
+
+ if (isNull1)
+ {
+ if (isNull2)
+ compare = 0; /* NULL "=" NULL */
+ else if (ssup->ssup_nulls_first)
+ compare = -1; /* NULL "<" NOT_NULL */
+ else
+ compare = 1; /* NULL ">" NOT_NULL */
+ }
+ else if (isNull2)
+ {
+ if (ssup->ssup_nulls_first)
+ compare = 1; /* NOT_NULL ">" NULL */
+ else
+ compare = -1; /* NOT_NULL "<" NULL */
+ }
+ else
+ {
+ compare = DatumGetInt32(datum1) < DatumGetInt32(datum2) ? -1 :
+ DatumGetInt32(datum1) > DatumGetInt32(datum2) ? 1 : 0;
+ if (ssup->ssup_reverse)
+ INVERT_COMPARE_RESULT(compare);
+ }
+
+ return compare;
+}
+
+/*
+ * Apply a sort comparator function and return a 3-way comparison using full,
+ * authoritative comparator. This takes care of handling reverse-sort and
+ * NULLs-ordering properly.
+ */
+static inline int
+ApplySortAbbrevFullComparator(Datum datum1, bool isNull1,
+ Datum datum2, bool isNull2,
+ SortSupport ssup)
+{
+ int compare;
+
+ if (isNull1)
+ {
+ if (isNull2)
+ compare = 0; /* NULL "=" NULL */
+ else if (ssup->ssup_nulls_first)
+ compare = -1; /* NULL "<" NOT_NULL */
+ else
+ compare = 1; /* NULL ">" NOT_NULL */
+ }
+ else if (isNull2)
+ {
+ if (ssup->ssup_nulls_first)
+ compare = 1; /* NOT_NULL ">" NULL */
+ else
+ compare = -1; /* NOT_NULL "<" NULL */
+ }
+ else
+ {
+ compare = ssup->abbrev_full_comparator(datum1, datum2, ssup);
+ if (ssup->ssup_reverse)
+ INVERT_COMPARE_RESULT(compare);
+ }
+
+ return compare;
+}
+
+/*
+ * Datum comparison functions that we have specialized sort routines for.
+ * Datatypes that install these as their comparator or abbreviated comparator
+ * are eligible for faster sorting.
+ */
+extern int ssup_datum_unsigned_cmp(Datum x, Datum y, SortSupport ssup);
+#if SIZEOF_DATUM >= 8
+extern int ssup_datum_signed_cmp(Datum x, Datum y, SortSupport ssup);
+#endif
+extern int ssup_datum_int32_cmp(Datum x, Datum y, SortSupport ssup);
+
+/* Other functions in utils/sort/sortsupport.c */
+extern void PrepareSortSupportComparisonShim(Oid cmpFunc, SortSupport ssup);
+extern void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup);
+extern void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy,
+ SortSupport ssup);
+extern void PrepareSortSupportFromGistIndexRel(Relation indexRel, SortSupport ssup);
+
+#endif /* SORTSUPPORT_H */
diff --git a/pgsql/include/server/utils/spccache.h b/pgsql/include/server/utils/spccache.h
new file mode 100644
index 0000000000000000000000000000000000000000..c6c754a2ec4d4286efdcac53018713bb6e6df87e
--- /dev/null
+++ b/pgsql/include/server/utils/spccache.h
@@ -0,0 +1,21 @@
+/*-------------------------------------------------------------------------
+ *
+ * spccache.h
+ * Tablespace cache.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/spccache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SPCCACHE_H
+#define SPCCACHE_H
+
+extern void get_tablespace_page_costs(Oid spcid, float8 *spc_random_page_cost,
+ float8 *spc_seq_page_cost);
+extern int get_tablespace_io_concurrency(Oid spcid);
+extern int get_tablespace_maintenance_io_concurrency(Oid spcid);
+
+#endif /* SPCCACHE_H */
diff --git a/pgsql/include/server/utils/syscache.h b/pgsql/include/server/utils/syscache.h
new file mode 100644
index 0000000000000000000000000000000000000000..67ea6e4945275b062e38f9b7e30585e59c1f8603
--- /dev/null
+++ b/pgsql/include/server/utils/syscache.h
@@ -0,0 +1,227 @@
+/*-------------------------------------------------------------------------
+ *
+ * syscache.h
+ * System catalog cache definitions.
+ *
+ * See also lsyscache.h, which provides convenience routines for
+ * common cache-lookup operations.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/syscache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef SYSCACHE_H
+#define SYSCACHE_H
+
+#include "access/attnum.h"
+#include "access/htup.h"
+/* we intentionally do not include utils/catcache.h here */
+
+/*
+ * SysCache identifiers.
+ *
+ * The order of these identifiers must match the order
+ * of the entries in the array cacheinfo[] in syscache.c.
+ * Keep them in alphabetical order (renumbering only costs a
+ * backend rebuild).
+ */
+
+enum SysCacheIdentifier
+{
+ AGGFNOID = 0,
+ AMNAME,
+ AMOID,
+ AMOPOPID,
+ AMOPSTRATEGY,
+ AMPROCNUM,
+ ATTNAME,
+ ATTNUM,
+ AUTHMEMMEMROLE,
+ AUTHMEMROLEMEM,
+ AUTHNAME,
+ AUTHOID,
+ CASTSOURCETARGET,
+ CLAAMNAMENSP,
+ CLAOID,
+ COLLNAMEENCNSP,
+ COLLOID,
+ CONDEFAULT,
+ CONNAMENSP,
+ CONSTROID,
+ CONVOID,
+ DATABASEOID,
+ DEFACLROLENSPOBJ,
+ ENUMOID,
+ ENUMTYPOIDNAME,
+ EVENTTRIGGERNAME,
+ EVENTTRIGGEROID,
+ FOREIGNDATAWRAPPERNAME,
+ FOREIGNDATAWRAPPEROID,
+ FOREIGNSERVERNAME,
+ FOREIGNSERVEROID,
+ FOREIGNTABLEREL,
+ INDEXRELID,
+ LANGNAME,
+ LANGOID,
+ NAMESPACENAME,
+ NAMESPACEOID,
+ OPERNAMENSP,
+ OPEROID,
+ OPFAMILYAMNAMENSP,
+ OPFAMILYOID,
+ PARAMETERACLNAME,
+ PARAMETERACLOID,
+ PARTRELID,
+ PROCNAMEARGSNSP,
+ PROCOID,
+ PUBLICATIONNAME,
+ PUBLICATIONNAMESPACE,
+ PUBLICATIONNAMESPACEMAP,
+ PUBLICATIONOID,
+ PUBLICATIONREL,
+ PUBLICATIONRELMAP,
+ RANGEMULTIRANGE,
+ RANGETYPE,
+ RELNAMENSP,
+ RELOID,
+ REPLORIGIDENT,
+ REPLORIGNAME,
+ RULERELNAME,
+ SEQRELID,
+ STATEXTDATASTXOID,
+ STATEXTNAMENSP,
+ STATEXTOID,
+ STATRELATTINH,
+ SUBSCRIPTIONNAME,
+ SUBSCRIPTIONOID,
+ SUBSCRIPTIONRELMAP,
+ TABLESPACEOID,
+ TRFOID,
+ TRFTYPELANG,
+ TSCONFIGMAP,
+ TSCONFIGNAMENSP,
+ TSCONFIGOID,
+ TSDICTNAMENSP,
+ TSDICTOID,
+ TSPARSERNAMENSP,
+ TSPARSEROID,
+ TSTEMPLATENAMENSP,
+ TSTEMPLATEOID,
+ TYPENAMENSP,
+ TYPEOID,
+ USERMAPPINGOID,
+ USERMAPPINGUSERSERVER
+
+#define SysCacheSize (USERMAPPINGUSERSERVER + 1)
+};
+
+extern void InitCatalogCache(void);
+extern void InitCatalogCachePhase2(void);
+
+extern HeapTuple SearchSysCache(int cacheId,
+ Datum key1, Datum key2, Datum key3, Datum key4);
+
+/*
+ * The use of argument specific numbers is encouraged. They're faster, and
+ * insulates the caller from changes in the maximum number of keys.
+ */
+extern HeapTuple SearchSysCache1(int cacheId,
+ Datum key1);
+extern HeapTuple SearchSysCache2(int cacheId,
+ Datum key1, Datum key2);
+extern HeapTuple SearchSysCache3(int cacheId,
+ Datum key1, Datum key2, Datum key3);
+extern HeapTuple SearchSysCache4(int cacheId,
+ Datum key1, Datum key2, Datum key3, Datum key4);
+
+extern void ReleaseSysCache(HeapTuple tuple);
+
+/* convenience routines */
+extern HeapTuple SearchSysCacheCopy(int cacheId,
+ Datum key1, Datum key2, Datum key3, Datum key4);
+extern bool SearchSysCacheExists(int cacheId,
+ Datum key1, Datum key2, Datum key3, Datum key4);
+extern Oid GetSysCacheOid(int cacheId, AttrNumber oidcol,
+ Datum key1, Datum key2, Datum key3, Datum key4);
+
+extern HeapTuple SearchSysCacheAttName(Oid relid, const char *attname);
+extern HeapTuple SearchSysCacheCopyAttName(Oid relid, const char *attname);
+extern bool SearchSysCacheExistsAttName(Oid relid, const char *attname);
+
+extern HeapTuple SearchSysCacheAttNum(Oid relid, int16 attnum);
+extern HeapTuple SearchSysCacheCopyAttNum(Oid relid, int16 attnum);
+
+extern Datum SysCacheGetAttr(int cacheId, HeapTuple tup,
+ AttrNumber attributeNumber, bool *isNull);
+
+extern Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup,
+ AttrNumber attributeNumber);
+
+extern uint32 GetSysCacheHashValue(int cacheId,
+ Datum key1, Datum key2, Datum key3, Datum key4);
+
+/* list-search interface. Users of this must import catcache.h too */
+struct catclist;
+extern struct catclist *SearchSysCacheList(int cacheId, int nkeys,
+ Datum key1, Datum key2, Datum key3);
+
+extern void SysCacheInvalidate(int cacheId, uint32 hashValue);
+
+extern bool RelationInvalidatesSnapshotsOnly(Oid relid);
+extern bool RelationHasSysCache(Oid relid);
+extern bool RelationSupportsSysCache(Oid relid);
+
+/*
+ * The use of the macros below rather than direct calls to the corresponding
+ * functions is encouraged, as it insulates the caller from changes in the
+ * maximum number of keys.
+ */
+#define SearchSysCacheCopy1(cacheId, key1) \
+ SearchSysCacheCopy(cacheId, key1, 0, 0, 0)
+#define SearchSysCacheCopy2(cacheId, key1, key2) \
+ SearchSysCacheCopy(cacheId, key1, key2, 0, 0)
+#define SearchSysCacheCopy3(cacheId, key1, key2, key3) \
+ SearchSysCacheCopy(cacheId, key1, key2, key3, 0)
+#define SearchSysCacheCopy4(cacheId, key1, key2, key3, key4) \
+ SearchSysCacheCopy(cacheId, key1, key2, key3, key4)
+
+#define SearchSysCacheExists1(cacheId, key1) \
+ SearchSysCacheExists(cacheId, key1, 0, 0, 0)
+#define SearchSysCacheExists2(cacheId, key1, key2) \
+ SearchSysCacheExists(cacheId, key1, key2, 0, 0)
+#define SearchSysCacheExists3(cacheId, key1, key2, key3) \
+ SearchSysCacheExists(cacheId, key1, key2, key3, 0)
+#define SearchSysCacheExists4(cacheId, key1, key2, key3, key4) \
+ SearchSysCacheExists(cacheId, key1, key2, key3, key4)
+
+#define GetSysCacheOid1(cacheId, oidcol, key1) \
+ GetSysCacheOid(cacheId, oidcol, key1, 0, 0, 0)
+#define GetSysCacheOid2(cacheId, oidcol, key1, key2) \
+ GetSysCacheOid(cacheId, oidcol, key1, key2, 0, 0)
+#define GetSysCacheOid3(cacheId, oidcol, key1, key2, key3) \
+ GetSysCacheOid(cacheId, oidcol, key1, key2, key3, 0)
+#define GetSysCacheOid4(cacheId, oidcol, key1, key2, key3, key4) \
+ GetSysCacheOid(cacheId, oidcol, key1, key2, key3, key4)
+
+#define GetSysCacheHashValue1(cacheId, key1) \
+ GetSysCacheHashValue(cacheId, key1, 0, 0, 0)
+#define GetSysCacheHashValue2(cacheId, key1, key2) \
+ GetSysCacheHashValue(cacheId, key1, key2, 0, 0)
+#define GetSysCacheHashValue3(cacheId, key1, key2, key3) \
+ GetSysCacheHashValue(cacheId, key1, key2, key3, 0)
+#define GetSysCacheHashValue4(cacheId, key1, key2, key3, key4) \
+ GetSysCacheHashValue(cacheId, key1, key2, key3, key4)
+
+#define SearchSysCacheList1(cacheId, key1) \
+ SearchSysCacheList(cacheId, 1, key1, 0, 0)
+#define SearchSysCacheList2(cacheId, key1, key2) \
+ SearchSysCacheList(cacheId, 2, key1, key2, 0)
+#define SearchSysCacheList3(cacheId, key1, key2, key3) \
+ SearchSysCacheList(cacheId, 3, key1, key2, key3)
+
+#define ReleaseSysCacheList(x) ReleaseCatCacheList(x)
+
+#endif /* SYSCACHE_H */
diff --git a/pgsql/include/server/utils/timeout.h b/pgsql/include/server/utils/timeout.h
new file mode 100644
index 0000000000000000000000000000000000000000..e561a1cde920ce018b081f9c915a9c82eeda2d9b
--- /dev/null
+++ b/pgsql/include/server/utils/timeout.h
@@ -0,0 +1,95 @@
+/*-------------------------------------------------------------------------
+ *
+ * timeout.h
+ * Routines to multiplex SIGALRM interrupts for multiple timeout reasons.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/timeout.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TIMEOUT_H
+#define TIMEOUT_H
+
+#include "datatype/timestamp.h"
+
+/*
+ * Identifiers for timeout reasons. Note that in case multiple timeouts
+ * trigger at the same time, they are serviced in the order of this enum.
+ */
+typedef enum TimeoutId
+{
+ /* Predefined timeout reasons */
+ STARTUP_PACKET_TIMEOUT,
+ DEADLOCK_TIMEOUT,
+ LOCK_TIMEOUT,
+ STATEMENT_TIMEOUT,
+ STANDBY_DEADLOCK_TIMEOUT,
+ STANDBY_TIMEOUT,
+ STANDBY_LOCK_TIMEOUT,
+ IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
+ IDLE_SESSION_TIMEOUT,
+ IDLE_STATS_UPDATE_TIMEOUT,
+ CLIENT_CONNECTION_CHECK_TIMEOUT,
+ STARTUP_PROGRESS_TIMEOUT,
+ /* First user-definable timeout reason */
+ USER_TIMEOUT,
+ /* Maximum number of timeout reasons */
+ MAX_TIMEOUTS = USER_TIMEOUT + 10
+} TimeoutId;
+
+/* callback function signature */
+typedef void (*timeout_handler_proc) (void);
+
+/*
+ * Parameter structure for setting multiple timeouts at once
+ */
+typedef enum TimeoutType
+{
+ TMPARAM_AFTER,
+ TMPARAM_AT,
+ TMPARAM_EVERY
+} TimeoutType;
+
+typedef struct
+{
+ TimeoutId id; /* timeout to set */
+ TimeoutType type; /* TMPARAM_AFTER or TMPARAM_AT */
+ int delay_ms; /* only used for TMPARAM_AFTER/EVERY */
+ TimestampTz fin_time; /* only used for TMPARAM_AT */
+} EnableTimeoutParams;
+
+/*
+ * Parameter structure for clearing multiple timeouts at once
+ */
+typedef struct
+{
+ TimeoutId id; /* timeout to clear */
+ bool keep_indicator; /* keep the indicator flag? */
+} DisableTimeoutParams;
+
+/* timeout setup */
+extern void InitializeTimeouts(void);
+extern TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler);
+extern void reschedule_timeouts(void);
+
+/* timeout operation */
+extern void enable_timeout_after(TimeoutId id, int delay_ms);
+extern void enable_timeout_every(TimeoutId id, TimestampTz fin_time,
+ int delay_ms);
+extern void enable_timeout_at(TimeoutId id, TimestampTz fin_time);
+extern void enable_timeouts(const EnableTimeoutParams *timeouts, int count);
+extern void disable_timeout(TimeoutId id, bool keep_indicator);
+extern void disable_timeouts(const DisableTimeoutParams *timeouts, int count);
+extern void disable_all_timeouts(bool keep_indicators);
+
+/* accessors */
+extern bool get_timeout_active(TimeoutId id);
+extern bool get_timeout_indicator(TimeoutId id, bool reset_indicator);
+extern TimestampTz get_timeout_start_time(TimeoutId id);
+extern TimestampTz get_timeout_finish_time(TimeoutId id);
+
+#endif /* TIMEOUT_H */
diff --git a/pgsql/include/server/utils/timestamp.h b/pgsql/include/server/utils/timestamp.h
new file mode 100644
index 0000000000000000000000000000000000000000..c4dd96c8c97c85924afc413b7fe4b6663212e966
--- /dev/null
+++ b/pgsql/include/server/utils/timestamp.h
@@ -0,0 +1,147 @@
+/*-------------------------------------------------------------------------
+ *
+ * timestamp.h
+ * Definitions for the SQL "timestamp" and "interval" types.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/timestamp.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TIMESTAMP_H
+#define TIMESTAMP_H
+
+#include "datatype/timestamp.h"
+#include "fmgr.h"
+#include "pgtime.h"
+
+
+/*
+ * Functions for fmgr-callable functions.
+ *
+ * For Timestamp, we make use of the same support routines as for int64.
+ * Therefore Timestamp is pass-by-reference if and only if int64 is!
+ */
+static inline Timestamp
+DatumGetTimestamp(Datum X)
+{
+ return (Timestamp) DatumGetInt64(X);
+}
+
+static inline TimestampTz
+DatumGetTimestampTz(Datum X)
+{
+ return (TimestampTz) DatumGetInt64(X);
+}
+
+static inline Interval *
+DatumGetIntervalP(Datum X)
+{
+ return (Interval *) DatumGetPointer(X);
+}
+
+static inline Datum
+TimestampGetDatum(Timestamp X)
+{
+ return Int64GetDatum(X);
+}
+
+static inline Datum
+TimestampTzGetDatum(TimestampTz X)
+{
+ return Int64GetDatum(X);
+}
+
+static inline Datum
+IntervalPGetDatum(const Interval *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_TIMESTAMP(n) DatumGetTimestamp(PG_GETARG_DATUM(n))
+#define PG_GETARG_TIMESTAMPTZ(n) DatumGetTimestampTz(PG_GETARG_DATUM(n))
+#define PG_GETARG_INTERVAL_P(n) DatumGetIntervalP(PG_GETARG_DATUM(n))
+
+#define PG_RETURN_TIMESTAMP(x) return TimestampGetDatum(x)
+#define PG_RETURN_TIMESTAMPTZ(x) return TimestampTzGetDatum(x)
+#define PG_RETURN_INTERVAL_P(x) return IntervalPGetDatum(x)
+
+
+#define TIMESTAMP_MASK(b) (1 << (b))
+#define INTERVAL_MASK(b) (1 << (b))
+
+/* Macros to handle packing and unpacking the typmod field for intervals */
+#define INTERVAL_FULL_RANGE (0x7FFF)
+#define INTERVAL_RANGE_MASK (0x7FFF)
+#define INTERVAL_FULL_PRECISION (0xFFFF)
+#define INTERVAL_PRECISION_MASK (0xFFFF)
+#define INTERVAL_TYPMOD(p,r) ((((r) & INTERVAL_RANGE_MASK) << 16) | ((p) & INTERVAL_PRECISION_MASK))
+#define INTERVAL_PRECISION(t) ((t) & INTERVAL_PRECISION_MASK)
+#define INTERVAL_RANGE(t) (((t) >> 16) & INTERVAL_RANGE_MASK)
+
+/* Macros for doing timestamp arithmetic without assuming timestamp's units */
+#define TimestampTzPlusMilliseconds(tz,ms) ((tz) + ((ms) * (int64) 1000))
+#define TimestampTzPlusSeconds(tz,s) ((tz) + ((s) * (int64) 1000000))
+
+
+/* Set at postmaster start */
+extern PGDLLIMPORT TimestampTz PgStartTime;
+
+/* Set at configuration reload */
+extern PGDLLIMPORT TimestampTz PgReloadTime;
+
+
+/* Internal routines (not fmgr-callable) */
+
+extern int32 anytimestamp_typmod_check(bool istz, int32 typmod);
+
+extern TimestampTz GetCurrentTimestamp(void);
+extern TimestampTz GetSQLCurrentTimestamp(int32 typmod);
+extern Timestamp GetSQLLocalTimestamp(int32 typmod);
+extern void TimestampDifference(TimestampTz start_time, TimestampTz stop_time,
+ long *secs, int *microsecs);
+extern long TimestampDifferenceMilliseconds(TimestampTz start_time,
+ TimestampTz stop_time);
+extern bool TimestampDifferenceExceeds(TimestampTz start_time,
+ TimestampTz stop_time,
+ int msec);
+
+extern TimestampTz time_t_to_timestamptz(pg_time_t tm);
+extern pg_time_t timestamptz_to_time_t(TimestampTz t);
+
+extern const char *timestamptz_to_str(TimestampTz t);
+
+extern int tm2timestamp(struct pg_tm *tm, fsec_t fsec, int *tzp, Timestamp *result);
+extern int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm,
+ fsec_t *fsec, const char **tzn, pg_tz *attimezone);
+extern void dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec);
+
+extern void interval2itm(Interval span, struct pg_itm *itm);
+extern int itm2interval(struct pg_itm *itm, Interval *span);
+extern int itmin2interval(struct pg_itm_in *itm_in, Interval *span);
+
+extern Timestamp SetEpochTimestamp(void);
+extern void GetEpochTime(struct pg_tm *tm);
+
+extern int timestamp_cmp_internal(Timestamp dt1, Timestamp dt2);
+
+/* timestamp comparison works for timestamptz also */
+#define timestamptz_cmp_internal(dt1,dt2) timestamp_cmp_internal(dt1, dt2)
+
+extern TimestampTz timestamp2timestamptz_opt_overflow(Timestamp timestamp,
+ int *overflow);
+extern int32 timestamp_cmp_timestamptz_internal(Timestamp timestampVal,
+ TimestampTz dt2);
+
+extern int isoweek2j(int year, int week);
+extern void isoweek2date(int woy, int *year, int *mon, int *mday);
+extern void isoweekdate2date(int isoweek, int wday, int *year, int *mon, int *mday);
+extern int date2isoweek(int year, int mon, int mday);
+extern int date2isoyear(int year, int mon, int mday);
+extern int date2isoyearday(int year, int mon, int mday);
+
+extern bool TimestampTimestampTzRequiresRewrite(void);
+
+#endif /* TIMESTAMP_H */
diff --git a/pgsql/include/server/utils/tuplesort.h b/pgsql/include/server/utils/tuplesort.h
new file mode 100644
index 0000000000000000000000000000000000000000..af057b6358efa81135168110e58f039e2c43bace
--- /dev/null
+++ b/pgsql/include/server/utils/tuplesort.h
@@ -0,0 +1,445 @@
+/*-------------------------------------------------------------------------
+ *
+ * tuplesort.h
+ * Generalized tuple sorting routines.
+ *
+ * This module handles sorting of heap tuples, index tuples, or single
+ * Datums (and could easily support other kinds of sortable objects,
+ * if necessary). It works efficiently for both small and large amounts
+ * of data. Small amounts are sorted in-memory using qsort(). Large
+ * amounts are sorted using temporary files and a standard external sort
+ * algorithm. Parallel sorts use a variant of this external sort
+ * algorithm, and are typically only used for large amounts of data.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/tuplesort.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TUPLESORT_H
+#define TUPLESORT_H
+
+#include "access/itup.h"
+#include "executor/tuptable.h"
+#include "storage/dsm.h"
+#include "utils/logtape.h"
+#include "utils/relcache.h"
+#include "utils/sortsupport.h"
+
+
+/*
+ * Tuplesortstate and Sharedsort are opaque types whose details are not
+ * known outside tuplesort.c.
+ */
+typedef struct Tuplesortstate Tuplesortstate;
+typedef struct Sharedsort Sharedsort;
+
+/*
+ * Tuplesort parallel coordination state, allocated by each participant in
+ * local memory. Participant caller initializes everything. See usage notes
+ * below.
+ */
+typedef struct SortCoordinateData
+{
+ /* Worker process? If not, must be leader. */
+ bool isWorker;
+
+ /*
+ * Leader-process-passed number of participants known launched (workers
+ * set this to -1). Includes state within leader needed for it to
+ * participate as a worker, if any.
+ */
+ int nParticipants;
+
+ /* Private opaque state (points to shared memory) */
+ Sharedsort *sharedsort;
+} SortCoordinateData;
+
+typedef struct SortCoordinateData *SortCoordinate;
+
+/*
+ * Data structures for reporting sort statistics. Note that
+ * TuplesortInstrumentation can't contain any pointers because we
+ * sometimes put it in shared memory.
+ *
+ * The parallel-sort infrastructure relies on having a zero TuplesortMethod
+ * to indicate that a worker never did anything, so we assign zero to
+ * SORT_TYPE_STILL_IN_PROGRESS. The other values of this enum can be
+ * OR'ed together to represent a situation where different workers used
+ * different methods, so we need a separate bit for each one. Keep the
+ * NUM_TUPLESORTMETHODS constant in sync with the number of bits!
+ */
+typedef enum
+{
+ SORT_TYPE_STILL_IN_PROGRESS = 0,
+ SORT_TYPE_TOP_N_HEAPSORT = 1 << 0,
+ SORT_TYPE_QUICKSORT = 1 << 1,
+ SORT_TYPE_EXTERNAL_SORT = 1 << 2,
+ SORT_TYPE_EXTERNAL_MERGE = 1 << 3
+} TuplesortMethod;
+
+#define NUM_TUPLESORTMETHODS 4
+
+typedef enum
+{
+ SORT_SPACE_TYPE_DISK,
+ SORT_SPACE_TYPE_MEMORY
+} TuplesortSpaceType;
+
+/* Bitwise option flags for tuple sorts */
+#define TUPLESORT_NONE 0
+
+/* specifies whether non-sequential access to the sort result is required */
+#define TUPLESORT_RANDOMACCESS (1 << 0)
+
+/* specifies if the tuplesort is able to support bounded sorts */
+#define TUPLESORT_ALLOWBOUNDED (1 << 1)
+
+typedef struct TuplesortInstrumentation
+{
+ TuplesortMethod sortMethod; /* sort algorithm used */
+ TuplesortSpaceType spaceType; /* type of space spaceUsed represents */
+ int64 spaceUsed; /* space consumption, in kB */
+} TuplesortInstrumentation;
+
+/*
+ * The objects we actually sort are SortTuple structs. These contain
+ * a pointer to the tuple proper (might be a MinimalTuple or IndexTuple),
+ * which is a separate palloc chunk --- we assume it is just one chunk and
+ * can be freed by a simple pfree() (except during merge, when we use a
+ * simple slab allocator). SortTuples also contain the tuple's first key
+ * column in Datum/nullflag format, and a source/input tape number that
+ * tracks which tape each heap element/slot belongs to during merging.
+ *
+ * Storing the first key column lets us save heap_getattr or index_getattr
+ * calls during tuple comparisons. We could extract and save all the key
+ * columns not just the first, but this would increase code complexity and
+ * overhead, and wouldn't actually save any comparison cycles in the common
+ * case where the first key determines the comparison result. Note that
+ * for a pass-by-reference datatype, datum1 points into the "tuple" storage.
+ *
+ * There is one special case: when the sort support infrastructure provides an
+ * "abbreviated key" representation, where the key is (typically) a pass by
+ * value proxy for a pass by reference type. In this case, the abbreviated key
+ * is stored in datum1 in place of the actual first key column.
+ *
+ * When sorting single Datums, the data value is represented directly by
+ * datum1/isnull1 for pass by value types (or null values). If the datatype is
+ * pass-by-reference and isnull1 is false, then "tuple" points to a separately
+ * palloc'd data value, otherwise "tuple" is NULL. The value of datum1 is then
+ * either the same pointer as "tuple", or is an abbreviated key value as
+ * described above. Accordingly, "tuple" is always used in preference to
+ * datum1 as the authoritative value for pass-by-reference cases.
+ */
+typedef struct
+{
+ void *tuple; /* the tuple itself */
+ Datum datum1; /* value of first key column */
+ bool isnull1; /* is first key column NULL? */
+ int srctape; /* source tape number */
+} SortTuple;
+
+typedef int (*SortTupleComparator) (const SortTuple *a, const SortTuple *b,
+ Tuplesortstate *state);
+
+/*
+ * The public part of a Tuple sort operation state. This data structure
+ * contains the definition of sort-variant-specific interface methods and
+ * the part of Tuple sort operation state required by their implementations.
+ */
+typedef struct
+{
+ /*
+ * These function pointers decouple the routines that must know what kind
+ * of tuple we are sorting from the routines that don't need to know it.
+ * They are set up by the tuplesort_begin_xxx routines.
+ *
+ * Function to compare two tuples; result is per qsort() convention, ie:
+ * <0, 0, >0 according as ab. The API must match
+ * qsort_arg_comparator.
+ */
+ SortTupleComparator comparetup;
+
+ /*
+ * Alter datum1 representation in the SortTuple's array back from the
+ * abbreviated key to the first column value.
+ */
+ void (*removeabbrev) (Tuplesortstate *state, SortTuple *stups,
+ int count);
+
+ /*
+ * Function to write a stored tuple onto tape. The representation of the
+ * tuple on tape need not be the same as it is in memory.
+ */
+ void (*writetup) (Tuplesortstate *state, LogicalTape *tape,
+ SortTuple *stup);
+
+ /*
+ * Function to read a stored tuple from tape back into memory. 'len' is
+ * the already-read length of the stored tuple. The tuple is allocated
+ * from the slab memory arena, or is palloc'd, see
+ * tuplesort_readtup_alloc().
+ */
+ void (*readtup) (Tuplesortstate *state, SortTuple *stup,
+ LogicalTape *tape, unsigned int len);
+
+ /*
+ * Function to do some specific release of resources for the sort variant.
+ * In particular, this function should free everything stored in the "arg"
+ * field, which wouldn't be cleared on reset of the Tuple sort memory
+ * contexts. This can be NULL if nothing specific needs to be done.
+ */
+ void (*freestate) (Tuplesortstate *state);
+
+ /*
+ * The subsequent fields are used in the implementations of the functions
+ * above.
+ */
+ MemoryContext maincontext; /* memory context for tuple sort metadata that
+ * persists across multiple batches */
+ MemoryContext sortcontext; /* memory context holding most sort data */
+ MemoryContext tuplecontext; /* sub-context of sortcontext for tuple data */
+
+ /*
+ * Whether SortTuple's datum1 and isnull1 members are maintained by the
+ * above routines. If not, some sort specializations are disabled.
+ */
+ bool haveDatum1;
+
+ /*
+ * The sortKeys variable is used by every case other than the hash index
+ * case; it is set by tuplesort_begin_xxx. tupDesc is only used by the
+ * MinimalTuple and CLUSTER routines, though.
+ */
+ int nKeys; /* number of columns in sort key */
+ SortSupport sortKeys; /* array of length nKeys */
+
+ /*
+ * This variable is shared by the single-key MinimalTuple case and the
+ * Datum case (which both use qsort_ssup()). Otherwise, it's NULL. The
+ * presence of a value in this field is also checked by various sort
+ * specialization functions as an optimization when comparing the leading
+ * key in a tiebreak situation to determine if there are any subsequent
+ * keys to sort on.
+ */
+ SortSupport onlyKey;
+
+ int sortopt; /* Bitmask of flags used to setup sort */
+
+ bool tuples; /* Can SortTuple.tuple ever be set? */
+
+ void *arg; /* Specific information for the sort variant */
+} TuplesortPublic;
+
+/* Sort parallel code from state for sort__start probes */
+#define PARALLEL_SORT(coordinate) (coordinate == NULL || \
+ (coordinate)->sharedsort == NULL ? 0 : \
+ (coordinate)->isWorker ? 1 : 2)
+
+#define TuplesortstateGetPublic(state) ((TuplesortPublic *) state)
+
+/* When using this macro, beware of double evaluation of len */
+#define LogicalTapeReadExact(tape, ptr, len) \
+ do { \
+ if (LogicalTapeRead(tape, ptr, len) != (size_t) (len)) \
+ elog(ERROR, "unexpected end of data"); \
+ } while(0)
+
+/*
+ * We provide multiple interfaces to what is essentially the same code,
+ * since different callers have different data to be sorted and want to
+ * specify the sort key information differently. There are two APIs for
+ * sorting HeapTuples and two more for sorting IndexTuples. Yet another
+ * API supports sorting bare Datums.
+ *
+ * Serial sort callers should pass NULL for their coordinate argument.
+ *
+ * The "heap" API actually stores/sorts MinimalTuples, which means it doesn't
+ * preserve the system columns (tuple identity and transaction visibility
+ * info). The sort keys are specified by column numbers within the tuples
+ * and sort operator OIDs. We save some cycles by passing and returning the
+ * tuples in TupleTableSlots, rather than forming actual HeapTuples (which'd
+ * have to be converted to MinimalTuples). This API works well for sorts
+ * executed as parts of plan trees.
+ *
+ * The "cluster" API stores/sorts full HeapTuples including all visibility
+ * info. The sort keys are specified by reference to a btree index that is
+ * defined on the relation to be sorted. Note that putheaptuple/getheaptuple
+ * go with this API, not the "begin_heap" one!
+ *
+ * The "index_btree" API stores/sorts IndexTuples (preserving all their
+ * header fields). The sort keys are specified by a btree index definition.
+ *
+ * The "index_hash" API is similar to index_btree, but the tuples are
+ * actually sorted by their hash codes not the raw data.
+ *
+ * Parallel sort callers are required to coordinate multiple tuplesort states
+ * in a leader process and one or more worker processes. The leader process
+ * must launch workers, and have each perform an independent "partial"
+ * tuplesort, typically fed by the parallel heap interface. The leader later
+ * produces the final output (internally, it merges runs output by workers).
+ *
+ * Callers must do the following to perform a sort in parallel using multiple
+ * worker processes:
+ *
+ * 1. Request tuplesort-private shared memory for n workers. Use
+ * tuplesort_estimate_shared() to get the required size.
+ * 2. Have leader process initialize allocated shared memory using
+ * tuplesort_initialize_shared(). Launch workers.
+ * 3. Initialize a coordinate argument within both the leader process, and
+ * for each worker process. This has a pointer to the shared
+ * tuplesort-private structure, as well as some caller-initialized fields.
+ * Leader's coordinate argument reliably indicates number of workers
+ * launched (this is unused by workers).
+ * 4. Begin a tuplesort using some appropriate tuplesort_begin* routine,
+ * (passing the coordinate argument) within each worker. The workMem
+ * arguments need not be identical. All other arguments should match
+ * exactly, though.
+ * 5. tuplesort_attach_shared() should be called by all workers. Feed tuples
+ * to each worker, and call tuplesort_performsort() within each when input
+ * is exhausted.
+ * 6. Call tuplesort_end() in each worker process. Worker processes can shut
+ * down once tuplesort_end() returns.
+ * 7. Begin a tuplesort in the leader using the same tuplesort_begin*
+ * routine, passing a leader-appropriate coordinate argument (this can
+ * happen as early as during step 3, actually, since we only need to know
+ * the number of workers successfully launched). The leader must now wait
+ * for workers to finish. Caller must use own mechanism for ensuring that
+ * next step isn't reached until all workers have called and returned from
+ * tuplesort_performsort(). (Note that it's okay if workers have already
+ * also called tuplesort_end() by then.)
+ * 8. Call tuplesort_performsort() in leader. Consume output using the
+ * appropriate tuplesort_get* routine. Leader can skip this step if
+ * tuplesort turns out to be unnecessary.
+ * 9. Call tuplesort_end() in leader.
+ *
+ * This division of labor assumes nothing about how input tuples are produced,
+ * but does require that caller combine the state of multiple tuplesorts for
+ * any purpose other than producing the final output. For example, callers
+ * must consider that tuplesort_get_stats() reports on only one worker's role
+ * in a sort (or the leader's role), and not statistics for the sort as a
+ * whole.
+ *
+ * Note that callers may use the leader process to sort runs as if it was an
+ * independent worker process (prior to the process performing a leader sort
+ * to produce the final sorted output). Doing so only requires a second
+ * "partial" tuplesort within the leader process, initialized like that of a
+ * worker process. The steps above don't touch on this directly. The only
+ * difference is that the tuplesort_attach_shared() call is never needed within
+ * leader process, because the backend as a whole holds the shared fileset
+ * reference. A worker Tuplesortstate in leader is expected to do exactly the
+ * same amount of total initial processing work as a worker process
+ * Tuplesortstate, since the leader process has nothing else to do before
+ * workers finish.
+ *
+ * Note that only a very small amount of memory will be allocated prior to
+ * the leader state first consuming input, and that workers will free the
+ * vast majority of their memory upon returning from tuplesort_performsort().
+ * Callers can rely on this to arrange for memory to be used in a way that
+ * respects a workMem-style budget across an entire parallel sort operation.
+ *
+ * Callers are responsible for parallel safety in general. However, they
+ * can at least rely on there being no parallel safety hazards within
+ * tuplesort, because tuplesort thinks of the sort as several independent
+ * sorts whose results are combined. Since, in general, the behavior of
+ * sort operators is immutable, caller need only worry about the parallel
+ * safety of whatever the process is through which input tuples are
+ * generated (typically, caller uses a parallel heap scan).
+ */
+
+
+extern Tuplesortstate *tuplesort_begin_common(int workMem,
+ SortCoordinate coordinate,
+ int sortopt);
+extern void tuplesort_set_bound(Tuplesortstate *state, int64 bound);
+extern bool tuplesort_used_bound(Tuplesortstate *state);
+extern void tuplesort_puttuple_common(Tuplesortstate *state,
+ SortTuple *tuple, bool useAbbrev);
+extern void tuplesort_performsort(Tuplesortstate *state);
+extern bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward,
+ SortTuple *stup);
+extern bool tuplesort_skiptuples(Tuplesortstate *state, int64 ntuples,
+ bool forward);
+extern void tuplesort_end(Tuplesortstate *state);
+extern void tuplesort_reset(Tuplesortstate *state);
+
+extern void tuplesort_get_stats(Tuplesortstate *state,
+ TuplesortInstrumentation *stats);
+extern const char *tuplesort_method_name(TuplesortMethod m);
+extern const char *tuplesort_space_type_name(TuplesortSpaceType t);
+
+extern int tuplesort_merge_order(int64 allowedMem);
+
+extern Size tuplesort_estimate_shared(int nWorkers);
+extern void tuplesort_initialize_shared(Sharedsort *shared, int nWorkers,
+ dsm_segment *seg);
+extern void tuplesort_attach_shared(Sharedsort *shared, dsm_segment *seg);
+
+/*
+ * These routines may only be called if TUPLESORT_RANDOMACCESS was specified
+ * during tuplesort_begin_*. Additionally backwards scan in gettuple/getdatum
+ * also require TUPLESORT_RANDOMACCESS. Note that parallel sorts do not
+ * support random access.
+ */
+extern void tuplesort_rescan(Tuplesortstate *state);
+extern void tuplesort_markpos(Tuplesortstate *state);
+extern void tuplesort_restorepos(Tuplesortstate *state);
+
+extern void *tuplesort_readtup_alloc(Tuplesortstate *state, Size tuplen);
+
+
+/* tuplesortvariants.c */
+
+extern Tuplesortstate *tuplesort_begin_heap(TupleDesc tupDesc,
+ int nkeys, AttrNumber *attNums,
+ Oid *sortOperators, Oid *sortCollations,
+ bool *nullsFirstFlags,
+ int workMem, SortCoordinate coordinate,
+ int sortopt);
+extern Tuplesortstate *tuplesort_begin_cluster(TupleDesc tupDesc,
+ Relation indexRel, int workMem,
+ SortCoordinate coordinate,
+ int sortopt);
+extern Tuplesortstate *tuplesort_begin_index_btree(Relation heapRel,
+ Relation indexRel,
+ bool enforceUnique,
+ bool uniqueNullsNotDistinct,
+ int workMem, SortCoordinate coordinate,
+ int sortopt);
+extern Tuplesortstate *tuplesort_begin_index_hash(Relation heapRel,
+ Relation indexRel,
+ uint32 high_mask,
+ uint32 low_mask,
+ uint32 max_buckets,
+ int workMem, SortCoordinate coordinate,
+ int sortopt);
+extern Tuplesortstate *tuplesort_begin_index_gist(Relation heapRel,
+ Relation indexRel,
+ int workMem, SortCoordinate coordinate,
+ int sortopt);
+extern Tuplesortstate *tuplesort_begin_datum(Oid datumType,
+ Oid sortOperator, Oid sortCollation,
+ bool nullsFirstFlag,
+ int workMem, SortCoordinate coordinate,
+ int sortopt);
+
+extern void tuplesort_puttupleslot(Tuplesortstate *state,
+ TupleTableSlot *slot);
+extern void tuplesort_putheaptuple(Tuplesortstate *state, HeapTuple tup);
+extern void tuplesort_putindextuplevalues(Tuplesortstate *state,
+ Relation rel, ItemPointer self,
+ Datum *values, bool *isnull);
+extern void tuplesort_putdatum(Tuplesortstate *state, Datum val,
+ bool isNull);
+
+extern bool tuplesort_gettupleslot(Tuplesortstate *state, bool forward,
+ bool copy, TupleTableSlot *slot, Datum *abbrev);
+extern HeapTuple tuplesort_getheaptuple(Tuplesortstate *state, bool forward);
+extern IndexTuple tuplesort_getindextuple(Tuplesortstate *state, bool forward);
+extern bool tuplesort_getdatum(Tuplesortstate *state, bool forward, bool copy,
+ Datum *val, bool *isNull, Datum *abbrev);
+
+
+#endif /* TUPLESORT_H */
diff --git a/pgsql/include/server/utils/tuplestore.h b/pgsql/include/server/utils/tuplestore.h
new file mode 100644
index 0000000000000000000000000000000000000000..36424b80b1b9ef9fa43c40941a5fd84b8af77709
--- /dev/null
+++ b/pgsql/include/server/utils/tuplestore.h
@@ -0,0 +1,91 @@
+/*-------------------------------------------------------------------------
+ *
+ * tuplestore.h
+ * Generalized routines for temporary tuple storage.
+ *
+ * This module handles temporary storage of tuples for purposes such
+ * as Materialize nodes, hashjoin batch files, etc. It is essentially
+ * a dumbed-down version of tuplesort.c; it does no sorting of tuples
+ * but can only store and regurgitate a sequence of tuples. However,
+ * because no sort is required, it is allowed to start reading the sequence
+ * before it has all been written. This is particularly useful for cursors,
+ * because it allows random access within the already-scanned portion of
+ * a query without having to process the underlying scan to completion.
+ * Also, it is possible to support multiple independent read pointers.
+ *
+ * A temporary file is used to handle the data if it exceeds the
+ * space limit specified by the caller.
+ *
+ * Beginning in Postgres 8.2, what is stored is just MinimalTuples;
+ * callers cannot expect valid system columns in regurgitated tuples.
+ * Also, we have changed the API to return tuples in TupleTableSlots,
+ * so that there is a check to prevent attempted access to system columns.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/tuplestore.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TUPLESTORE_H
+#define TUPLESTORE_H
+
+#include "executor/tuptable.h"
+
+
+/* Tuplestorestate is an opaque type whose details are not known outside
+ * tuplestore.c.
+ */
+typedef struct Tuplestorestate Tuplestorestate;
+
+/*
+ * Currently we only need to store MinimalTuples, but it would be easy
+ * to support the same behavior for IndexTuples and/or bare Datums.
+ */
+
+extern Tuplestorestate *tuplestore_begin_heap(bool randomAccess,
+ bool interXact,
+ int maxKBytes);
+
+extern void tuplestore_set_eflags(Tuplestorestate *state, int eflags);
+
+extern void tuplestore_puttupleslot(Tuplestorestate *state,
+ TupleTableSlot *slot);
+extern void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple);
+extern void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc,
+ Datum *values, bool *isnull);
+
+/* Backwards compatibility macro */
+#define tuplestore_donestoring(state) ((void) 0)
+
+extern int tuplestore_alloc_read_pointer(Tuplestorestate *state, int eflags);
+
+extern void tuplestore_select_read_pointer(Tuplestorestate *state, int ptr);
+
+extern void tuplestore_copy_read_pointer(Tuplestorestate *state,
+ int srcptr, int destptr);
+
+extern void tuplestore_trim(Tuplestorestate *state);
+
+extern bool tuplestore_in_memory(Tuplestorestate *state);
+
+extern bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward,
+ bool copy, TupleTableSlot *slot);
+
+extern bool tuplestore_advance(Tuplestorestate *state, bool forward);
+
+extern bool tuplestore_skiptuples(Tuplestorestate *state,
+ int64 ntuples, bool forward);
+
+extern int64 tuplestore_tuple_count(Tuplestorestate *state);
+
+extern bool tuplestore_ateof(Tuplestorestate *state);
+
+extern void tuplestore_rescan(Tuplestorestate *state);
+
+extern void tuplestore_clear(Tuplestorestate *state);
+
+extern void tuplestore_end(Tuplestorestate *state);
+
+#endif /* TUPLESTORE_H */
diff --git a/pgsql/include/server/utils/typcache.h b/pgsql/include/server/utils/typcache.h
new file mode 100644
index 0000000000000000000000000000000000000000..95f3a9ee308e92eebec5daf0af06269bc7c6dbfd
--- /dev/null
+++ b/pgsql/include/server/utils/typcache.h
@@ -0,0 +1,209 @@
+/*-------------------------------------------------------------------------
+ *
+ * typcache.h
+ * Type cache definitions.
+ *
+ * The type cache exists to speed lookup of certain information about data
+ * types that is not directly available from a type's pg_type row.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/typcache.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TYPCACHE_H
+#define TYPCACHE_H
+
+#include "access/tupdesc.h"
+#include "fmgr.h"
+#include "storage/dsm.h"
+#include "utils/dsa.h"
+
+
+/* DomainConstraintCache is an opaque struct known only within typcache.c */
+typedef struct DomainConstraintCache DomainConstraintCache;
+
+/* TypeCacheEnumData is an opaque struct known only within typcache.c */
+struct TypeCacheEnumData;
+
+typedef struct TypeCacheEntry
+{
+ /* typeId is the hash lookup key and MUST BE FIRST */
+ Oid type_id; /* OID of the data type */
+
+ uint32 type_id_hash; /* hashed value of the OID */
+
+ /* some subsidiary information copied from the pg_type row */
+ int16 typlen;
+ bool typbyval;
+ char typalign;
+ char typstorage;
+ char typtype;
+ Oid typrelid;
+ Oid typsubscript;
+ Oid typelem;
+ Oid typcollation;
+
+ /*
+ * Information obtained from opfamily entries
+ *
+ * These will be InvalidOid if no match could be found, or if the
+ * information hasn't yet been requested. Also note that for array and
+ * composite types, typcache.c checks that the contained types are
+ * comparable or hashable before allowing eq_opr etc to become set.
+ */
+ Oid btree_opf; /* the default btree opclass' family */
+ Oid btree_opintype; /* the default btree opclass' opcintype */
+ Oid hash_opf; /* the default hash opclass' family */
+ Oid hash_opintype; /* the default hash opclass' opcintype */
+ Oid eq_opr; /* the equality operator */
+ Oid lt_opr; /* the less-than operator */
+ Oid gt_opr; /* the greater-than operator */
+ Oid cmp_proc; /* the btree comparison function */
+ Oid hash_proc; /* the hash calculation function */
+ Oid hash_extended_proc; /* the extended hash calculation function */
+
+ /*
+ * Pre-set-up fmgr call info for the equality operator, the btree
+ * comparison function, and the hash calculation function. These are kept
+ * in the type cache to avoid problems with memory leaks in repeated calls
+ * to functions such as array_eq, array_cmp, hash_array. There is not
+ * currently a need to maintain call info for the lt_opr or gt_opr.
+ */
+ FmgrInfo eq_opr_finfo;
+ FmgrInfo cmp_proc_finfo;
+ FmgrInfo hash_proc_finfo;
+ FmgrInfo hash_extended_proc_finfo;
+
+ /*
+ * Tuple descriptor if it's a composite type (row type). NULL if not
+ * composite or information hasn't yet been requested. (NOTE: this is a
+ * reference-counted tupledesc.)
+ *
+ * To simplify caching dependent info, tupDesc_identifier is an identifier
+ * for this tupledesc that is unique for the life of the process, and
+ * changes anytime the tupledesc does. Zero if not yet determined.
+ */
+ TupleDesc tupDesc;
+ uint64 tupDesc_identifier;
+
+ /*
+ * Fields computed when TYPECACHE_RANGE_INFO is requested. Zeroes if not
+ * a range type or information hasn't yet been requested. Note that
+ * rng_cmp_proc_finfo could be different from the element type's default
+ * btree comparison function.
+ */
+ struct TypeCacheEntry *rngelemtype; /* range's element type */
+ Oid rng_collation; /* collation for comparisons, if any */
+ FmgrInfo rng_cmp_proc_finfo; /* comparison function */
+ FmgrInfo rng_canonical_finfo; /* canonicalization function, if any */
+ FmgrInfo rng_subdiff_finfo; /* difference function, if any */
+
+ /*
+ * Fields computed when TYPECACHE_MULTIRANGE_INFO is required.
+ */
+ struct TypeCacheEntry *rngtype; /* multirange's range underlying type */
+
+ /*
+ * Domain's base type and typmod if it's a domain type. Zeroes if not
+ * domain, or if information hasn't been requested.
+ */
+ Oid domainBaseType;
+ int32 domainBaseTypmod;
+
+ /*
+ * Domain constraint data if it's a domain type. NULL if not domain, or
+ * if domain has no constraints, or if information hasn't been requested.
+ */
+ DomainConstraintCache *domainData;
+
+ /* Private data, for internal use of typcache.c only */
+ int flags; /* flags about what we've computed */
+
+ /*
+ * Private information about an enum type. NULL if not enum or
+ * information hasn't been requested.
+ */
+ struct TypeCacheEnumData *enumData;
+
+ /* We also maintain a list of all known domain-type cache entries */
+ struct TypeCacheEntry *nextDomain;
+} TypeCacheEntry;
+
+/* Bit flags to indicate which fields a given caller needs to have set */
+#define TYPECACHE_EQ_OPR 0x00001
+#define TYPECACHE_LT_OPR 0x00002
+#define TYPECACHE_GT_OPR 0x00004
+#define TYPECACHE_CMP_PROC 0x00008
+#define TYPECACHE_HASH_PROC 0x00010
+#define TYPECACHE_EQ_OPR_FINFO 0x00020
+#define TYPECACHE_CMP_PROC_FINFO 0x00040
+#define TYPECACHE_HASH_PROC_FINFO 0x00080
+#define TYPECACHE_TUPDESC 0x00100
+#define TYPECACHE_BTREE_OPFAMILY 0x00200
+#define TYPECACHE_HASH_OPFAMILY 0x00400
+#define TYPECACHE_RANGE_INFO 0x00800
+#define TYPECACHE_DOMAIN_BASE_INFO 0x01000
+#define TYPECACHE_DOMAIN_CONSTR_INFO 0x02000
+#define TYPECACHE_HASH_EXTENDED_PROC 0x04000
+#define TYPECACHE_HASH_EXTENDED_PROC_FINFO 0x08000
+#define TYPECACHE_MULTIRANGE_INFO 0x10000
+
+/* This value will not equal any valid tupledesc identifier, nor 0 */
+#define INVALID_TUPLEDESC_IDENTIFIER ((uint64) 1)
+
+/*
+ * Callers wishing to maintain a long-lived reference to a domain's constraint
+ * set must store it in one of these. Use InitDomainConstraintRef() and
+ * UpdateDomainConstraintRef() to manage it. Note: DomainConstraintState is
+ * considered an executable expression type, so it's defined in execnodes.h.
+ */
+typedef struct DomainConstraintRef
+{
+ List *constraints; /* list of DomainConstraintState nodes */
+ MemoryContext refctx; /* context holding DomainConstraintRef */
+ TypeCacheEntry *tcache; /* typcache entry for domain type */
+ bool need_exprstate; /* does caller need check_exprstate? */
+
+ /* Management data --- treat these fields as private to typcache.c */
+ DomainConstraintCache *dcc; /* current constraints, or NULL if none */
+ MemoryContextCallback callback; /* used to release refcount when done */
+} DomainConstraintRef;
+
+typedef struct SharedRecordTypmodRegistry SharedRecordTypmodRegistry;
+
+extern TypeCacheEntry *lookup_type_cache(Oid type_id, int flags);
+
+extern void InitDomainConstraintRef(Oid type_id, DomainConstraintRef *ref,
+ MemoryContext refctx, bool need_exprstate);
+
+extern void UpdateDomainConstraintRef(DomainConstraintRef *ref);
+
+extern bool DomainHasConstraints(Oid type_id);
+
+extern TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod);
+
+extern TupleDesc lookup_rowtype_tupdesc_noerror(Oid type_id, int32 typmod,
+ bool noError);
+
+extern TupleDesc lookup_rowtype_tupdesc_copy(Oid type_id, int32 typmod);
+
+extern TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod,
+ bool noError);
+
+extern void assign_record_type_typmod(TupleDesc tupDesc);
+
+extern uint64 assign_record_type_identifier(Oid type_id, int32 typmod);
+
+extern int compare_values_of_enum(TypeCacheEntry *tcache, Oid arg1, Oid arg2);
+
+extern size_t SharedRecordTypmodRegistryEstimate(void);
+
+extern void SharedRecordTypmodRegistryInit(SharedRecordTypmodRegistry *,
+ dsm_segment *segment, dsa_area *area);
+
+extern void SharedRecordTypmodRegistryAttach(SharedRecordTypmodRegistry *);
+
+#endif /* TYPCACHE_H */
diff --git a/pgsql/include/server/utils/tzparser.h b/pgsql/include/server/utils/tzparser.h
new file mode 100644
index 0000000000000000000000000000000000000000..760785b2bf2d8a67b4e072d690f80885de3f91f8
--- /dev/null
+++ b/pgsql/include/server/utils/tzparser.h
@@ -0,0 +1,39 @@
+/*-------------------------------------------------------------------------
+ *
+ * tzparser.h
+ * Timezone offset file parsing definitions.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/tzparser.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef TZPARSER_H
+#define TZPARSER_H
+
+#include "utils/datetime.h"
+
+/*
+ * The result of parsing a timezone configuration file is an array of
+ * these structs, in order by abbrev. We export this because datetime.c
+ * needs it.
+ */
+typedef struct tzEntry
+{
+ /* the actual data */
+ char *abbrev; /* TZ abbreviation (downcased) */
+ char *zone; /* zone name if dynamic abbrev, else NULL */
+ /* for a dynamic abbreviation, offset/is_dst are not used */
+ int offset; /* offset in seconds from UTC */
+ bool is_dst; /* true if a DST abbreviation */
+ /* source information (for error messages) */
+ int lineno;
+ const char *filename;
+} tzEntry;
+
+
+extern TimeZoneAbbrevTable *load_tzoffsets(const char *filename);
+
+#endif /* TZPARSER_H */
diff --git a/pgsql/include/server/utils/usercontext.h b/pgsql/include/server/utils/usercontext.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8195c194de6bfac706b0850560e7e86ae424805
--- /dev/null
+++ b/pgsql/include/server/utils/usercontext.h
@@ -0,0 +1,26 @@
+/*-------------------------------------------------------------------------
+ *
+ * usercontext.h
+ * Convenience functions for running code as a different database user.
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef USERCONTEXT_H
+#define USERCONTEXT_H
+
+/*
+ * When temporarily changing to run as a different user, this structure
+ * holds the details needed to restore the original state.
+ */
+typedef struct UserContext
+{
+ Oid save_userid;
+ int save_sec_context;
+ int save_nestlevel;
+} UserContext;
+
+/* Function prototypes. */
+extern void SwitchToUntrustedUser(Oid userid, UserContext *context);
+extern void RestoreUserContext(UserContext *context);
+
+#endif /* USERCONTEXT_H */
diff --git a/pgsql/include/server/utils/uuid.h b/pgsql/include/server/utils/uuid.h
new file mode 100644
index 0000000000000000000000000000000000000000..11177171b2c18309609a3d675b46d0b5d60edf10
--- /dev/null
+++ b/pgsql/include/server/utils/uuid.h
@@ -0,0 +1,42 @@
+/*-------------------------------------------------------------------------
+ *
+ * uuid.h
+ * Header file for the "uuid" ADT. In C, we use the name pg_uuid_t,
+ * to avoid conflicts with any uuid_t type that might be defined by
+ * the system headers.
+ *
+ * Copyright (c) 2007-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/uuid.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef UUID_H
+#define UUID_H
+
+/* uuid size in bytes */
+#define UUID_LEN 16
+
+typedef struct pg_uuid_t
+{
+ unsigned char data[UUID_LEN];
+} pg_uuid_t;
+
+/* fmgr interface macros */
+static inline Datum
+UUIDPGetDatum(const pg_uuid_t *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_RETURN_UUID_P(X) return UUIDPGetDatum(X)
+
+static inline pg_uuid_t *
+DatumGetUUIDP(Datum X)
+{
+ return (pg_uuid_t *) DatumGetPointer(X);
+}
+
+#define PG_GETARG_UUID_P(X) DatumGetUUIDP(PG_GETARG_DATUM(X))
+
+#endif /* UUID_H */
diff --git a/pgsql/include/server/utils/varbit.h b/pgsql/include/server/utils/varbit.h
new file mode 100644
index 0000000000000000000000000000000000000000..3bb7945ed99fb6893102df21e70661f79aed6757
--- /dev/null
+++ b/pgsql/include/server/utils/varbit.h
@@ -0,0 +1,89 @@
+/*-------------------------------------------------------------------------
+ *
+ * varbit.h
+ * Functions for the SQL datatypes BIT() and BIT VARYING().
+ *
+ * Code originally contributed by Adriaan Joubert.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/varbit.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef VARBIT_H
+#define VARBIT_H
+
+#include
+
+#include "fmgr.h"
+
+/*
+ * Modeled on struct varlena from postgres.h, but data type is bits8.
+ *
+ * Caution: if bit_len is not a multiple of BITS_PER_BYTE, the low-order
+ * bits of the last byte of bit_dat[] are unused and MUST be zeroes.
+ * (This allows bit_cmp() to not bother masking the last byte.)
+ * Also, there should not be any excess bytes counted in the header length.
+ */
+typedef struct
+{
+ int32 vl_len_; /* varlena header (do not touch directly!) */
+ int32 bit_len; /* number of valid bits */
+ bits8 bit_dat[FLEXIBLE_ARRAY_MEMBER]; /* bit string, most sig. byte
+ * first */
+} VarBit;
+
+/*
+ * fmgr interface macros
+ *
+ * BIT and BIT VARYING are toastable varlena types. They are the same
+ * as far as representation goes, so we just have one set of macros.
+ */
+static inline VarBit *
+DatumGetVarBitP(Datum X)
+{
+ return (VarBit *) PG_DETOAST_DATUM(X);
+}
+
+static inline VarBit *
+DatumGetVarBitPCopy(Datum X)
+{
+ return (VarBit *) PG_DETOAST_DATUM_COPY(X);
+}
+
+static inline Datum
+VarBitPGetDatum(const VarBit *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_VARBIT_P(n) DatumGetVarBitP(PG_GETARG_DATUM(n))
+#define PG_GETARG_VARBIT_P_COPY(n) DatumGetVarBitPCopy(PG_GETARG_DATUM(n))
+#define PG_RETURN_VARBIT_P(x) return VarBitPGetDatum(x)
+
+/* Header overhead *in addition to* VARHDRSZ */
+#define VARBITHDRSZ sizeof(int32)
+/* Number of bits in this bit string */
+#define VARBITLEN(PTR) (((VarBit *) (PTR))->bit_len)
+/* Pointer to the first byte containing bit string data */
+#define VARBITS(PTR) (((VarBit *) (PTR))->bit_dat)
+/* Number of bytes in the data section of a bit string */
+#define VARBITBYTES(PTR) (VARSIZE(PTR) - VARHDRSZ - VARBITHDRSZ)
+/* Padding of the bit string at the end (in bits) */
+#define VARBITPAD(PTR) (VARBITBYTES(PTR)*BITS_PER_BYTE - VARBITLEN(PTR))
+/* Number of bytes needed to store a bit string of a given length */
+#define VARBITTOTALLEN(BITLEN) (((BITLEN) + BITS_PER_BYTE-1)/BITS_PER_BYTE + \
+ VARHDRSZ + VARBITHDRSZ)
+/*
+ * Maximum number of bits. Several code sites assume no overflow from
+ * computing bitlen + X; VARBITTOTALLEN() has the largest such X.
+ */
+#define VARBITMAXLEN (INT_MAX - BITS_PER_BYTE + 1)
+/* pointer beyond the end of the bit string (like end() in STL containers) */
+#define VARBITEND(PTR) (((bits8 *) (PTR)) + VARSIZE(PTR))
+/* Mask that will cover exactly one byte, i.e. BITS_PER_BYTE bits */
+#define BITMASK 0xFF
+
+#endif
diff --git a/pgsql/include/server/utils/varlena.h b/pgsql/include/server/utils/varlena.h
new file mode 100644
index 0000000000000000000000000000000000000000..77f5b247351d658e77bef60fc38d56c9d378ab8f
--- /dev/null
+++ b/pgsql/include/server/utils/varlena.h
@@ -0,0 +1,53 @@
+/*-------------------------------------------------------------------------
+ *
+ * varlena.h
+ * Functions for the variable-length built-in types.
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/varlena.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef VARLENA_H
+#define VARLENA_H
+
+#include "nodes/pg_list.h"
+#include "utils/sortsupport.h"
+
+extern int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid);
+extern void varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid);
+extern int varstr_levenshtein(const char *source, int slen,
+ const char *target, int tlen,
+ int ins_c, int del_c, int sub_c,
+ bool trusted);
+extern int varstr_levenshtein_less_equal(const char *source, int slen,
+ const char *target, int tlen,
+ int ins_c, int del_c, int sub_c,
+ int max_d, bool trusted);
+extern List *textToQualifiedNameList(text *textval);
+extern bool SplitIdentifierString(char *rawstring, char separator,
+ List **namelist);
+extern bool SplitDirectoriesString(char *rawstring, char separator,
+ List **namelist);
+extern bool SplitGUCList(char *rawstring, char separator,
+ List **namelist);
+extern text *replace_text_regexp(text *src_text, text *pattern_text,
+ text *replace_text,
+ int cflags, Oid collation,
+ int search_start, int n);
+
+typedef struct ClosestMatchState
+{
+ const char *source;
+ int min_d;
+ int max_d;
+ const char *match;
+} ClosestMatchState;
+
+extern void initClosestMatch(ClosestMatchState *state, const char *source, int max_d);
+extern void updateClosestMatch(ClosestMatchState *state, const char *candidate);
+extern const char *getClosestMatch(ClosestMatchState *state);
+
+#endif
diff --git a/pgsql/include/server/utils/wait_event.h b/pgsql/include/server/utils/wait_event.h
new file mode 100644
index 0000000000000000000000000000000000000000..2adc5df2e79b0c299aa86b2c93241135b38c5189
--- /dev/null
+++ b/pgsql/include/server/utils/wait_event.h
@@ -0,0 +1,295 @@
+/*-------------------------------------------------------------------------
+ * wait_event.h
+ * Definitions related to wait event reporting
+ *
+ * Copyright (c) 2001-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/wait_event.h
+ * ----------
+ */
+#ifndef WAIT_EVENT_H
+#define WAIT_EVENT_H
+
+
+/* ----------
+ * Wait Classes
+ * ----------
+ */
+#define PG_WAIT_LWLOCK 0x01000000U
+#define PG_WAIT_LOCK 0x03000000U
+#define PG_WAIT_BUFFER_PIN 0x04000000U
+#define PG_WAIT_ACTIVITY 0x05000000U
+#define PG_WAIT_CLIENT 0x06000000U
+#define PG_WAIT_EXTENSION 0x07000000U
+#define PG_WAIT_IPC 0x08000000U
+#define PG_WAIT_TIMEOUT 0x09000000U
+#define PG_WAIT_IO 0x0A000000U
+
+/* ----------
+ * Wait Events - Activity
+ *
+ * Use this category when a process is waiting because it has no work to do,
+ * unless the "Client" or "Timeout" category describes the situation better.
+ * Typically, this should only be used for background processes.
+ * ----------
+ */
+typedef enum
+{
+ WAIT_EVENT_ARCHIVER_MAIN = PG_WAIT_ACTIVITY,
+ WAIT_EVENT_AUTOVACUUM_MAIN,
+ WAIT_EVENT_BGWRITER_HIBERNATE,
+ WAIT_EVENT_BGWRITER_MAIN,
+ WAIT_EVENT_CHECKPOINTER_MAIN,
+ WAIT_EVENT_LOGICAL_APPLY_MAIN,
+ WAIT_EVENT_LOGICAL_LAUNCHER_MAIN,
+ WAIT_EVENT_LOGICAL_PARALLEL_APPLY_MAIN,
+ WAIT_EVENT_RECOVERY_WAL_STREAM,
+ WAIT_EVENT_SYSLOGGER_MAIN,
+ WAIT_EVENT_WAL_RECEIVER_MAIN,
+ WAIT_EVENT_WAL_SENDER_MAIN,
+ WAIT_EVENT_WAL_WRITER_MAIN
+} WaitEventActivity;
+
+/* ----------
+ * Wait Events - Client
+ *
+ * Use this category when a process is waiting to send data to or receive data
+ * from the frontend process to which it is connected. This is never used for
+ * a background process, which has no client connection.
+ * ----------
+ */
+typedef enum
+{
+ WAIT_EVENT_CLIENT_READ = PG_WAIT_CLIENT,
+ WAIT_EVENT_CLIENT_WRITE,
+ WAIT_EVENT_GSS_OPEN_SERVER,
+ WAIT_EVENT_LIBPQWALRECEIVER_CONNECT,
+ WAIT_EVENT_LIBPQWALRECEIVER_RECEIVE,
+ WAIT_EVENT_SSL_OPEN_SERVER,
+ WAIT_EVENT_WAL_SENDER_WAIT_WAL,
+ WAIT_EVENT_WAL_SENDER_WRITE_DATA,
+} WaitEventClient;
+
+/* ----------
+ * Wait Events - IPC
+ *
+ * Use this category when a process cannot complete the work it is doing because
+ * it is waiting for a notification from another process.
+ * ----------
+ */
+typedef enum
+{
+ WAIT_EVENT_APPEND_READY = PG_WAIT_IPC,
+ WAIT_EVENT_ARCHIVE_CLEANUP_COMMAND,
+ WAIT_EVENT_ARCHIVE_COMMAND,
+ WAIT_EVENT_BACKEND_TERMINATION,
+ WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE,
+ WAIT_EVENT_BGWORKER_SHUTDOWN,
+ WAIT_EVENT_BGWORKER_STARTUP,
+ WAIT_EVENT_BTREE_PAGE,
+ WAIT_EVENT_BUFFER_IO,
+ WAIT_EVENT_CHECKPOINT_DONE,
+ WAIT_EVENT_CHECKPOINT_START,
+ WAIT_EVENT_EXECUTE_GATHER,
+ WAIT_EVENT_HASH_BATCH_ALLOCATE,
+ WAIT_EVENT_HASH_BATCH_ELECT,
+ WAIT_EVENT_HASH_BATCH_LOAD,
+ WAIT_EVENT_HASH_BUILD_ALLOCATE,
+ WAIT_EVENT_HASH_BUILD_ELECT,
+ WAIT_EVENT_HASH_BUILD_HASH_INNER,
+ WAIT_EVENT_HASH_BUILD_HASH_OUTER,
+ WAIT_EVENT_HASH_GROW_BATCHES_DECIDE,
+ WAIT_EVENT_HASH_GROW_BATCHES_ELECT,
+ WAIT_EVENT_HASH_GROW_BATCHES_FINISH,
+ WAIT_EVENT_HASH_GROW_BATCHES_REALLOCATE,
+ WAIT_EVENT_HASH_GROW_BATCHES_REPARTITION,
+ WAIT_EVENT_HASH_GROW_BUCKETS_ELECT,
+ WAIT_EVENT_HASH_GROW_BUCKETS_REALLOCATE,
+ WAIT_EVENT_HASH_GROW_BUCKETS_REINSERT,
+ WAIT_EVENT_LOGICAL_APPLY_SEND_DATA,
+ WAIT_EVENT_LOGICAL_PARALLEL_APPLY_STATE_CHANGE,
+ WAIT_EVENT_LOGICAL_SYNC_DATA,
+ WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE,
+ WAIT_EVENT_MQ_INTERNAL,
+ WAIT_EVENT_MQ_PUT_MESSAGE,
+ WAIT_EVENT_MQ_RECEIVE,
+ WAIT_EVENT_MQ_SEND,
+ WAIT_EVENT_PARALLEL_BITMAP_SCAN,
+ WAIT_EVENT_PARALLEL_CREATE_INDEX_SCAN,
+ WAIT_EVENT_PARALLEL_FINISH,
+ WAIT_EVENT_PROCARRAY_GROUP_UPDATE,
+ WAIT_EVENT_PROC_SIGNAL_BARRIER,
+ WAIT_EVENT_PROMOTE,
+ WAIT_EVENT_RECOVERY_CONFLICT_SNAPSHOT,
+ WAIT_EVENT_RECOVERY_CONFLICT_TABLESPACE,
+ WAIT_EVENT_RECOVERY_END_COMMAND,
+ WAIT_EVENT_RECOVERY_PAUSE,
+ WAIT_EVENT_REPLICATION_ORIGIN_DROP,
+ WAIT_EVENT_REPLICATION_SLOT_DROP,
+ WAIT_EVENT_RESTORE_COMMAND,
+ WAIT_EVENT_SAFE_SNAPSHOT,
+ WAIT_EVENT_SYNC_REP,
+ WAIT_EVENT_WAL_RECEIVER_EXIT,
+ WAIT_EVENT_WAL_RECEIVER_WAIT_START,
+ WAIT_EVENT_XACT_GROUP_UPDATE
+} WaitEventIPC;
+
+/* ----------
+ * Wait Events - Timeout
+ *
+ * Use this category when a process is waiting for a timeout to expire.
+ * ----------
+ */
+typedef enum
+{
+ WAIT_EVENT_BASE_BACKUP_THROTTLE = PG_WAIT_TIMEOUT,
+ WAIT_EVENT_CHECKPOINT_WRITE_DELAY,
+ WAIT_EVENT_PG_SLEEP,
+ WAIT_EVENT_RECOVERY_APPLY_DELAY,
+ WAIT_EVENT_RECOVERY_RETRIEVE_RETRY_INTERVAL,
+ WAIT_EVENT_REGISTER_SYNC_REQUEST,
+ WAIT_EVENT_SPIN_DELAY,
+ WAIT_EVENT_VACUUM_DELAY,
+ WAIT_EVENT_VACUUM_TRUNCATE
+} WaitEventTimeout;
+
+/* ----------
+ * Wait Events - IO
+ *
+ * Use this category when a process is waiting for a IO.
+ * ----------
+ */
+typedef enum
+{
+ WAIT_EVENT_BASEBACKUP_READ = PG_WAIT_IO,
+ WAIT_EVENT_BASEBACKUP_SYNC,
+ WAIT_EVENT_BASEBACKUP_WRITE,
+ WAIT_EVENT_BUFFILE_READ,
+ WAIT_EVENT_BUFFILE_WRITE,
+ WAIT_EVENT_BUFFILE_TRUNCATE,
+ WAIT_EVENT_CONTROL_FILE_READ,
+ WAIT_EVENT_CONTROL_FILE_SYNC,
+ WAIT_EVENT_CONTROL_FILE_SYNC_UPDATE,
+ WAIT_EVENT_CONTROL_FILE_WRITE,
+ WAIT_EVENT_CONTROL_FILE_WRITE_UPDATE,
+ WAIT_EVENT_COPY_FILE_READ,
+ WAIT_EVENT_COPY_FILE_WRITE,
+ WAIT_EVENT_DATA_FILE_EXTEND,
+ WAIT_EVENT_DATA_FILE_FLUSH,
+ WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC,
+ WAIT_EVENT_DATA_FILE_PREFETCH,
+ WAIT_EVENT_DATA_FILE_READ,
+ WAIT_EVENT_DATA_FILE_SYNC,
+ WAIT_EVENT_DATA_FILE_TRUNCATE,
+ WAIT_EVENT_DATA_FILE_WRITE,
+ WAIT_EVENT_DSM_ALLOCATE,
+ WAIT_EVENT_DSM_FILL_ZERO_WRITE,
+ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ,
+ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC,
+ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE,
+ WAIT_EVENT_LOCK_FILE_CREATE_READ,
+ WAIT_EVENT_LOCK_FILE_CREATE_SYNC,
+ WAIT_EVENT_LOCK_FILE_CREATE_WRITE,
+ WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ,
+ WAIT_EVENT_LOGICAL_REWRITE_CHECKPOINT_SYNC,
+ WAIT_EVENT_LOGICAL_REWRITE_MAPPING_SYNC,
+ WAIT_EVENT_LOGICAL_REWRITE_MAPPING_WRITE,
+ WAIT_EVENT_LOGICAL_REWRITE_SYNC,
+ WAIT_EVENT_LOGICAL_REWRITE_TRUNCATE,
+ WAIT_EVENT_LOGICAL_REWRITE_WRITE,
+ WAIT_EVENT_RELATION_MAP_READ,
+ WAIT_EVENT_RELATION_MAP_REPLACE,
+ WAIT_EVENT_RELATION_MAP_WRITE,
+ WAIT_EVENT_REORDER_BUFFER_READ,
+ WAIT_EVENT_REORDER_BUFFER_WRITE,
+ WAIT_EVENT_REORDER_LOGICAL_MAPPING_READ,
+ WAIT_EVENT_REPLICATION_SLOT_READ,
+ WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC,
+ WAIT_EVENT_REPLICATION_SLOT_SYNC,
+ WAIT_EVENT_REPLICATION_SLOT_WRITE,
+ WAIT_EVENT_SLRU_FLUSH_SYNC,
+ WAIT_EVENT_SLRU_READ,
+ WAIT_EVENT_SLRU_SYNC,
+ WAIT_EVENT_SLRU_WRITE,
+ WAIT_EVENT_SNAPBUILD_READ,
+ WAIT_EVENT_SNAPBUILD_SYNC,
+ WAIT_EVENT_SNAPBUILD_WRITE,
+ WAIT_EVENT_TIMELINE_HISTORY_FILE_SYNC,
+ WAIT_EVENT_TIMELINE_HISTORY_FILE_WRITE,
+ WAIT_EVENT_TIMELINE_HISTORY_READ,
+ WAIT_EVENT_TIMELINE_HISTORY_SYNC,
+ WAIT_EVENT_TIMELINE_HISTORY_WRITE,
+ WAIT_EVENT_TWOPHASE_FILE_READ,
+ WAIT_EVENT_TWOPHASE_FILE_SYNC,
+ WAIT_EVENT_TWOPHASE_FILE_WRITE,
+ WAIT_EVENT_VERSION_FILE_WRITE,
+ WAIT_EVENT_WALSENDER_TIMELINE_HISTORY_READ,
+ WAIT_EVENT_WAL_BOOTSTRAP_SYNC,
+ WAIT_EVENT_WAL_BOOTSTRAP_WRITE,
+ WAIT_EVENT_WAL_COPY_READ,
+ WAIT_EVENT_WAL_COPY_SYNC,
+ WAIT_EVENT_WAL_COPY_WRITE,
+ WAIT_EVENT_WAL_INIT_SYNC,
+ WAIT_EVENT_WAL_INIT_WRITE,
+ WAIT_EVENT_WAL_READ,
+ WAIT_EVENT_WAL_SYNC,
+ WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN,
+ WAIT_EVENT_WAL_WRITE,
+ WAIT_EVENT_VERSION_FILE_SYNC
+} WaitEventIO;
+
+
+extern const char *pgstat_get_wait_event(uint32 wait_event_info);
+extern const char *pgstat_get_wait_event_type(uint32 wait_event_info);
+static inline void pgstat_report_wait_start(uint32 wait_event_info);
+static inline void pgstat_report_wait_end(void);
+extern void pgstat_set_wait_event_storage(uint32 *wait_event_info);
+extern void pgstat_reset_wait_event_storage(void);
+
+extern PGDLLIMPORT uint32 *my_wait_event_info;
+
+
+/* ----------
+ * pgstat_report_wait_start() -
+ *
+ * Called from places where server process needs to wait. This is called
+ * to report wait event information. The wait information is stored
+ * as 4-bytes where first byte represents the wait event class (type of
+ * wait, for different types of wait, refer WaitClass) and the next
+ * 3-bytes represent the actual wait event. Currently 2-bytes are used
+ * for wait event which is sufficient for current usage, 1-byte is
+ * reserved for future usage.
+ *
+ * Historically we used to make this reporting conditional on
+ * pgstat_track_activities, but the check for that seems to add more cost
+ * than it saves.
+ *
+ * my_wait_event_info initially points to local memory, making it safe to
+ * call this before MyProc has been initialized.
+ * ----------
+ */
+static inline void
+pgstat_report_wait_start(uint32 wait_event_info)
+{
+ /*
+ * Since this is a four-byte field which is always read and written as
+ * four-bytes, updates are atomic.
+ */
+ *(volatile uint32 *) my_wait_event_info = wait_event_info;
+}
+
+/* ----------
+ * pgstat_report_wait_end() -
+ *
+ * Called to report end of a wait.
+ * ----------
+ */
+static inline void
+pgstat_report_wait_end(void)
+{
+ /* see pgstat_report_wait_start() */
+ *(volatile uint32 *) my_wait_event_info = 0;
+}
+
+
+#endif /* WAIT_EVENT_H */
diff --git a/pgsql/include/server/utils/xid8.h b/pgsql/include/server/utils/xid8.h
new file mode 100644
index 0000000000000000000000000000000000000000..2f5e14baad4d6b866f21de63c1b3d3fa662920b8
--- /dev/null
+++ b/pgsql/include/server/utils/xid8.h
@@ -0,0 +1,32 @@
+/*-------------------------------------------------------------------------
+ *
+ * xid8.h
+ * Header file for the "xid8" ADT.
+ *
+ * Copyright (c) 2020-2023, PostgreSQL Global Development Group
+ *
+ * src/include/utils/xid8.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef XID8_H
+#define XID8_H
+
+#include "access/transam.h"
+
+static inline FullTransactionId
+DatumGetFullTransactionId(Datum X)
+{
+ return FullTransactionIdFromU64(DatumGetUInt64(X));
+}
+
+static inline Datum
+FullTransactionIdGetDatum(FullTransactionId X)
+{
+ return UInt64GetDatum(U64FromFullTransactionId(X));
+}
+
+#define PG_GETARG_FULLTRANSACTIONID(X) DatumGetFullTransactionId(PG_GETARG_DATUM(X))
+#define PG_RETURN_FULLTRANSACTIONID(X) return FullTransactionIdGetDatum(X)
+
+#endif /* XID8_H */
diff --git a/pgsql/include/server/utils/xml.h b/pgsql/include/server/utils/xml.h
new file mode 100644
index 0000000000000000000000000000000000000000..224f6d75ffde32f96286dc4e3f99bbfaa2bd7f3b
--- /dev/null
+++ b/pgsql/include/server/utils/xml.h
@@ -0,0 +1,94 @@
+/*-------------------------------------------------------------------------
+ *
+ * xml.h
+ * Declarations for XML data type support.
+ *
+ *
+ * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/utils/xml.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef XML_H
+#define XML_H
+
+#include "executor/tablefunc.h"
+#include "fmgr.h"
+#include "nodes/execnodes.h"
+#include "nodes/primnodes.h"
+
+typedef struct varlena xmltype;
+
+typedef enum
+{
+ XML_STANDALONE_YES,
+ XML_STANDALONE_NO,
+ XML_STANDALONE_NO_VALUE,
+ XML_STANDALONE_OMITTED
+} XmlStandaloneType;
+
+typedef enum
+{
+ XMLBINARY_BASE64,
+ XMLBINARY_HEX
+} XmlBinaryType;
+
+typedef enum
+{
+ PG_XML_STRICTNESS_LEGACY, /* ignore errors unless function result
+ * indicates error condition */
+ PG_XML_STRICTNESS_WELLFORMED, /* ignore non-parser messages */
+ PG_XML_STRICTNESS_ALL /* report all notices/warnings/errors */
+} PgXmlStrictness;
+
+/* struct PgXmlErrorContext is private to xml.c */
+typedef struct PgXmlErrorContext PgXmlErrorContext;
+
+static inline xmltype *
+DatumGetXmlP(Datum X)
+{
+ return (xmltype *) PG_DETOAST_DATUM(X);
+}
+
+static inline Datum
+XmlPGetDatum(const xmltype *X)
+{
+ return PointerGetDatum(X);
+}
+
+#define PG_GETARG_XML_P(n) DatumGetXmlP(PG_GETARG_DATUM(n))
+#define PG_RETURN_XML_P(x) PG_RETURN_POINTER(x)
+
+extern void pg_xml_init_library(void);
+extern PgXmlErrorContext *pg_xml_init(PgXmlStrictness strictness);
+extern void pg_xml_done(PgXmlErrorContext *errcxt, bool isError);
+extern bool pg_xml_error_occurred(PgXmlErrorContext *errcxt);
+extern void xml_ereport(PgXmlErrorContext *errcxt, int level, int sqlcode,
+ const char *msg);
+
+extern xmltype *xmlconcat(List *args);
+extern xmltype *xmlelement(XmlExpr *xexpr,
+ Datum *named_argvalue, bool *named_argnull,
+ Datum *argvalue, bool *argnull);
+extern xmltype *xmlparse(text *data, XmlOptionType xmloption_arg, bool preserve_whitespace);
+extern xmltype *xmlpi(const char *target, text *arg, bool arg_is_null, bool *result_is_null);
+extern xmltype *xmlroot(xmltype *data, text *version, int standalone);
+extern bool xml_is_document(xmltype *arg);
+extern text *xmltotext_with_options(xmltype *data, XmlOptionType xmloption_arg,
+ bool indent);
+extern char *escape_xml(const char *str);
+
+extern char *map_sql_identifier_to_xml_name(const char *ident, bool fully_escaped, bool escape_period);
+extern char *map_xml_name_to_sql_identifier(const char *name);
+extern char *map_sql_value_to_xml_value(Datum value, Oid type, bool xml_escape_strings);
+
+extern PGDLLIMPORT int xmlbinary; /* XmlBinaryType, but int for guc enum */
+
+extern PGDLLIMPORT int xmloption; /* XmlOptionType, but int for guc enum */
+
+extern PGDLLIMPORT const TableFuncRoutine XmlTableRoutine;
+
+#endif /* XML_H */