postgresql
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePostgresql Skill
PostgreSQL 技能文档
Comprehensive assistance with postgresql development, generated from official documentation.
本文档基于官方资料生成,为PostgreSQL开发提供全面指导。
When to Use This Skill
何时使用本技能
This skill should be triggered when:
- Working with postgresql
- Asking about postgresql features or APIs
- Implementing postgresql solutions
- Debugging postgresql code
- Learning postgresql best practices
在以下场景中应使用本技能:
- 处理PostgreSQL相关工作
- 咨询PostgreSQL功能或API
- 实现PostgreSQL解决方案
- 调试PostgreSQL相关代码
- 学习PostgreSQL最佳实践
Quick Reference
快速参考
Common Patterns
常见模式
Pattern 1: 32.1. Database Connection Control Functions # 32.1.1. Connection Strings 32.1.2. Parameter Key Words The following functions deal with making a connection to a PostgreSQL backend server. An application program can have several backend connections open at one time. (One reason to do that is to access more than one database.) Each connection is represented by a PGconn object, which is obtained from the function PQconnectdb, PQconnectdbParams, or PQsetdbLogin. Note that these functions will always return a non-null object pointer, unless perhaps there is too little memory even to allocate the PGconn object. The PQstatus function should be called to check the return value for a successful connection before queries are sent via the connection object. Warning 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 can set parameter key word options to value -csearch_path=. Alternately, one can issue PQexec(conn, "SELECT pg_catalog.set_config('search_path', '', false)") after connecting. This consideration is not specific to libpq; it applies to every interface for executing arbitrary SQL commands. Warning On Unix, forking a process with open libpq connections can lead to unpredictable results because the parent and child processes share the same sockets and operating system resources. For this reason, such usage is not recommended, though doing an exec from the child process to load a new executable is safe. PQconnectdbParams # Makes a new connection to the database server. PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname); This function opens a new database connection using the parameters taken from two NULL-terminated arrays. The first, keywords, is defined as an array of strings, each one being a key word. The second, values, gives the value for each key word. Unlike PQsetdbLogin below, the parameter set can be extended without changing the function signature, so use of this function (or its nonblocking analogs PQconnectStartParams and PQconnectPoll) is preferred for new application programming. The currently recognized parameter key words are listed in Section 32.1.2. The passed arrays can be empty to use all default parameters, or can contain one or more parameter settings. They must be matched in length. Processing will stop at the first NULL entry in the keywords array. Also, if the values entry associated with a non-NULL keywords entry is NULL or an empty string, that entry is ignored and processing continues with the next pair of array entries. When expand_dbname is non-zero, the value for the first dbname key word is checked to see if it is a connection string. If so, it is “expanded” into the individual connection parameters extracted from the string. The value is considered to be a connection string, rather than just a database name, if it contains an equal sign (=) or it begins with a URI scheme designator. (More details on connection string formats appear in Section 32.1.1.) Only the first occurrence of dbname is treated in this way; any subsequent dbname parameter is processed as a plain database name. In general the parameter arrays are processed from start to end. If any key word is repeated, the last value (that is not NULL or empty) is used. This rule applies in particular when a key word found in a connection string conflicts with one appearing in the keywords array. Thus, the programmer may determine whether array entries can override or be overridden by values taken from a connection string. Array entries appearing before an expanded dbname entry can be overridden by fields of the connection string, and in turn those fields are overridden by array entries appearing after dbname (but, again, only if those entries supply non-empty values). After processing all the array entries and any expanded connection string, any connection parameters that remain unset are filled with default values. If an unset parameter's corresponding environment variable (see Section 32.15) is set, its value is used. If the environment variable is not set either, then the parameter's built-in default value is used. PQconnectdb # Makes a new connection to the database server. PGconn *PQconnectdb(const char *conninfo); This function opens a new database connection using the parameters taken from the string conninfo. The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace, or it can contain a URI. See Section 32.1.1 for details. PQsetdbLogin # Makes a new connection to the database server. PGconn *PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd); This is the predecessor of PQconnectdb with a fixed set of parameters. It has the same functionality except that the missing parameters will always take on default values. Write NULL or an empty string for any one of the fixed parameters that is to be defaulted. If the dbName contains an = sign or has a valid connection URI prefix, it is taken as a conninfo string in exactly the same way as if it had been passed to PQconnectdb, and the remaining parameters are then applied as specified for PQconnectdbParams. pgtty is no longer used and any value passed will be ignored. PQsetdb # Makes a new connection to the database server. PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName); This is a macro that calls PQsetdbLogin with null pointers for the login and pwd parameters. It is provided for backward compatibility with very old programs. PQconnectStartParamsPQconnectStartPQconnectPoll # Make a connection to the database server in a nonblocking manner. PGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname); PGconn *PQconnectStart(const char *conninfo); PostgresPollingStatusType PQconnectPoll(PGconn *conn); These three functions are used to open a connection to a database server such that your application's thread of execution is not blocked on remote I/O whilst doing so. The point of this approach is that the waits for I/O to complete can occur in the application's main loop, rather than down inside PQconnectdbParams or PQconnectdb, and so the application can manage this operation in parallel with other activities. With PQconnectStartParams, the database connection is made using the parameters taken from the keywords and values arrays, and controlled by expand_dbname, as described above for PQconnectdbParams. With PQconnectStart, the database connection is made using the parameters taken from the string conninfo as described above for PQconnectdb. Neither PQconnectStartParams nor PQconnectStart nor PQconnectPoll will block, so long as a number of restrictions are met: The hostaddr parameter must be used appropriately to prevent DNS queries from being made. See the documentation of this parameter in Section 32.1.2 for details. If you call PQtrace, ensure that the stream object into which you trace will not block. You must ensure that the socket is in the appropriate state before calling PQconnectPoll, as described below. To begin a nonblocking connection request, call PQconnectStart or PQconnectStartParams. If the result is null, then libpq has been unable to allocate a new PGconn structure. Otherwise, a valid PGconn pointer is returned (though not yet representing a valid connection to the database). Next call PQstatus(conn). If the result is CONNECTION_BAD, the connection attempt has already failed, typically because of invalid connection parameters. If PQconnectStart or PQconnectStartParams succeeds, the next stage is to poll libpq so that it can proceed with the connection sequence. Use PQsocket(conn) to obtain the descriptor of the socket underlying the database connection. (Caution: do not assume that the socket remains the same across PQconnectPoll calls.) Loop thus: If PQconnectPoll(conn) last returned PGRES_POLLING_READING, wait until the socket is ready to read (as indicated by select(), poll(), or similar system function). Note that PQsocketPoll can help reduce boilerplate by abstracting the setup of select(2) or poll(2) if it is available on your system. Then call PQconnectPoll(conn) again. Conversely, if PQconnectPoll(conn) last returned PGRES_POLLING_WRITING, wait until the socket is ready to write, then call PQconnectPoll(conn) again. On the first iteration, i.e., if you have yet to call PQconnectPoll, behave as if it last returned PGRES_POLLING_WRITING. Continue this loop until PQconnectPoll(conn) returns PGRES_POLLING_FAILED, indicating the connection procedure has failed, or PGRES_POLLING_OK, indicating the connection has been successfully made. At any time during connection, the status of the connection can be checked by calling PQstatus. If this call returns CONNECTION_BAD, then the connection procedure has failed; if the call returns CONNECTION_OK, then the connection is ready. Both of these states are equally detectable from the return value of PQconnectPoll, described above. Other states might also occur during (and only during) an asynchronous connection procedure. These indicate the current stage of the connection procedure and might be useful to provide feedback to the user for example. These statuses are: CONNECTION_STARTED # Waiting for connection to be made. CONNECTION_MADE # Connection OK; waiting to send. CONNECTION_AWAITING_RESPONSE # Waiting for a response from the server. CONNECTION_AUTH_OK # Received authentication; waiting for backend start-up to finish. CONNECTION_SSL_STARTUP # Negotiating SSL encryption. CONNECTION_GSS_STARTUP # Negotiating GSS encryption. CONNECTION_CHECK_WRITABLE # Checking if connection is able to handle write transactions. CONNECTION_CHECK_STANDBY # Checking if connection is to a server in standby mode. CONNECTION_CONSUME # Consuming any remaining response messages on connection. Note that, although these constants will remain (in order to maintain compatibility), an application should never rely upon these occurring in a particular order, or at all, or on the status always being one of these documented values. An application might do something like this: switch(PQstatus(conn)) { case CONNECTION_STARTED: feedback = "Connecting..."; break; case CONNECTION_MADE: feedback = "Connected to server..."; break; . . . default: feedback = "Connecting..."; } The connect_timeout connection parameter is ignored when using PQconnectPoll; it is the application's responsibility to decide whether an excessive amount of time has elapsed. Otherwise, PQconnectStart followed by a PQconnectPoll loop is equivalent to PQconnectdb. Note that when PQconnectStart or PQconnectStartParams returns a non-null pointer, you must call PQfinish when you are finished with it, in order to dispose of the structure and any associated memory blocks. This must be done even if the connection attempt fails or is abandoned. PQsocketPoll # Poll a connection's underlying socket descriptor retrieved with PQsocket. The primary use of this function is iterating through the connection sequence described in the documentation of PQconnectStartParams. typedef int64_t pg_usec_time_t; int PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time); This function performs polling of a file descriptor, optionally with a timeout. If forRead is nonzero, the function will terminate when the socket is ready for reading. If forWrite is nonzero, the function will terminate when the socket is ready for writing. The timeout is specified by end_time, which is the time to stop waiting expressed as a number of microseconds since the Unix epoch (that is, time_t times 1 million). Timeout is infinite if end_time is -1. Timeout is immediate (no blocking) if end_time is 0 (or indeed, any time before now). Timeout values can be calculated conveniently by adding the desired number of microseconds to the result of PQgetCurrentTimeUSec. Note that the underlying system calls may have less than microsecond precision, so that the actual delay may be imprecise. The function returns a value greater than 0 if the specified condition is met, 0 if a timeout occurred, or -1 if an error occurred. The error can be retrieved by checking the errno(3) value. In the event both forRead and forWrite are zero, the function immediately returns a timeout indication. PQsocketPoll is implemented using either poll(2) or select(2), depending on platform. See POLLIN and POLLOUT from poll(2), or readfds and writefds from select(2), for more information. PQconndefaults # Returns the default connection options. PQconninfoOption *PQconndefaults(void); typedef struct { char keyword; / The keyword of the option */ char envvar; / Fallback environment variable name */ char compiled; / Fallback compiled in default value */ char val; / Option's current value, or NULL */ char label; / Label for field in connect dialog / char dispchar; / Indicates how to display this field in a connect dialog. Values are: "" Display entered value as is "" Password field - hide value "D" Debug option - don't show by default / int dispsize; / Field size in characters for dialog */ } PQconninfoOption; Returns a connection options array. This can be used to determine all possible PQconnectdb options and their current default values. The return value points to an array of PQconninfoOption structures, which ends with an entry having a null keyword pointer. The null pointer is returned if memory could not be allocated. Note that the current default values (val fields) will depend on environment variables and other context. A missing or invalid service file will be silently ignored. Callers must treat the connection options data as read-only. After processing the options array, free it by passing it to PQconninfoFree. If this is not done, a small amount of memory is leaked for each call to PQconndefaults. PQconninfo # Returns the connection options used by a live connection. PQconninfoOption *PQconninfo(PGconn *conn); Returns a connection options array. This can be used to determine all possible PQconnectdb options and the values that were used to connect to the server. The return value points to an array of PQconninfoOption structures, which ends with an entry having a null keyword pointer. All notes above for PQconndefaults also apply to the result of PQconninfo. PQconninfoParse # Returns parsed connection options from the provided connection string. PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg); Parses a connection string and returns the resulting options as an array; or returns NULL if there is a problem with the connection string. This function can be used to extract the PQconnectdb options in the provided connection string. The return value points to an array of PQconninfoOption structures, which ends with an entry having a null keyword pointer. All legal options will be present in the result array, but the PQconninfoOption for any option not present in the connection string will have val set to NULL; default values are not inserted. If errmsg is not NULL, then *errmsg is set to NULL on success, else to a malloc'd error string explaining the problem. (It is also possible for *errmsg to be set to NULL and the function to return NULL; this indicates an out-of-memory condition.) After processing the options array, free it by passing it to PQconninfoFree. If this is not done, some memory is leaked for each call to PQconninfoParse. Conversely, if an error occurs and errmsg is not NULL, be sure to free the error string using PQfreemem. PQfinish # Closes the connection to the server. Also frees memory used by the PGconn object. void PQfinish(PGconn *conn); Note that even if the server connection attempt fails (as indicated by PQstatus), the application should call PQfinish to free the memory used by the PGconn object. The PGconn pointer must not be used again after PQfinish has been called. PQreset # Resets the communication channel to the server. void PQreset(PGconn *conn); This function will close the connection to the server and attempt to establish a new connection, using all the same parameters previously used. This might be useful for error recovery if a working connection is lost. PQresetStartPQresetPoll # Reset the communication channel to the server, in a nonblocking manner. int PQresetStart(PGconn *conn); PostgresPollingStatusType PQresetPoll(PGconn *conn); These functions will close the connection to the server and attempt to establish a new connection, using all the same parameters previously used. This can be useful for error recovery if a working connection is lost. They differ from PQreset (above) in that they act in a nonblocking manner. These functions suffer from the same restrictions as PQconnectStartParams, PQconnectStart and PQconnectPoll. To initiate a connection reset, call PQresetStart. If it returns 0, the reset has failed. If it returns 1, poll the reset using PQresetPoll in exactly the same way as you would create the connection using PQconnectPoll. PQpingParams # PQpingParams reports the status of the server. It accepts connection parameters identical to those of PQconnectdbParams, described above. 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. PGPing PQpingParams(const char * const *keywords, const char * const *values, int expand_dbname); The function returns one of the following values: PQPING_OK # The server is running and appears to be accepting connections. PQPING_REJECT # The server is running but is in a state that disallows connections (startup, shutdown, or crash recovery). PQPING_NO_RESPONSE # The server could not be contacted. This might indicate that the server is not running, or that there is something wrong with the given connection parameters (for example, wrong port number), or that there is a network connectivity problem (for example, a firewall blocking the connection request). PQPING_NO_ATTEMPT # No attempt was made to contact the server, because the supplied parameters were obviously incorrect or there was some client-side problem (for example, out of memory). PQping # PQping reports the status of the server. It accepts connection parameters identical to those of PQconnectdb, described above. 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. PGPing PQping(const char *conninfo); The return values are the same as for PQpingParams. PQsetSSLKeyPassHook_OpenSSL # PQsetSSLKeyPassHook_OpenSSL lets an application override libpq's default handling of encrypted client certificate key files using sslpassword or interactive prompting. void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook); The application passes a pointer to a callback function with signature: int callback_fn(char *buf, int size, PGconn *conn); which libpq will then call instead of its default PQdefaultSSLKeyPassHook_OpenSSL handler. The callback should determine the password for the key and copy it to result-buffer buf of size size. The string in buf must be null-terminated. The callback must return the length of the password stored in buf excluding the null terminator. On failure, the callback should set buf[0] = '\0' and return 0. See PQdefaultSSLKeyPassHook_OpenSSL in libpq's source code for an example. If the user specified an explicit key location, its path will be in conn->sslkey when the callback is invoked. This will be empty if the default key path is being used. For keys that are engine specifiers, it is up to engine implementations whether they use the OpenSSL password callback or define their own handling. The app callback may choose to delegate unhandled cases to PQdefaultSSLKeyPassHook_OpenSSL, or call it first and try something else if it returns 0, or completely override it. The callback must not escape normal flow control with exceptions, longjmp(...), etc. It must return normally. PQgetSSLKeyPassHook_OpenSSL # PQgetSSLKeyPassHook_OpenSSL returns the current client certificate key password hook, or NULL if none has been set. PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void); 32.1.1. Connection Strings # Several libpq functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plain keyword/value strings and URIs. URIs generally follow RFC 3986, except that multi-host connection strings are allowed as further described below. 32.1.1.1. Keyword/Value Connection Strings # In the keyword/value format, each parameter setting is in the form keyword = value, with space(s) between settings. Spaces around a setting's equal sign are optional. To write an empty value, or a value containing spaces, surround it with single quotes, for example keyword = 'a value'. Single quotes and backslashes within a value must be escaped with a backslash, i.e., ' and \. Example: host=localhost port=5432 dbname=mydb connect_timeout=10 The recognized parameter key words are listed in Section 32.1.2. 32.1.1.2. Connection URIs # The general form for a connection URI is: postgresql://[userspec@][hostspec][/dbname][?paramspec] where userspec is: user[:password] and hostspec is: [host][:port][,...] and paramspec is: name=value[&...] The URI scheme designator can be either postgresql:// or postgres://. Each of the remaining URI parts is optional. The following examples illustrate valid URI syntax: postgresql:// postgresql://localhost postgresql://localhost:5433 postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp Values that would normally appear in the hierarchical part of the URI can alternatively be given as named parameters. For example: postgresql:///mydb?host=localhost&port=5433 All named parameters must match key words listed in Section 32.1.2, except that for compatibility with JDBC connection URIs, instances of ssl=true are translated into sslmode=require. The connection URI needs to be encoded with percent-encoding if it includes symbols with special meaning in any of its parts. Here is an example where the equal sign (=) is replaced with %3D and the space character with %20: postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff The host part may be either a host name or an IP address. To specify an IPv6 address, enclose it in square brackets: postgresql://[2001:db8::1234]/database The host part is interpreted as described for the parameter host. In particular, a Unix-domain socket connection is chosen if the host part is either empty or looks like an absolute path name, otherwise a TCP/IP connection is initiated. Note, however, that the slash is a reserved character in the hierarchical part of the URI. So, to specify a non-standard Unix-domain socket directory, either omit the host part of the URI and specify the host as a named parameter, or percent-encode the path in the host part of the URI: postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname It is possible to specify multiple host components, each with an optional port component, in a single URI. A URI of the form postgresql://host1:port1,host2:port2,host3:port3/ is equivalent to a connection string of the form host=host1,host2,host3 port=port1,port2,port3. As further described below, each host will be tried in turn until a connection is successfully established. 32.1.1.3. Specifying Multiple Hosts # It is possible to specify multiple hosts to connect to, so that they are tried in the given order. In the Keyword/Value format, the host, hostaddr, and port options accept comma-separated lists of values. The same number of elements must be given in each option that is specified, such that e.g., the first hostaddr corresponds to the first host name, the second hostaddr corresponds to the second host name, and so forth. As an exception, if only one port is specified, it applies to all the hosts. In the connection URI format, you can list multiple host:port pairs separated by commas in the host component of the URI. In either format, a single host name can translate to multiple network addresses. A common example of this is a host that has both an IPv4 and an IPv6 address. When multiple hosts are specified, or when a single host name is translated to multiple addresses, all the hosts and addresses will be tried in order, until one succeeds. If none of the hosts can be reached, the connection fails. If a connection is established successfully, but authentication fails, the remaining hosts in the list are not tried. If a password file is used, you can have different passwords for different hosts. All the other connection options are the same for every host in the list; it is not possible to e.g., specify different usernames for different hosts. 32.1.2. Parameter Key Words # The currently recognized parameter key words are: host # Name of host to connect to. If a host name looks like an absolute path name, it specifies Unix-domain communication rather than TCP/IP communication; the value is the name of the directory in which the socket file is stored. (On Unix, an absolute path name begins with a slash. On Windows, paths starting with drive letters are also recognized.) If the host name starts with @, it is taken as a Unix-domain socket in the abstract namespace (currently supported on Linux and Windows). The default behavior when host is not specified, or is empty, is to connect to a Unix-domain socket in /tmp (or whatever socket directory was specified when PostgreSQL was built). On Windows, the default is to connect to localhost. A comma-separated list of host names is also accepted, in which case each host name in the list is tried in order; an empty item in the list selects the default behavior as explained above. See Section 32.1.1.3 for details. hostaddr # Numeric IP address of host to connect to. This should be in the standard IPv4 address format, e.g., 172.28.40.9. If your machine supports IPv6, you can also use those addresses. TCP/IP communication is always used when a nonempty string is specified for this parameter. If this parameter is not specified, the value of host will be looked up to find the corresponding IP address — or, if host specifies an IP address, that value will be used directly. Using hostaddr allows the application to avoid a host name look-up, which might be important in applications with time constraints. However, a host name is required for GSSAPI or SSPI authentication methods, as well as for verify-full SSL certificate verification. The following rules are used: If host is specified without hostaddr, a host name lookup occurs. (When using PQconnectPoll, the lookup occurs when PQconnectPoll first considers this host name, and it may cause PQconnectPoll to block for a significant amount of time.) If hostaddr is specified without host, the value for hostaddr gives the server network address. The connection attempt will fail if the authentication method requires a host name. If both host and hostaddr are specified, the value for hostaddr gives the server network address. The value for host is ignored unless the authentication method requires it, in which case it will be used as the host name. Note that authentication is likely to fail if host is not the name of the server at network address hostaddr. Also, when both host and hostaddr are specified, host is used to identify the connection in a password file (see Section 32.16). A comma-separated list of hostaddr values is also accepted, in which case each host in the list is tried in order. An empty item in the list causes the corresponding host name to be used, or the default host name if that is empty as well. See Section 32.1.1.3 for details. Without either a host name or host address, libpq will connect using a local Unix-domain socket; or on Windows, it will attempt to connect to localhost. port # Port number to connect to at the server host, or socket file name extension for Unix-domain connections. If multiple hosts were given in the host or hostaddr parameters, this parameter may specify a comma-separated list of ports of the same length as the host list, or it may specify a single port number to be used for all hosts. An empty string, or an empty item in a comma-separated list, specifies the default port number established when PostgreSQL was built. dbname # The database name. Defaults to be the same as the user name. In certain contexts, the value is checked for extended formats; see Section 32.1.1 for more details on those. user # PostgreSQL user name to connect as. Defaults to be the same as the operating system name of the user running the application. password # Password to be used if the server demands password authentication. passfile # Specifies the name of the file used to store passwords (see Section 32.16). Defaults to ~/.pgpass, or %APPDATA%\postgresql\pgpass.conf on Microsoft Windows. (No error is reported if this file does not exist.) require_auth # Specifies the authentication method that the client requires from the server. If the server does not use the required method to authenticate the client, or if the authentication handshake is not fully completed by the server, the connection will fail. A comma-separated list of methods may also be provided, of which the server must use exactly one in order for the connection to succeed. By default, any authentication method is accepted, and the server is free to skip authentication altogether. Methods may be negated with the addition of a ! prefix, in which case the server must not attempt the listed method; any other method is accepted, and the server is free not to authenticate the client at all. If a comma-separated list is provided, the server may not attempt any of the listed negated methods. Negated and non-negated forms may not be combined in the same setting. As a final special case, the none method requires the server not to use an authentication challenge. (It may also be negated, to require some form of authentication.) The following methods may be specified: password The server must request plaintext password authentication. md5 The server must request MD5 hashed password authentication. Warning Support for MD5-encrypted passwords is deprecated and will be removed in a future release of PostgreSQL. Refer to Section 20.5 for details about migrating to another password type. gss The server must either request a Kerberos handshake via GSSAPI or establish a GSS-encrypted channel (see also gssencmode). sspi The server must request Windows SSPI authentication. scram-sha-256 The server must successfully complete a SCRAM-SHA-256 authentication exchange with the client. oauth The server must request an OAuth bearer token from the client. none The server must not prompt the client for an authentication exchange. (This does not prohibit client certificate authentication via TLS, nor GSS authentication via its encrypted transport.) channel_binding # This option controls the client's use of channel binding. A setting of require means that the connection must employ channel binding, prefer means that the client will choose channel binding if available, and disable prevents the use of channel binding. The default is prefer if PostgreSQL is compiled with SSL support; otherwise the default is disable. Channel binding is a method for the server to authenticate itself to the client. It is only supported over SSL connections with PostgreSQL 11 or later servers using the SCRAM authentication method. connect_timeout # Maximum time to wait while connecting, in seconds (write as a decimal integer, e.g., 10). Zero, negative, or not specified means wait indefinitely. This timeout applies separately to each host name or IP address. For example, if you specify two hosts and connect_timeout is 5, each host will time out if no connection is made within 5 seconds, so the total time spent waiting for a connection might be up to 10 seconds. client_encoding # This sets the client_encoding configuration parameter for this connection. In addition to the values accepted by the corresponding server option, you can use auto to determine the right encoding from the current locale in the client (LC_CTYPE environment variable on Unix systems). options # Specifies command-line options to send to the server at connection start. For example, setting this to -c geqo=off or --geqo=off sets the session's value of the geqo parameter to off. Spaces within this string are considered to separate command-line arguments, unless escaped with a backslash (); write \ to represent a literal backslash. For a detailed discussion of the available options, consult Chapter 19. application_name # Specifies a value for the application_name configuration parameter. fallback_application_name # Specifies a fallback value for the application_name configuration parameter. This value will be used if no value has been given for application_name via a connection parameter or the PGAPPNAME environment variable. Specifying a fallback name is useful in generic utility programs that wish to set a default application name but allow it to be overridden by the user. keepalives # Controls whether client-side TCP keepalives are used. The default value is 1, meaning on, but you can change this to 0, meaning off, if keepalives are not wanted. This parameter is ignored for connections made via a Unix-domain socket. keepalives_idle # Controls the number of seconds of inactivity after which TCP should send a keepalive message to the server. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket, or if keepalives are disabled. It is only supported on systems where TCP_KEEPIDLE or an equivalent socket option is available, and on Windows; on other systems, it has no effect. keepalives_interval # Controls the number of seconds after which a TCP keepalive message that is not acknowledged by the server should be retransmitted. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket, or if keepalives are disabled. It is only supported on systems where TCP_KEEPINTVL or an equivalent socket option is available, and on Windows; on other systems, it has no effect. keepalives_count # Controls the number of TCP keepalives that can be lost before the client's connection to the server is considered dead. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket, or if keepalives are disabled. It is only supported on systems where TCP_KEEPCNT or an equivalent socket option is available; on other systems, it has no effect. tcp_user_timeout # Controls the number of milliseconds that transmitted data may remain unacknowledged before a connection is forcibly closed. A value of zero uses the system default. This parameter is ignored for connections made via a Unix-domain socket. It is only supported on systems where TCP_USER_TIMEOUT is available; on other systems, it has no effect. replication # This option determines whether the connection should use the replication protocol instead of the normal protocol. This is what PostgreSQL replication connections as well as tools such as pg_basebackup use internally, but it can also be used by third-party applications. For a description of the replication protocol, consult Section 54.4. The following values, which are case-insensitive, are supported: true, on, yes, 1 The connection goes into physical replication mode. database The connection goes into logical replication mode, connecting to the database specified in the dbname parameter. false, off, no, 0 The connection is a regular one, which is the default behavior. In physical or logical replication mode, only the simple query protocol can be used. gssencmode # This option determines whether or with what priority a secure GSS TCP/IP connection will be negotiated with the server. There are three modes: disable only try a non-GSSAPI-encrypted connection prefer (default) if there are GSSAPI credentials present (i.e., in a credentials cache), first try a GSSAPI-encrypted connection; if that fails or there are no credentials, try a non-GSSAPI-encrypted connection. This is the default when PostgreSQL has been compiled with GSSAPI support. require only try a GSSAPI-encrypted connection gssencmode is ignored for Unix domain socket communication. If PostgreSQL is compiled without GSSAPI support, using the require option will cause an error, while prefer will be accepted but libpq will not actually attempt a GSSAPI-encrypted connection. sslmode # This option determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server. There are six modes: disable only try a non-SSL connection allow first try a non-SSL connection; if that fails, try an SSL connection prefer (default) first try an SSL connection; if that fails, try a non-SSL connection require only try an SSL connection. If a root CA file is present, verify the certificate in the same way as if verify-ca was specified verify-ca only try an SSL connection, and verify that the server certificate is issued by a trusted certificate authority (CA) verify-full only try an SSL connection, verify that the server certificate is issued by a trusted CA and that the requested server host name matches that in the certificate See Section 32.19 for a detailed description of how these options work. sslmode is ignored for Unix domain socket communication. If PostgreSQL is compiled without SSL support, using options require, verify-ca, or verify-full will cause an error, while options allow and prefer will be accepted but libpq will not actually attempt an SSL connection. Note that if GSSAPI encryption is possible, that will be used in preference to SSL encryption, regardless of the value of sslmode. To force use of SSL encryption in an environment that has working GSSAPI infrastructure (such as a Kerberos server), also set gssencmode to disable. requiressl # This option is deprecated in favor of the sslmode setting. If set to 1, an SSL connection to the server is required (this is equivalent to sslmode require). libpq will then refuse to connect if the server does not accept an SSL connection. If set to 0 (default), libpq will negotiate the connection type with the server (equivalent to sslmode prefer). This option is only available if PostgreSQL is compiled with SSL support. sslnegotiation # This option controls how SSL encryption is negotiated with the server, if SSL is used. In the default postgres mode, the client first asks the server if SSL is supported. In direct mode, the client starts the standard SSL handshake directly after establishing the TCP/IP connection. Traditional PostgreSQL protocol negotiation is the most flexible with different server configurations. If the server is known to support direct SSL connections then the latter requires one fewer round trip reducing connection latency and also allows the use of protocol agnostic SSL network tools. The direct SSL option was introduced in PostgreSQL version 17. postgres perform PostgreSQL protocol negotiation. This is the default if the option is not provided. direct start SSL handshake directly after establishing the TCP/IP connection. This is only allowed with sslmode=require or higher, because the weaker settings could lead to unintended fallback to plaintext authentication when the server does not support direct SSL handshake. sslcompression # If set to 1, data sent over SSL connections will be compressed. If set to 0, compression will be disabled. The default is 0. This parameter is ignored if a connection without SSL is made. SSL compression is nowadays considered insecure and its use is no longer recommended. OpenSSL 1.1.0 disabled compression by default, and many operating system distributions disabled it in prior versions as well, so setting this parameter to on will not have any effect if the server does not accept compression. PostgreSQL 14 disabled compression completely in the backend. If security is not a primary concern, compression can improve throughput if the network is the bottleneck. Disabling compression can improve response time and throughput if CPU performance is the limiting factor. sslcert # This parameter specifies the file name of the client SSL certificate, replacing the default ~/.postgresql/postgresql.crt. This parameter is ignored if an SSL connection is not made. sslkey # This parameter specifies the location for the secret key used for the client certificate. It can either specify a file name that will be used instead of the default ~/.postgresql/postgresql.key, or it can specify a key obtained from an external “engine” (engines are OpenSSL loadable modules). An external engine specification should consist of a colon-separated engine name and an engine-specific key identifier. This parameter is ignored if an SSL connection is not made. sslkeylogfile # This parameter specifies the location where libpq will log keys used in this SSL context. This is useful for debugging PostgreSQL protocol interactions or client connections using network inspection tools like Wireshark. This parameter is ignored if an SSL connection is not made, or if LibreSSL is used (LibreSSL does not support key logging). Keys are logged using the NSS format. Warning Key logging will expose potentially sensitive information in the keylog file. Keylog files should be handled with the same care as sslkey files. sslpassword # This parameter specifies the password for the secret key specified in sslkey, allowing client certificate private keys to be stored in encrypted form on disk even when interactive passphrase input is not practical. Specifying this parameter with any non-empty value suppresses the Enter PEM pass phrase: prompt that OpenSSL will emit by default when an encrypted client certificate key is provided to libpq. If the key is not encrypted this parameter is ignored. The parameter has no effect on keys specified by OpenSSL engines unless the engine uses the OpenSSL password callback mechanism for prompts. There is no environment variable equivalent to this option, and no facility for looking it up in .pgpass. It can be used in a service file connection definition. Users with more sophisticated uses should consider using OpenSSL engines and tools like PKCS#11 or USB crypto offload devices. sslcertmode # This option determines whether a client certificate may be sent to the server, and whether the server is required to request one. There are three modes: disable A client certificate is never sent, even if one is available (default location or provided via sslcert). allow (default) A certificate may be sent, if the server requests one and the client has one to send. require The server must request a certificate. The connection will fail if the client does not send a certificate and the server successfully authenticates the client anyway. Note sslcertmode=require doesn't add any additional security, since there is no guarantee that the server is validating the certificate correctly; PostgreSQL servers generally request TLS certificates from clients whether they validate them or not. The option may be useful when troubleshooting more complicated TLS setups. sslrootcert # This parameter specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities. The default is ~/.postgresql/root.crt. The special value system may be specified instead, in which case the trusted CA roots from the SSL implementation will be loaded. The exact locations of these root certificates differ by SSL implementation and platform. For OpenSSL in particular, the locations may be further modified by the SSL_CERT_DIR and SSL_CERT_FILE environment variables. Note When using sslrootcert=system, the default sslmode is changed to verify-full, and any weaker setting will result in an error. In most cases it is trivial for anyone to obtain a certificate trusted by the system for a hostname they control, rendering verify-ca and all weaker modes useless. The magic system value will take precedence over a local certificate file with the same name. If for some reason you find yourself in this situation, use an alternative path like sslrootcert=./system instead. sslcrl # This parameter specifies the file name of the SSL server certificate revocation list (CRL). Certificates listed in this file, if it exists, will be rejected while attempting to authenticate the server's certificate. If neither sslcrl nor sslcrldir is set, this setting is taken as ~/.postgresql/root.crl. sslcrldir # This parameter specifies the directory name of the SSL server certificate revocation list (CRL). Certificates listed in the files in this directory, if it exists, will be rejected while attempting to authenticate the server's certificate. The directory needs to be prepared with the OpenSSL command openssl rehash or c_rehash. See its documentation for details. Both sslcrl and sslcrldir can be specified together. sslsni # If set to 1 (default), libpq sets the TLS extension “Server Name Indication” (SNI) on SSL-enabled connections. By setting this parameter to 0, this is turned off. The Server Name Indication can be used by SSL-aware proxies to route connections without having to decrypt the SSL stream. (Note that unless the proxy is aware of the PostgreSQL protocol handshake this would require setting sslnegotiation to direct.) However, SNI makes the destination host name appear in cleartext in the network traffic, so it might be undesirable in some cases. requirepeer # This parameter specifies the operating-system user name of the server, for example requirepeer=postgres. When making a Unix-domain socket connection, if this parameter is set, the client checks at the beginning of the connection that the server process is running under the specified user name; if it is not, the connection is aborted with an error. This parameter can be used to provide server authentication similar to that available with SSL certificates on TCP/IP connections. (Note that if the Unix-domain socket is in /tmp or another publicly writable location, any user could start a server listening there. Use this parameter to ensure that you are connected to a server run by a trusted user.) This option is only supported on platforms for which the peer authentication method is implemented; see Section 20.9. ssl_min_protocol_version # This parameter specifies the minimum SSL/TLS protocol version to allow for the connection. Valid values are TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3. The supported protocols depend on the version of OpenSSL used, older versions not supporting the most modern protocol versions. If not specified, the default is TLSv1.2, which satisfies industry best practices as of this writing. ssl_max_protocol_version # This parameter specifies the maximum SSL/TLS protocol version to allow for the connection. Valid values are TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3. The supported protocols depend on the version of OpenSSL used, older versions not supporting the most modern protocol versions. If not set, this parameter is ignored and the connection will use the maximum bound defined by the backend, if set. Setting the maximum protocol version is mainly useful for testing or if some component has issues working with a newer protocol. min_protocol_version # Specifies the minimum protocol version to allow for the connection. The default is to allow any version of the PostgreSQL protocol supported by libpq, which currently means 3.0. If the server does not support at least this protocol version the connection will be closed. The current supported values are 3.0, 3.2, and latest. The latest value is equivalent to the latest protocol version supported by the libpq version being used, which is currently 3.2. max_protocol_version # Specifies the protocol version to request from the server. The default is to use version 3.0 of the PostgreSQL protocol, unless the connection string specifies a feature that relies on a higher protocol version, in which case the latest version supported by libpq is used. If the server does not support the protocol version requested by the client, the connection is automatically downgraded to a lower minor protocol version that the server supports. After the connection attempt has completed you can use PQprotocolVersion to find out which exact protocol version was negotiated. The current supported values are 3.0, 3.2, and latest. The latest value is equivalent to the latest protocol version supported by the libpq version being used, which is currently 3.2. krbsrvname # Kerberos service name to use when authenticating with GSSAPI. This must match the service name specified in the server configuration for Kerberos authentication to succeed. (See also Section 20.6.) The default value is normally postgres, but that can be changed when building PostgreSQL via the --with-krb-srvnam option of configure. In most environments, this parameter never needs to be changed. Some Kerberos implementations might require a different service name, such as Microsoft Active Directory which requires the service name to be in upper case (POSTGRES). gsslib # GSS library to use for GSSAPI authentication. Currently this is disregarded except on Windows builds that include both GSSAPI and SSPI support. In that case, set this to gssapi to cause libpq to use the GSSAPI library for authentication instead of the default SSPI. gssdelegation # Forward (delegate) GSS credentials to the server. The default is 0 which means credentials will not be forwarded to the server. Set this to 1 to have credentials forwarded when possible. scram_client_key # The base64-encoded SCRAM client key. This can be used by foreign-data wrappers or similar middleware to enable pass-through SCRAM authentication. See Section F.38.1.10 for one such implementation. It is not meant to be specified directly by users or client applications. scram_server_key # The base64-encoded SCRAM server key. This can be used by foreign-data wrappers or similar middleware to enable pass-through SCRAM authentication. See Section F.38.1.10 for one such implementation. It is not meant to be specified directly by users or client applications. service # Service name to use for additional parameters. It specifies a service name in pg_service.conf that holds additional connection parameters. This allows applications to specify only a service name so connection parameters can be centrally maintained. See Section 32.17. target_session_attrs # This option determines whether the session must have certain properties to be acceptable. It's typically used in combination with multiple host names to select the first acceptable alternative among several hosts. There are six modes: any (default) any successful connection is acceptable read-write session must accept read-write transactions by default (that is, the server must not be in hot standby mode and the default_transaction_read_only parameter must be off) read-only session must not accept read-write transactions by default (the converse) primary server must not be in hot standby mode standby server must be in hot standby mode prefer-standby first try to find a standby server, but if none of the listed hosts is a standby server, try again in any mode load_balance_hosts # Controls the order in which the client tries to connect to the available hosts and addresses. Once a connection attempt is successful no other hosts and addresses will be tried. This parameter is typically used in combination with multiple host names or a DNS record that returns multiple IPs. This parameter can be used in combination with target_session_attrs to, for example, load balance over standby servers only. Once successfully connected, subsequent queries on the returned connection will all be sent to the same server. There are currently two modes: disable (default) No load balancing across hosts is performed. Hosts are tried in the order in which they are provided and addresses are tried in the order they are received from DNS or a hosts file. random Hosts and addresses are tried in random order. This value is mostly useful when opening multiple connections at the same time, possibly from different machines. This way connections can be load balanced across multiple PostgreSQL servers. While random load balancing, due to its random nature, will almost never result in a completely uniform distribution, it statistically gets quite close. One important aspect here is that this algorithm uses two levels of random choices: First the hosts will be resolved in random order. Then secondly, before resolving the next host, all resolved addresses for the current host will be tried in random order. This behaviour can skew the amount of connections each node gets greatly in certain cases, for instance when some hosts resolve to more addresses than others. But such a skew can also be used on purpose, e.g. to increase the number of connections a larger server gets by providing its hostname multiple times in the host string. When using this value it's recommended to also configure a reasonable value for connect_timeout. Because then, if one of the nodes that are used for load balancing is not responding, a new node will be tried. oauth_issuer # The HTTPS URL of a trusted issuer to contact if the server requests an OAuth token for the connection. This parameter is required for all OAuth connections; it should exactly match the issuer setting in the server's HBA configuration. As part of the standard authentication handshake, libpq will ask the server for a discovery document: a URL providing a set of OAuth configuration parameters. The server must provide a URL that is directly constructed from the components of the oauth_issuer, and this value must exactly match the issuer identifier that is declared in the discovery document itself, or the connection will fail. This is required to prevent a class of "mix-up attacks" on OAuth clients. You may also explicitly set oauth_issuer to the /.well-known/ URI used for OAuth discovery. In this case, if the server asks for a different URL, the connection will fail, but a custom OAuth flow may be able to speed up the standard handshake by using previously cached tokens. (In this case, it is recommended that oauth_scope be set as well, since the client will not have a chance to ask the server for a correct scope setting, and the default scopes for a token may not be sufficient to connect.) libpq currently supports the following well-known endpoints: /.well-known/openid-configuration /.well-known/oauth-authorization-server Warning Issuers are highly privileged during the OAuth connection handshake. As a rule of thumb, if you would not trust the operator of a URL to handle access to your servers, or to impersonate you directly, that URL should not be trusted as an oauth_issuer. oauth_client_id # An OAuth 2.0 client identifier, as issued by the authorization server. If the PostgreSQL server requests an OAuth token for the connection (and if no custom OAuth hook is installed to provide one), then this parameter must be set; otherwise, the connection will fail. oauth_client_secret # The client password, if any, to use when contacting the OAuth authorization server. Whether this parameter is required or not is determined by the OAuth provider; "public" clients generally do not use a secret, whereas "confidential" clients generally do. oauth_scope # The scope of the access request sent to the authorization server, specified as a (possibly empty) space-separated list of OAuth scope identifiers. This parameter is optional and intended for advanced usage. Usually the client will obtain appropriate scope settings from the PostgreSQL server. If this parameter is used, the server's requested scope list will be ignored. This can prevent a less-trusted server from requesting inappropriate access scopes from the end user. However, if the client's scope setting does not contain the server's required scopes, the server is likely to reject the issued token, and the connection will fail. The meaning of an empty scope list is provider-dependent. An OAuth authorization server may choose to issue a token with "default scope", whatever that happens to be, or it may reject the token request entirely.
PGconnPattern 2: 32.1.1. Connection Strings # Several libpq functions parse a user-specified string to obtain connection parameters. There are two accepted formats for these strings: plain keyword/value strings and URIs. URIs generally follow RFC 3986, except that multi-host connection strings are allowed as further described below. 32.1.1.1. Keyword/Value Connection Strings # In the keyword/value format, each parameter setting is in the form keyword = value, with space(s) between settings. Spaces around a setting's equal sign are optional. To write an empty value, or a value containing spaces, surround it with single quotes, for example keyword = 'a value'. Single quotes and backslashes within a value must be escaped with a backslash, i.e., ' and \. Example: host=localhost port=5432 dbname=mydb connect_timeout=10 The recognized parameter key words are listed in Section 32.1.2. 32.1.1.2. Connection URIs # The general form for a connection URI is: postgresql://[userspec@][hostspec][/dbname][?paramspec] where userspec is: user[:password] and hostspec is: [host][:port][,...] and paramspec is: name=value[&...] The URI scheme designator can be either postgresql:// or postgres://. Each of the remaining URI parts is optional. The following examples illustrate valid URI syntax: postgresql:// postgresql://localhost postgresql://localhost:5433 postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp Values that would normally appear in the hierarchical part of the URI can alternatively be given as named parameters. For example: postgresql:///mydb?host=localhost&port=5433 All named parameters must match key words listed in Section 32.1.2, except that for compatibility with JDBC connection URIs, instances of ssl=true are translated into sslmode=require. The connection URI needs to be encoded with percent-encoding if it includes symbols with special meaning in any of its parts. Here is an example where the equal sign (=) is replaced with %3D and the space character with %20: postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff The host part may be either a host name or an IP address. To specify an IPv6 address, enclose it in square brackets: postgresql://[2001:db8::1234]/database The host part is interpreted as described for the parameter host. In particular, a Unix-domain socket connection is chosen if the host part is either empty or looks like an absolute path name, otherwise a TCP/IP connection is initiated. Note, however, that the slash is a reserved character in the hierarchical part of the URI. So, to specify a non-standard Unix-domain socket directory, either omit the host part of the URI and specify the host as a named parameter, or percent-encode the path in the host part of the URI: postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname It is possible to specify multiple host components, each with an optional port component, in a single URI. A URI of the form postgresql://host1:port1,host2:port2,host3:port3/ is equivalent to a connection string of the form host=host1,host2,host3 port=port1,port2,port3. As further described below, each host will be tried in turn until a connection is successfully established. 32.1.1.3. Specifying Multiple Hosts # It is possible to specify multiple hosts to connect to, so that they are tried in the given order. In the Keyword/Value format, the host, hostaddr, and port options accept comma-separated lists of values. The same number of elements must be given in each option that is specified, such that e.g., the first hostaddr corresponds to the first host name, the second hostaddr corresponds to the second host name, and so forth. As an exception, if only one port is specified, it applies to all the hosts. In the connection URI format, you can list multiple host:port pairs separated by commas in the host component of the URI. In either format, a single host name can translate to multiple network addresses. A common example of this is a host that has both an IPv4 and an IPv6 address. When multiple hosts are specified, or when a single host name is translated to multiple addresses, all the hosts and addresses will be tried in order, until one succeeds. If none of the hosts can be reached, the connection fails. If a connection is established successfully, but authentication fails, the remaining hosts in the list are not tried. If a password file is used, you can have different passwords for different hosts. All the other connection options are the same for every host in the list; it is not possible to e.g., specify different usernames for different hosts.
keywordPattern 3: Example:
host=localhost port=5432 dbname=mydb connect_timeout=10Pattern 4: 32.1.1.2. Connection URIs # The general form for a connection URI is: postgresql://[userspec@][hostspec][/dbname][?paramspec] where userspec is: user[:password] and hostspec is: [host][:port][,...] and paramspec is: name=value[&...] The URI scheme designator can be either postgresql:// or postgres://. Each of the remaining URI parts is optional. The following examples illustrate valid URI syntax: postgresql:// postgresql://localhost postgresql://localhost:5433 postgresql://localhost/mydb postgresql://user@localhost postgresql://user:secret@localhost postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp Values that would normally appear in the hierarchical part of the URI can alternatively be given as named parameters. For example: postgresql:///mydb?host=localhost&port=5433 All named parameters must match key words listed in Section 32.1.2, except that for compatibility with JDBC connection URIs, instances of ssl=true are translated into sslmode=require. The connection URI needs to be encoded with percent-encoding if it includes symbols with special meaning in any of its parts. Here is an example where the equal sign (=) is replaced with %3D and the space character with %20: postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff The host part may be either a host name or an IP address. To specify an IPv6 address, enclose it in square brackets: postgresql://[2001:db8::1234]/database The host part is interpreted as described for the parameter host. In particular, a Unix-domain socket connection is chosen if the host part is either empty or looks like an absolute path name, otherwise a TCP/IP connection is initiated. Note, however, that the slash is a reserved character in the hierarchical part of the URI. So, to specify a non-standard Unix-domain socket directory, either omit the host part of the URI and specify the host as a named parameter, or percent-encode the path in the host part of the URI: postgresql:///dbname?host=/var/lib/postgresql postgresql://%2Fvar%2Flib%2Fpostgresql/dbname It is possible to specify multiple host components, each with an optional port component, in a single URI. A URI of the form postgresql://host1:port1,host2:port2,host3:port3/ is equivalent to a connection string of the form host=host1,host2,host3 port=port1,port2,port3. As further described below, each host will be tried in turn until a connection is successfully established.
postgresql://[userspec@][hostspec][/dbname][?paramspec]
where userspec is:
user[:password]
and hostspec is:
[host][:port][,...]
and paramspec is:
name=value[&...]Pattern 5: 21.5. Predefined Roles # PostgreSQL provides a set of predefined roles that provide access to certain, commonly needed, privileged capabilities and information. Administrators (including roles that have the CREATEROLE privilege) can GRANT these roles to users and/or other roles in their environment, providing those users with access to the specified capabilities and information. For example: GRANT pg_signal_backend TO admin_user; Warning Care should be taken when granting these roles to ensure they are only used where needed and with the understanding that these roles grant access to privileged information. The predefined roles are described below. Note that the specific permissions for each of the roles may change in the future as additional capabilities are added. Administrators should monitor the release notes for changes. pg_checkpoint # pg_checkpoint allows executing the CHECKPOINT command. pg_create_subscription # pg_create_subscription allows users with CREATE permission on the database to issue CREATE SUBSCRIPTION. pg_database_owner # pg_database_owner always has exactly one implicit member: the current database owner. It cannot be granted membership in any role, and no role can be granted membership in pg_database_owner. However, like any other role, it can own objects and receive grants of access privileges. Consequently, once pg_database_owner has rights within a template database, each owner of a database instantiated from that template will possess those rights. Initially, this role owns the public schema, so each database owner governs local use of that schema. pg_maintain # pg_maintain allows executing VACUUM, ANALYZE, CLUSTER, REFRESH MATERIALIZED VIEW, REINDEX, and LOCK TABLE on all relations, as if having MAINTAIN rights on those objects. pg_monitorpg_read_all_settingspg_read_all_statspg_stat_scan_tables # These roles are intended to allow administrators to easily configure a role for the purpose of monitoring the database server. They grant a set of common privileges allowing the role to read various useful configuration settings, statistics, and other system information normally restricted to superusers. pg_monitor allows reading/executing various monitoring views and functions. This role is a member of pg_read_all_settings, pg_read_all_stats and pg_stat_scan_tables. pg_read_all_settings allows reading all configuration variables, even those normally visible only to superusers. pg_read_all_stats allows reading all pg_stat_* views and use various statistics related extensions, even those normally visible only to superusers. pg_stat_scan_tables allows executing monitoring functions that may take ACCESS SHARE locks on tables, potentially for a long time (e.g., pgrowlocks(text) in the pgrowlocks extension). pg_read_all_datapg_write_all_data # pg_read_all_data allows reading all data (tables, views, sequences), as if having SELECT rights on those objects and USAGE rights on all schemas. This role does not bypass row-level security (RLS) policies. If RLS is being used, an administrator may wish to set BYPASSRLS on roles which this role is granted to. pg_write_all_data allows writing all data (tables, views, sequences), as if having INSERT, UPDATE, and DELETE rights on those objects and USAGE rights on all schemas. This role does not bypass row-level security (RLS) policies. If RLS is being used, an administrator may wish to set BYPASSRLS on roles which this role is granted to. pg_read_server_filespg_write_server_filespg_execute_server_program # These roles are intended to allow administrators to have trusted, but non-superuser, roles which are able to access files and run programs on the database server as the user the database runs as. They bypass all database-level permission checks when accessing files directly and they could be used to gain superuser-level access. Therefore, great care should be taken when granting these roles to users. pg_read_server_files allows reading files from any location the database can access on the server using COPY and other file-access functions. pg_write_server_files allows writing to files in any location the database can access on the server using COPY and other file-access functions. pg_execute_server_program allows executing programs on the database server as the user the database runs as using COPY and other functions which allow executing a server-side program. pg_signal_autovacuum_worker # pg_signal_autovacuum_worker allows signaling autovacuum workers to cancel the current table's vacuum or terminate its session. See Section 9.28.2. pg_signal_backend # pg_signal_backend allows signaling another backend to cancel a query or terminate its session. Note that this role does not permit signaling backends owned by a superuser. See Section 9.28.2. pg_use_reserved_connections # pg_use_reserved_connections allows use of connection slots reserved via reserved_connections.
CREATEROLEPattern 6: 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, DELETE, and MERGE 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 default 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 default 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 default data available to RETURNING is the content of the deleted row. For example: DELETE FROM products WHERE obsoletion_date = 'today' RETURNING ; In a MERGE, the default data available to RETURNING is the content of the source row plus the content of the inserted, updated, or deleted target row. Since it is quite common for the source and target to have many of the same columns, specifying RETURNING * can lead to a lot of duplicated columns, so it is often more useful to qualify it so as to return just the source or target row. For example: MERGE INTO products p USING new_products n ON p.product_no = n.product_no WHEN NOT MATCHED THEN INSERT VALUES (n.product_no, n.name, n.price) WHEN MATCHED THEN UPDATE SET name = n.name, price = n.price RETURNING p.; In each of these commands, it is also possible to explicitly return the old and new content of the modified row. For example: UPDATE products SET price = price * 1.10 WHERE price <= 99.99 RETURNING name, old.price AS old_price, new.price AS new_price, new.price - old.price AS price_change; In this example, writing new.price is the same as just writing price, but it makes the meaning clearer. This syntax for returning old and new values is available in INSERT, UPDATE, DELETE, and MERGE commands, but typically old values will be NULL for an INSERT, and new values will be NULL for a DELETE. However, there are situations where it can still be useful for those commands. For example, in an INSERT with an ON CONFLICT DO UPDATE clause, the old values will be non-NULL for conflicting rows. Similarly, if a DELETE is turned into an UPDATE by a rewrite rule, the new values may be non-NULL. If there are triggers (Chapter 37) 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.
INSERTPattern 7: In an UPDATE, the default data available to RETURNING is the new content of the modified row. For example:
UPDATEPattern 8: In a DELETE, the default data available to RETURNING is the content of the deleted row. For example:
DELETE模式1: 32.1. 数据库连接控制函数 # 32.1.1. 连接字符串 32.1.2. 参数关键字
以下函数用于建立与PostgreSQL后端服务器的连接。应用程序可以同时打开多个后端连接(例如访问多个数据库)。每个连接由PGconn对象表示,可通过PQconnectdb、PQconnectdbParams或PQsetdbLogin函数获取。注意,除非内存不足无法分配PGconn对象,否则这些函数始终返回非空指针。在通过连接对象发送查询之前,应调用PQstatus函数检查连接是否成功。
警告:如果不受信任的用户可以访问未采用安全模式使用规范的数据库,请在每个会话开始时从search_path中移除可公开写入的模式。可以将参数关键字options设置为值 -csearch_path=.,或者在连接后执行PQexec(conn, "SELECT pg_catalog.set_config('search_path', '', false)")。注意,这并非libpq特有的问题,而是适用于所有执行任意SQL命令的接口。
警告:在Unix系统中,fork带有打开的libpq连接的进程可能导致不可预测的结果,因为父子进程共享相同的套接字和操作系统资源。因此不建议这样使用,但在子进程中执行exec加载新可执行文件是安全的。
PQconnectdbParams # 建立与数据库服务器的新连接
PGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname);
该函数使用两个以NULL结尾的数组中的参数打开新的数据库连接。第一个数组keywords是关键字数组,第二个数组values是对应关键字的值。与下面的PQsetdbLogin不同,该函数的参数集可以扩展而无需更改函数签名,因此对于新的应用程序编程,建议使用此函数(或其非阻塞版本PQconnectStartParams和PQconnectPoll)。当前支持的参数关键字请参见32.1.2节。传入的数组可以为空以使用所有默认参数,也可以包含一个或多个参数设置。数组长度必须匹配,处理将在keywords数组中的第一个NULL条目处停止。此外,如果与非NULL关键字条目关联的values条目为NULL或空字符串,则忽略该条目并继续处理下一对数组条目。
当expand_dbname非零时,会检查第一个dbname关键字的值是否为连接字符串。如果是,则将其“展开”为从字符串中提取的各个连接参数。如果值包含等号(=)或以URI方案指示符开头,则将其视为连接字符串而非单纯的数据库名称(连接字符串格式的更多详细信息请参见32.1.1节)。只有第一个dbname会被这样处理;后续的dbname参数将被视为普通数据库名称。
通常,参数数组会从头到尾处理。如果任何关键字重复,则使用最后一个非NULL或非空的值。当连接字符串中的关键字与keywords数组中的关键字冲突时,此规则同样适用。因此,程序员可以决定数组条目是否可以覆盖连接字符串中的值,或者被其覆盖。在展开的dbname条目之前出现的数组条目可能会被连接字符串的字段覆盖,而这些字段又会被dbname之后出现的数组条目覆盖(但仅当这些条目提供非空值时)。处理完所有数组条目和任何展开的连接字符串后,任何未设置的连接参数将使用默认值填充。如果未设置的参数对应的环境变量(参见32.15节)已设置,则使用其值;否则使用参数的内置默认值。
PQconnectdb # 建立与数据库服务器的新连接
PGconn *PQconnectdb(const char *conninfo);
该函数使用conninfo字符串中的参数打开新的数据库连接。传入的字符串可以为空以使用所有默认参数,也可以包含一个或多个由空格分隔的参数设置,或者包含一个URI。详细信息请参见32.1.1节。
PQsetdbLogin # 建立与数据库服务器的新连接
PGconn *PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd);
这是PQconnectdb的前身,具有固定的参数集。它的功能与PQconnectdb相同,只是缺失的参数将始终采用默认值。对于任何要使用默认值的固定参数,请传入NULL或空字符串。如果dbName包含等号或有效的连接URI前缀,则会将其视为conninfo字符串,就像传递给PQconnectdb一样,然后按照PQconnectdbParams的指定应用其余参数。pgtty不再使用,传递的任何值都将被忽略。
PQsetdb # 建立与数据库服务器的新连接
PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName);
这是一个宏,调用PQsetdbLogin时传入login和pwd的空指针。它是为了与非常旧的程序向后兼容而提供的。
PQconnectStartParams、PQconnectStart、PQconnectPoll # 以非阻塞方式建立与数据库服务器的连接
PGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname);
PGconn *PQconnectStart(const char *conninfo);
PostgresPollingStatusType PQconnectPoll(PGconn *conn);
这三个函数用于打开与数据库服务器的连接,使应用程序的执行线程在执行此操作时不会被远程I/O阻塞。这种方法的优点是,等待I/O完成的过程可以在应用程序的主循环中进行,而不是在PQconnectdbParams或PQconnectdb内部,因此应用程序可以在执行此操作的同时管理其他活动。
使用PQconnectStartParams时,数据库连接使用keywords和values数组中的参数,并由expand_dbname控制,如PQconnectdbParams所述。使用PQconnectStart时,数据库连接使用conninfo字符串中的参数,如PQconnectdb所述。
只要满足一些限制条件,PQconnectStartParams、PQconnectStart和PQconnectPoll都不会阻塞:必须正确使用hostaddr参数以避免进行DNS查询(有关此参数的详细信息请参见32.1.2节);如果调用PQtrace,请确保跟踪的流对象不会阻塞;在调用PQconnectPoll之前,必须确保套接字处于适当的状态,如下所述。
要开始非阻塞连接请求,请调用PQconnectStart或PQconnectStartParams。如果结果为null,则libpq无法分配新的PGconn结构。否则,将返回有效的PGconn指针(尽管尚未表示与数据库的有效连接)。接下来调用PQstatus(conn)。如果结果为CONNECTION_BAD,则连接尝试已失败,通常是因为连接参数无效。
如果PQconnectStart或PQconnectStartParams成功,下一步是轮询libpq以继续连接序列。使用PQsocket(conn)获取数据库连接底层的套接字描述符(注意:不要假设套接字在PQconnectPoll调用之间保持不变)。循环执行以下步骤:
如果PQconnectPoll(conn)上次返回PGRES_POLLING_READING,则等待套接字准备好读取(由select()、poll()或类似系统函数指示)。注意,如果系统支持,PQsocketPoll可以通过抽象select(2)或poll(2)的设置来减少样板代码。然后再次调用PQconnectPoll(conn)。反之,如果PQconnectPoll(conn)上次返回PGRES_POLLING_WRITING,则等待套接字准备好写入,然后再次调用PQconnectPoll(conn)。在第一次迭代中(即尚未调用PQconnectPoll时),应视为上次返回PGRES_POLLING_WRITING。
继续此循环,直到PQconnectPoll(conn)返回PGRES_POLLING_FAILED(表示连接过程失败)或PGRES_POLLING_OK(表示连接已成功建立)。
在连接过程中的任何时候,都可以通过调用PQstatus检查连接状态。如果返回CONNECTION_BAD,则连接过程已失败;如果返回CONNECTION_OK,则连接已准备就绪。这两种状态也可以通过PQconnectPoll的返回值检测到。在异步连接过程中(且仅在此过程中)可能还会出现其他状态,这些状态指示连接过程的当前阶段,可能用于向用户提供反馈。这些状态包括:
CONNECTION_STARTED # 等待连接建立
CONNECTION_MADE # 连接已建立;等待发送数据
CONNECTION_AWAITING_RESPONSE # 等待来自服务器的响应
CONNECTION_AUTH_OK # 已通过身份验证;等待后端启动完成
CONNECTION_SSL_STARTUP # 正在协商SSL加密
CONNECTION_GSS_STARTUP # 正在协商GSS加密
CONNECTION_CHECK_WRITABLE # 检查连接是否能够处理写入事务
CONNECTION_CHECK_STANDBY # 检查连接是否指向备用模式的服务器
CONNECTION_CONSUME # 正在处理连接中的剩余响应消息
注意,尽管这些常量将保留(以保持兼容性),但应用程序不应依赖它们以特定顺序出现,或必须出现,也不应依赖状态始终是这些记录的值。应用程序可以这样处理:
switch(PQstatus(conn)) {
case CONNECTION_STARTED:
feedback = "正在连接...";
break;
case CONNECTION_MADE:
feedback = "已连接到服务器...";
break;
...
default:
feedback = "正在连接...";
}
使用PQconnectPoll时,connect_timeout连接参数将被忽略;应用程序负责判断是否已花费过多时间。否则,PQconnectStart后跟PQconnectPoll循环等效于PQconnectdb。注意,当PQconnectStart或PQconnectStartParams返回非空指针时,即使连接尝试失败或被放弃,也必须在使用完毕后调用PQfinish以释放结构和任何相关内存块。
PQsocketPoll # 轮询通过PQsocket获取的连接底层套接字描述符
该函数的主要用途是在PQconnectStartParams文档中描述的连接序列中进行迭代。
typedef int64_t pg_usec_time_t;
int PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time);
该函数对文件描述符进行轮询,可选择设置超时。如果forRead非零,函数将在套接字准备好读取时终止。如果forWrite非零,函数将在套接字准备好写入时终止。超时由end_time指定,即停止等待的时间,表示为自Unix纪元以来的微秒数(即time_t乘以100万)。如果end_time为-1,则超时为无限;如果end_time为0(或任何早于当前时间的时间),则超时为立即(无阻塞)。可以通过将所需的微秒数添加到PQgetCurrentTimeUSec的结果中来方便地计算超时值。注意,底层系统调用的精度可能低于微秒,因此实际延迟可能不精确。
如果指定的条件满足,函数返回大于0的值;如果超时,返回0;如果发生错误,返回-1。可以通过检查errno(3)值来获取错误信息。如果forRead和forWrite都为零,函数将立即返回超时指示。PQsocketPoll使用poll(2)或select(2)实现,具体取决于平台。有关更多信息,请参见poll(2)中的POLLIN和POLLOUT,或select(2)中的readfds和writefds。
PQconndefaults # 返回默认连接选项
PQconninfoOption *PQconndefaults(void);
typedef struct {
char keyword; / 选项的关键字 */
char envvar; / 备用环境变量名称 */
char compiled; / 备用编译时默认值 */
char val; / 选项的当前值,或NULL */
char label; / 连接对话框中字段的标签 /
char dispchar; / 指示如何在连接对话框中显示此字段。值包括:"" 按原样显示输入的值;"" 密码字段 - 隐藏值;"D" 调试选项 - 默认不显示 /
int dispsize; / 对话框中字段的字符大小 */
} PQconninfoOption;
返回连接选项数组,可用于确定所有可能的PQconnectdb选项及其当前默认值。返回值指向PQconninfoOption结构的数组,数组末尾是一个关键字为null的条目。如果无法分配内存,则返回null指针。注意,当前默认值(val字段)将取决于环境变量和其他上下文。缺失或无效的服务文件将被静默忽略。调用者必须将连接选项数据视为只读。处理完选项数组后,通过将其传递给PQconninfoFree来释放它。如果不这样做,每次调用PQconndefaults都会泄漏少量内存。
PQconninfo # 返回活动连接使用的连接选项
PQconninfoOption *PQconninfo(PGconn *conn);
返回连接选项数组,可用于确定所有可能的PQconnectdb选项以及用于连接到服务器的值。返回值指向PQconninfoOption结构的数组,数组末尾是一个关键字为null的条目。上述关于PQconndefaults的所有注意事项也适用于PQconninfo的结果。
PQconninfoParse # 从提供的连接字符串返回解析后的连接选项
PQconninfoOption PQconninfoParse(const char conninfo, char **errmsg);
解析连接字符串并将结果选项作为数组返回;如果连接字符串有问题,则返回NULL。此函数可用于提取提供的连接字符串中的PQconnectdb选项。返回值指向PQconninfoOption结构的数组,数组末尾是一个关键字为null的条目。结果数组中将包含所有合法选项,但连接字符串中不存在的选项对应的PQconninfoOption的val将设置为NULL;不会插入默认值。如果errmsg不为NULL,则成功时errmsg设置为NULL,否则设置为malloc分配的错误字符串以解释问题(也可能errmsg设置为NULL且函数返回NULL,这表示内存不足)。处理完选项数组后,通过将其传递给PQconninfoFree来释放它。如果不这样做,每次调用PQconninfoParse都会泄漏一些内存。反之,如果发生错误且errmsg不为NULL,请务必使用PQfreemem释放错误字符串。
PQfinish # 关闭与服务器的连接并释放PGconn对象使用的内存
void PQfinish(PGconn *conn);
注意,即使服务器连接尝试失败(由PQstatus指示),应用程序也应调用PQfinish以释放PGconn对象使用的内存。调用PQfinish后,不得再使用PGconn指针。
PQreset # 重置与服务器的通信通道
void PQreset(PGconn *conn);
该函数将关闭与服务器的连接,并尝试使用之前的所有参数建立新连接。这在工作连接丢失时的错误恢复中可能有用。
PQresetStart、PQresetPoll # 以非阻塞方式重置与服务器的通信通道
int PQresetStart(PGconn *conn);
PostgresPollingStatusType PQresetPoll(PGconn *conn);
这些函数将关闭与服务器的连接,并尝试使用之前的所有参数建立新连接。这在工作连接丢失时的错误恢复中可能有用。它们与PQreset(上述)的不同之处在于它们以非阻塞方式运行。这些函数与PQconnectStartParams、PQconnectStart和PQconnectPoll有相同的限制。
要启动连接重置,请调用PQresetStart。如果返回0,则重置失败。如果返回1,则使用PQresetPoll轮询重置,方式与使用PQconnectPoll创建连接完全相同。
PQpingParams # PQpingParams报告服务器状态
它接受与PQconnectdbParams相同的连接参数,如上所述。无需提供正确的用户名、密码或数据库名称即可获取服务器状态;但是,如果提供了不正确的值,服务器将记录失败的连接尝试。
PGPing PQpingParams(const char * const *keywords, const char * const *values, int expand_dbname);
该函数返回以下值之一:
PQPING_OK # 服务器正在运行且似乎接受连接
PQPING_REJECT # 服务器正在运行,但处于不允许连接的状态(启动、关闭或崩溃恢复)
PQPING_NO_RESPONSE # 无法联系到服务器,可能表示服务器未运行、连接参数错误(例如端口号错误)或存在网络连接问题(例如防火墙阻止连接请求)
PQPING_NO_ATTEMPT # 未尝试联系服务器,因为提供的参数明显不正确或存在客户端问题(例如内存不足)
PQping # PQping报告服务器状态
它接受与PQconnectdb相同的连接参数,如上所述。无需提供正确的用户名、密码或数据库名称即可获取服务器状态;但是,如果提供了不正确的值,服务器将记录失败的连接尝试。
PGPing PQping(const char *conninfo);
返回值与PQpingParams相同。
PQsetSSLKeyPassHook_OpenSSL # PQsetSSLKeyPassHook_OpenSSL允许应用程序覆盖libpq对加密客户端证书密钥文件的默认处理方式,使用sslpassword或交互式提示
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
应用程序传递一个回调函数指针,签名为:
int callback_fn(char *buf, int size, PGconn *conn);
然后libpq将调用此函数,而非其默认的PQdefaultSSLKeyPassHook_OpenSSL处理程序。回调函数应确定密钥的密码并将其复制到大小为size的结果缓冲区buf中,buf中的字符串必须以null结尾。回调函数必须返回buf中存储的密码长度(不包括null终止符)。失败时,回调函数应设置buf[0] = '\0'并返回0。有关示例,请参见libpq源代码中的PQdefaultSSLKeyPassHook_OpenSSL。
如果用户指定了显式的密钥位置,则在调用回调函数时,conn->sslkey将包含其路径。如果使用默认密钥路径,则该值为空。对于作为引擎指定符的密钥,是否使用OpenSSL密码回调或定义自己的处理方式由引擎实现决定。应用程序回调可以选择将未处理的情况委托给PQdefaultSSLKeyPassHook_OpenSSL,或者先调用它并在返回0时尝试其他方法,或者完全覆盖它。回调函数不得使用异常、longjmp(...)等方式逃避正常的流程控制,必须正常返回。
PQgetSSLKeyPassHook_OpenSSL # PQgetSSLKeyPassHook_OpenSSL返回当前的客户端证书密钥密码钩子,如果未设置则返回NULL
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
32.1.1. 连接字符串 # 多个libpq函数解析用户指定的字符串以获取连接参数。这些字符串有两种接受的格式:普通关键字/值字符串和URI。URI通常遵循RFC 3986,但允许多主机连接字符串,如下所述。
32.1.1.1. 关键字/值连接字符串 # 在关键字/值格式中,每个参数设置的形式为keyword = value,设置之间用空格分隔。设置的等号两侧的空格是可选的。要写入空值或包含空格的值,请用单引号括起来,例如keyword = 'a value'。值中的单引号和反斜杠必须用反斜杠转义,即'和\。示例:host=localhost port=5432 dbname=mydb connect_timeout=10。已识别的参数关键字请参见32.1.2节。
32.1.1.2. 连接URI # 连接URI的一般形式为:
postgresql://[userspec@][hostspec][/dbname][?paramspec]
其中userspec为:
user[:password]
hostspec为:
[host][:port][,...]
paramspec为:
name=value[&...]
URI方案指示符可以是postgresql://或postgres://。其余的URI部分都是可选的。以下示例展示了有效的URI语法:
postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp
通常出现在URI层次结构部分的值也可以作为命名参数给出。例如:
postgresql:///mydb?host=localhost&port=5433
所有命名参数必须与32.1.2节中列出的关键字匹配,除了为了与JDBC连接URI兼容,ssl=true将被转换为sslmode=require。如果连接URI包含其任何部分中具有特殊含义的符号,则需要进行百分号编码。以下示例中,等号(=)替换为%3D,空格字符替换为%20:
postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
主机部分可以是主机名或IP地址。要指定IPv6地址,请将其括在方括号中:
postgresql://[2001:db8::1234]/database
主机部分的解释与host参数的描述相同。特别是,如果主机部分为空或看起来像绝对路径名,则选择Unix域套接字连接;否则启动TCP/IP连接。但是,斜杠是URI层次结构部分中的保留字符。因此,要指定非标准的Unix域套接字目录,可以省略URI的主机部分并将host指定为命名参数,或者对URI主机部分中的路径进行百分号编码:
postgresql:///dbname?host=/var/lib/postgresql
postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
可以在单个URI中指定多个主机组件,每个组件可以包含可选的端口组件。形式为postgresql://host1:port1,host2:port2,host3:port3/的URI等效于形式为host=host1,host2,host3 port=port1,port2,port3的连接字符串。如下所述,将依次尝试每个主机,直到成功建立连接。
32.1.1.3. 指定多个主机 # 可以指定多个要连接的主机,按给定顺序尝试。在关键字/值格式中,host、hostaddr和port选项接受逗号分隔的值列表。指定的每个选项必须具有相同数量的元素,例如第一个hostaddr对应第一个主机名,第二个hostaddr对应第二个主机名,依此类推。例外情况是,如果只指定了一个端口,则该端口适用于所有主机。在连接URI格式中,可以在URI的主机部分列出多个用逗号分隔的host:port对。在任何一种格式中,单个主机名可以转换为多个网络地址,常见的例子是主机同时具有IPv4和IPv6地址。当指定多个主机,或者单个主机名转换为多个地址时,将按顺序尝试所有主机和地址,直到成功。如果无法联系到任何主机,则连接失败。如果连接成功建立但身份验证失败,则不会尝试列表中的剩余主机。如果使用密码文件,可以为不同的主机设置不同的密码。列表中的所有其他连接选项对于每个主机都是相同的;例如,无法为不同的主机指定不同的用户名。
PGconn模式2: 32.1.1. 连接字符串 # 多个libpq函数解析用户指定的字符串以获取连接参数。这些字符串有两种接受的格式:普通关键字/值字符串和URI。URI通常遵循RFC 3986,但允许多主机连接字符串,如下所述。
32.1.1.1. 关键字/值连接字符串 # 在关键字/值格式中,每个参数设置的形式为keyword = value,设置之间用空格分隔。设置的等号两侧的空格是可选的。要写入空值或包含空格的值,请用单引号括起来,例如keyword = 'a value'。值中的单引号和反斜杠必须用反斜杠转义,即'和\。示例:host=localhost port=5432 dbname=mydb connect_timeout=10。已识别的参数关键字请参见32.1.2节。
32.1.1.2. 连接URI # 连接URI的一般形式为:
postgresql://[userspec@][hostspec][/dbname][?paramspec]
其中userspec为:
user[:password]
hostspec为:
[host][:port][,...]
paramspec为:
name=value[&...]
URI方案指示符可以是postgresql://或postgres://。其余的URI部分都是可选的。以下示例展示了有效的URI语法:
postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp
通常出现在URI层次结构部分的值也可以作为命名参数给出。例如:
postgresql:///mydb?host=localhost&port=5433
所有命名参数必须与32.1.2节中列出的关键字匹配,除了为了与JDBC连接URI兼容,ssl=true将被转换为sslmode=require。如果连接URI包含其任何部分中具有特殊含义的符号,则需要进行百分号编码。以下示例中,等号(=)替换为%3D,空格字符替换为%20:
postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
主机部分可以是主机名或IP地址。要指定IPv6地址,请将其括在方括号中:
postgresql://[2001:db8::1234]/database
主机部分的解释与host参数的描述相同。特别是,如果主机部分为空或看起来像绝对路径名,则选择Unix域套接字连接;否则启动TCP/IP连接。但是,斜杠是URI层次结构部分中的保留字符。因此,要指定非标准的Unix域套接字目录,可以省略URI的主机部分并将host指定为命名参数,或者对URI主机部分中的路径进行百分号编码:
postgresql:///dbname?host=/var/lib/postgresql
postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
可以在单个URI中指定多个主机组件,每个组件可以包含可选的端口组件。形式为postgresql://host1:port1,host2:port2,host3:port3/的URI等效于形式为host=host1,host2,host3 port=port1,port2,port3的连接字符串。如下所述,将依次尝试每个主机,直到成功建立连接。
32.1.1.3. 指定多个主机 # 可以指定多个要连接的主机,按给定顺序尝试。在关键字/值格式中,host、hostaddr和port选项接受逗号分隔的值列表。指定的每个选项必须具有相同数量的元素,例如第一个hostaddr对应第一个主机名,第二个hostaddr对应第二个主机名,依此类推。例外情况是,如果只指定了一个端口,则该端口适用于所有主机。在连接URI格式中,可以在URI的主机部分列出多个用逗号分隔的host:port对。在任何一种格式中,单个主机名可以转换为多个网络地址,常见的例子是主机同时具有IPv4和IPv6地址。当指定多个主机,或者单个主机名转换为多个地址时,将按顺序尝试所有主机和地址,直到成功。如果无法联系到任何主机,则连接失败。如果连接成功建立但身份验证失败,则不会尝试列表中的剩余主机。如果使用密码文件,可以为不同的主机设置不同的密码。列表中的所有其他连接选项对于每个主机都是相同的;例如,无法为不同的主机指定不同的用户名。
keyword模式3: 示例:
host=localhost port=5432 dbname=mydb connect_timeout=10模式4: 32.1.1.2. 连接URI # 连接URI的一般形式为:
postgresql://[userspec@][hostspec][/dbname][?paramspec]
其中userspec为:
user[:password]
hostspec为:
[host][:port][,...]
paramspec为:
name=value[&...]
URI方案指示符可以是postgresql://或postgres://。其余的URI部分都是可选的。以下示例展示了有效的URI语法:
postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp
通常出现在URI层次结构部分的值也可以作为命名参数给出。例如:
postgresql:///mydb?host=localhost&port=5433
所有命名参数必须与32.1.2节中列出的关键字匹配,除了为了与JDBC连接URI兼容,ssl=true将被转换为sslmode=require。如果连接URI包含其任何部分中具有特殊含义的符号,则需要进行百分号编码。以下示例中,等号(=)替换为%3D,空格字符替换为%20:
postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
主机部分可以是主机名或IP地址。要指定IPv6地址,请将其括在方括号中:
postgresql://[2001:db8::1234]/database
主机部分的解释与host参数的描述相同。特别是,如果主机部分为空或看起来像绝对路径名,则选择Unix域套接字连接;否则启动TCP/IP连接。但是,斜杠是URI层次结构部分中的保留字符。因此,要指定非标准的Unix域套接字目录,可以省略URI的主机部分并将host指定为命名参数,或者对URI主机部分中的路径进行百分号编码:
postgresql:///dbname?host=/var/lib/postgresql
postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
可以在单个URI中指定多个主机组件,每个组件可以包含可选的端口组件。形式为postgresql://host1:port1,host2:port2,host3:port3/的URI等效于形式为host=host1,host2,host3 port=port1,port2,port3的连接字符串。如下所述,将依次尝试每个主机,直到成功建立连接。
postgresql://[userspec@][hostspec][/dbname][?paramspec]
where userspec is:
user[:password]
and hostspec is:
[host][:port][,...]
and paramspec is:
name=value[&...]模式5: 21.5. 预定义角色 # PostgreSQL提供了一组预定义角色,这些角色提供对某些常用特权功能和信息的访问权限。管理员(包括具有CREATEROLE特权的角色)可以将这些角色授予用户和/或其他角色,为这些用户提供对指定功能和信息的访问权限。例如:
GRANT pg_signal_backend TO admin_user;
警告:授予这些角色时应谨慎,确保仅在需要时使用,并了解这些角色授予对特权信息的访问权限。
以下描述预定义角色。请注意,每个角色的具体权限可能会在未来随着新增功能而变化,管理员应关注发行说明中的更改。
pg_checkpoint # pg_checkpoint允许执行CHECKPOINT命令。
pg_create_subscription # pg_create_subscription允许对数据库具有CREATE权限的用户执行CREATE SUBSCRIPTION。
pg_database_owner # pg_database_owner始终有一个隐式成员:当前数据库所有者。它不能被授予任何角色的成员资格,也不能将任何角色授予pg_database_owner的成员资格。但是,与任何其他角色一样,它可以拥有对象并接收访问特权的授予。因此,一旦pg_database_owner在模板数据库中拥有权限,从该模板实例化的每个数据库的所有者都将拥有这些权限。最初,该角色拥有public模式,因此每个数据库所有者都可以管理该模式的本地使用。
pg_maintain # pg_maintain允许对所有关系执行VACUUM、ANALYZE、CLUSTER、REFRESH MATERIALIZED VIEW、REINDEX和LOCK TABLE,就像对这些对象具有MAINTAIN权限一样。
pg_monitor、pg_read_all_settings、pg_read_all_stats、pg_stat_scan_tables # 这些角色旨在允许管理员轻松配置用于监控数据库服务器的角色。它们授予一组常见特权,允许角色读取通常仅限超级用户访问的各种有用配置设置、统计信息和其他系统信息。pg_monitor允许读取/执行各种监控视图和函数,该角色是pg_read_all_settings、pg_read_all_stats和pg_stat_scan_tables的成员。pg_read_all_settings允许读取所有配置变量,即使是通常仅超级用户可见的变量。pg_read_all_stats允许读取所有pg_stat_*视图并使用各种与统计相关的扩展,即使是通常仅超级用户可见的内容。pg_stat_scan_tables允许执行可能对表持有ACCESS SHARE锁的监控函数,可能会长时间持有(例如pgrowlocks扩展中的pgrowlocks(text))。
pg_read_all_data、pg_write_all_data # pg_read_all_data允许读取所有数据(表、视图、序列),就像对这些对象具有SELECT权限并对所有模式具有USAGE权限一样。该角色不会绕过行级安全性(RLS)策略。如果使用RLS,管理员可能希望对被授予该角色的角色设置BYPASSRLS。pg_write_all_data允许写入所有数据(表、视图、序列),就像对这些对象具有INSERT、UPDATE和DELETE权限并对所有模式具有USAGE权限一样。该角色不会绕过行级安全性(RLS)策略。如果使用RLS,管理员可能希望对被授予该角色的角色设置BYPASSRLS。
pg_read_server_files、pg_write_server_files、pg_execute_server_program # 这些角色旨在允许管理员拥有受信任但非超级用户的角色,这些角色能够以数据库运行的用户身份访问数据库服务器上的文件并运行程序。它们在直接访问文件时绕过所有数据库级别的权限检查,可用于获取超级用户级别的访问权限。因此,授予这些角色给用户时应格外小心。pg_read_server_files允许使用COPY和其他文件访问函数读取数据库在服务器上可访问的任何位置的文件。pg_write_server_files允许使用COPY和其他文件访问函数写入数据库在服务器上可访问的任何位置的文件。pg_execute_server_program允许使用COPY和其他函数以数据库运行的用户身份在数据库服务器上执行程序。
pg_signal_autovacuum_worker # pg_signal_autovacuum_worker允许向autovacuum工作进程发送信号以取消当前表的清理或终止其会话。请参见9.28.2节。
pg_signal_backend # pg_signal_backend允许向另一个后端发送信号以取消查询或终止其会话。请注意,该角色不允许向超级用户拥有的后端发送信号。请参见9.28.2节。
pg_use_reserved_connections # pg_use_reserved_connections允许使用通过reserved_connections保留的连接插槽。
CREATEROLE模式6: 6.4. 从修改的行返回数据 # 有时在操作行时获取修改后的数据是有用的。INSERT、UPDATE、DELETE和MERGE命令都有一个可选的RETURNING子句来支持此功能。使用RETURNING避免了执行额外的数据库查询来收集数据,尤其是在难以可靠识别修改的行时非常有价值。
RETURNING子句的允许内容与SELECT命令的输出列表相同(请参见7.3节)。它可以包含命令目标表的列名,或使用这些列的值表达式。常见的简写是RETURNING *,按顺序选择目标表的所有列。
在INSERT中,RETURNING可用的默认数据是插入后的行。在简单插入中这并不太有用,因为它只是重复客户端提供的数据。但在依赖计算默认值时非常有用。例如,当使用serial列提供唯一标识符时,RETURNING可以返回分配给新行的ID:
CREATE TABLE users (firstname text, lastname text, id serial primary key);
INSERT INTO users (firstname, lastname) VALUES ('Joe', 'Cool') RETURNING id;
RETURNING子句在INSERT ... SELECT中也非常有用。
在UPDATE中,RETURNING可用的默认数据是修改后行的新内容。例如:
UPDATE products SET price = price * 1.10 WHERE price <= 99.99 RETURNING name, price AS new_price;
在DELETE中,RETURNING可用的默认数据是被删除行的内容。例如:
DELETE FROM products WHERE obsoletion_date = 'today' RETURNING *;
在MERGE中,RETURNING可用的默认数据是源行的内容加上插入、更新或删除的目标行的内容。由于源和目标通常有许多相同的列,指定RETURNING 会导致大量重复列,因此通常更有用的是限定它以仅返回源行或目标行。例如:
MERGE INTO products p USING new_products n ON p.product_no = n.product_no
WHEN NOT MATCHED THEN INSERT VALUES (n.product_no, n.name, n.price)
WHEN MATCHED THEN UPDATE SET name = n.name, price = n.price
RETURNING p.;
在每个这些命令中,还可以显式返回修改行的旧内容和新内容。例如:
UPDATE products SET price = price * 1.10 WHERE price <= 99.99
RETURNING name, old.price AS old_price, new.price AS new_price, new.price - old.price AS price_change;
在此示例中,new.price与直接写price相同,但含义更清晰。这种返回旧值和新值的语法在INSERT、UPDATE、DELETE和MERGE命令中都可用,但通常INSERT的旧值为NULL,DELETE的新值为NULL。然而,在某些情况下,这些命令仍然可以使用此语法。例如,在带有ON CONFLICT DO UPDATE子句的INSERT中,冲突行的旧值将非NULL。同样,如果DELETE被重写规则转换为UPDATE,则新值可能非NULL。
如果目标表上有触发器(第37章),则RETURNING可用的数据是被触发器修改后的行。因此,检查触发器计算的列是RETURNING的另一个常见用例。
INSERT模式7: 在UPDATE中,RETURNING可用的默认数据是修改后行的新内容。例如:
UPDATE模式8: 在DELETE中,RETURNING可用的默认数据是被删除行的内容。例如:
DELETEExample Code Patterns
代码示例模式
Example 1 (javascript):
javascript
PGconn *PQconnectdbParams(const char * const *keywords,
const char * const *values,
int expand_dbname);Example 2 (javascript):
javascript
PGconn *PQconnectdb(const char *conninfo);示例1 (javascript):
javascript
PGconn *PQconnectdbParams(const char * const *keywords,
const char * const *values,
int expand_dbname);示例2 (javascript):
javascript
PGconn *PQconnectdb(const char *conninfo);Reference Files
参考文件
This skill includes comprehensive documentation in :
references/- getting_started.md - Getting Started documentation
- sql.md - Sql documentation
Use to read specific reference files when detailed information is needed.
view本技能在目录中包含全面的文档:
references/- getting_started.md - 入门文档
- sql.md - SQL文档
需要详细信息时,使用命令读取特定的参考文件。
viewWorking with This Skill
使用本技能的指南
For Beginners
面向初学者
Start with the getting_started or tutorials reference files for foundational concepts.
从入门或教程参考文件开始,学习基础概念。
For Specific Features
面向特定功能
Use the appropriate category reference file (api, guides, etc.) for detailed information.
使用相应的类别参考文件(如api、指南等)获取详细信息。
For Code Examples
面向代码示例
The quick reference section above contains common patterns extracted from the official docs.
上面的快速参考部分包含从官方文档中提取的常见模式。
Resources
资源
references/
references/
Organized documentation extracted from official sources. These files contain:
- Detailed explanations
- Code examples with language annotations
- Links to original documentation
- Table of contents for quick navigation
从官方来源提取的结构化文档,包含:
- 详细解释
- 带语言注释的代码示例
- 指向原始文档的链接
- 用于快速导航的目录
scripts/
scripts/
Add helper scripts here for common automation tasks.
在此处添加用于常见自动化任务的辅助脚本。
assets/
assets/
Add templates, boilerplate, or example projects here.
在此处添加模板、样板代码或示例项目。
Notes
说明
- This skill was automatically generated from official documentation
- Reference files preserve the structure and examples from source docs
- Code examples include language detection for better syntax highlighting
- Quick reference patterns are extracted from common usage examples in the docs
- 本技能由官方文档自动生成
- 参考文件保留了源文档的结构和示例
- 代码示例包含语言检测以实现更好的语法高亮
- 快速参考模式从文档中的常见使用示例中提取
Updating
更新方法
To refresh this skill with updated documentation:
- Re-run the scraper with the same configuration
- The skill will be rebuilt with the latest information
要使用更新后的文档刷新本技能:
- 使用相同的配置重新运行抓取工具
- 技能将使用最新信息重建