postgresql by 2025emma/vibe-coding-cn
npx skills add https://github.com/2025emma/vibe-coding-cn --skill postgresql基于官方文档生成的 PostgreSQL 开发综合辅助工具。
在以下情况时应触发此技能:
模式 1: 32.1. 数据库连接控制函数 # 32.1.1. 连接字符串 32.1.2. 参数关键字 以下函数用于建立到 PostgreSQL 后端服务器的连接。一个应用程序可以同时打开多个后端连接。(这样做的一个原因是访问多个数据库。)每个连接由一个 PGconn 对象表示,该对象从函数 PQconnectdb、PQconnectdbParams 或 PQsetdbLogin 获取。请注意,除非可能因为内存太少而无法分配 PGconn 对象,否则这些函数将始终返回一个非空的对象指针。在通过连接对象发送查询之前,应调用 PQstatus 函数来检查返回值以确保连接成功。警告 如果不受信任的用户可以访问未采用安全模式使用模式的数据库,请在每次会话开始时从 search_path 中移除公共可写模式。可以将参数关键字选项设置为值 。或者,可以在连接后执行 。这种考虑并非 特有;它适用于执行任意 SQL 命令的每个接口。警告 在 Unix 上,使用打开的 连接 fork 进程可能导致不可预测的结果,因为父进程和子进程共享相同的套接字和操作系统资源。因此,不推荐这种用法,尽管从子进程执行 来加载新的可执行文件是安全的。 # 建立到数据库服务器的新连接。 此函数使用从两个以 NULL 结尾的数组中获取的参数打开一个新的数据库连接。第一个数组 定义为字符串数组,每个字符串是一个关键字。第二个数组 给出每个关键字的值。与下面的 不同,参数集可以在不更改函数签名的情况下进行扩展,因此对于新的应用程序编程,建议使用此函数(或其非阻塞的类似函数 和 )。当前识别的参数关键字列在第 32.1.2 节中。传递的数组可以为空以使用所有默认参数,也可以包含一个或多个参数设置。它们的长度必须匹配。处理将在 数组中的第一个 NULL 条目处停止。此外,如果与非 NULL 条目关联的 条目为 NULL 或空字符串,则该条目将被忽略,处理将继续进行下一对数组条目。当 非零时,将检查第一个 关键字的值,看它是否是连接字符串。如果是,它将被“扩展”为从字符串中提取的各个连接参数。如果值包含等号()或以 URI 方案指示符开头,则它被视为连接字符串,而不仅仅是数据库名称。(有关连接字符串格式的更多详细信息,请参见第 32.1.1 节。)只有第一次出现的 会以这种方式处理;任何后续的 参数都将作为普通数据库名称处理。通常,参数数组从头到尾处理。如果任何关键字重复,则使用最后一个值(即不为 NULL 或空的值)。当连接字符串中找到的关键字与 数组中出现的某个关键字冲突时,此规则尤其适用。因此,程序员可以确定数组条目是否可以覆盖或被连接字符串中的值覆盖。出现在扩展的 条目之前的数组条目可以被连接字符串的字段覆盖,而这些字段又可以被出现在 之后的数组条目覆盖(但再次强调,仅当这些条目提供非空值时)。在处理完所有数组条目和任何扩展的连接字符串后,任何仍未设置的连接参数都将使用默认值填充。如果未设置参数对应的环境变量(参见第 32.15 节)已设置,则使用其值。如果环境变量也未设置,则使用参数的内置默认值。 # 建立到数据库服务器的新连接。 此函数使用从字符串 中获取的参数打开一个新的数据库连接。传递的字符串可以为空以使用所有默认参数,也可以包含一个或多个由空格分隔的参数设置,或者可以包含一个 URI。有关详细信息,请参见第 32.1.1 节。 # 建立到数据库服务器的新连接。 这是 的前身,具有一组固定的参数。它具有相同的功能,只是缺少的参数将始终采用默认值。对于任何要使用默认值的固定参数,请写入 或空字符串。如果 包含等号()或具有有效的连接 URI 前缀,则它将被视为 字符串,其处理方式与传递给 时完全相同,然后剩余的参数将按照为 指定的方式应用。 不再使用,传递的任何值都将被忽略。 # 建立到数据库服务器的新连接。 这是一个宏,它使用 指针作为 和 参数调用 。它提供是为了与非常古老的程序保持向后兼容。 # 以非阻塞方式建立到数据库服务器的连接。 这三个函数用于打开到数据库服务器的连接,使得应用程序的执行线程在执行此操作时不会在远程 I/O 上阻塞。这种方法的关键在于,等待 I/O 完成的操作可以发生在应用程序的主循环中,而不是在 或 内部,因此应用程序可以与其他活动并行管理此操作。使用 时,使用从 和 数组中获取的参数建立数据库连接,并由 控制,如上文 所述。使用 时,使用从字符串 中获取的参数建立数据库连接,如上文 所述。只要满足一些限制,、 和 都不会阻塞:必须适当使用 参数以防止进行 DNS 查询。有关详细信息,请参见第 32.1.2 节中此参数的文档。如果调用 ,请确保用于跟踪的流对象不会阻塞。必须在调用 之前确保套接字处于适当的状态,如下所述。要开始非阻塞连接请求,请调用 或 。如果结果为 ,则 无法分配新的 结构。否则,返回一个有效的 指针(尽管尚未表示与数据库的有效连接)。接下来调用 。如果结果为 ,则连接尝试已经失败,通常是由于无效的连接参数。如果 或 成功,下一阶段是轮询 ,以便它可以继续进行连接序列。使用 获取底层数据库连接的套接字描述符。(注意:不要假设套接字在 调用之间保持不变。)按如下方式循环:如果 上次返回 ,则等待套接字准备好读取(由 、 或类似的系统函数指示)。请注意,如果您的系统上可用, 可以通过抽象 或 的设置来帮助减少样板代码。然后再次调用 。相反,如果 上次返回 ,则等待套接字准备好写入,然后再次调用 。在第一次迭代时,即如果您尚未调用 ,则表现得好像它上次返回了 。继续此循环,直到 返回 (表示连接过程失败)或 (表示连接已成功建立)。在连接期间的任何时间,都可以通过调用 来检查连接状态。如果此调用返回 ,则连接过程失败;如果调用返回 ,则连接已就绪。这两种状态都可以从上述 的返回值中同等检测到。在(且仅在)异步连接过程中,也可能出现其他状态。这些状态指示连接过程的当前阶段,可能有助于向用户提供反馈,例如。这些状态是: # 等待建立连接。 # 连接正常;等待发送。 # 等待服务器响应。 # 已收到认证;等待后端启动完成。 # 协商 SSL 加密。 # 协商 GSS 加密。 # 检查连接是否能够处理写事务。 # 检查连接是否处于备用模式的服务器。 # 消费连接上任何剩余的响应消息。请注意,尽管这些常量将保留(以保持兼容性),但应用程序绝不应依赖这些状态以特定顺序出现、或根本出现、或状态始终是这些文档化的值之一。应用程序可能会执行类似这样的操作: 使用 时, 连接参数将被忽略;由应用程序决定是否已过去过多时间。否则, 后跟 循环等同于 。请注意,当 或 返回非空指针时,您必须在完成后调用 ,以释放该结构和任何关联的内存块。即使连接尝试失败或被放弃,也必须这样做。 # 轮询通过 检索到的连接底层套接字描述符。此函数的主要用途是遍历 文档中描述的连接序列。 此函数执行文件描述符的轮询,可选择带有超时。如果 非零,则当套接字准备好读取时,函数将终止。如果 非零,则当套接字准备好写入时,函数将终止。超时由 指定,它是停止等待的时间,表示为自 Unix 纪元以来的微秒数(即 乘以 100 万)。如果 为 ,则超时为无限。如果 为 (或实际上,任何早于现在的时间),则超时立即(无阻塞)。可以通过将所需的微秒数加到 的结果上来方便地计算超时值。请注意,底层系统调用的精度可能低于微秒,因此实际延迟可能不精确。如果满足指定条件,则函数返回值大于 ;如果发生超时,则返回 ;如果发生错误,则返回 。可以通过检查 值来检索错误。如果 和 都为零,则函数立即返回超时指示。 使用 或 实现,具体取决于平台。有关更多信息,请参见 中的 和 ,或 中的 和 。 # 返回默认连接选项。 返回一个连接选项数组。这可用于确定所有可能的 选项及其当前默认值。返回值指向一个 结构数组,该数组以一个具有空关键字指针的条目结束。如果无法分配内存,则返回空指针。请注意,当前默认值( 字段)将取决于环境变量和其他上下文。缺少或无效的服务文件将被静默忽略。调用者必须将连接选项数据视为只读。处理完选项数组后,通过将其传递给 来释放它。如果不这样做,每次调用 都会泄漏少量内存。 # 返回活动连接使用的连接选项。 返回一个连接选项数组。这可用于确定所有可能的 选项以及用于连接到服务器的值。返回值指向一个 结构数组,该数组以一个具有空关键字指针的条目结束。上述 的所有说明也适用于 的结果。 # 从提供的连接字符串返回解析后的连接选项。 解析连接字符串并将结果选项作为数组返回;如果连接字符串有问题,则返回 。此函数可用于提取提供的连接字符串中的 选项。返回值指向一个 结构数组,该数组以一个具有空关键字指针的条目结束。所有合法选项都将出现在结果数组中,但连接字符串中不存在的任何选项的 的 将设置为 ;不会插入默认值。如果 不为 ,则在成功时 设置为 ,否则设置为一个 分配的错误字符串来解释问题。(也可能 设置为 且函数返回 ;这表示内存不足的情况。)处理完选项数组后,通过将其传递给 来释放它。如果不这样做,每次调用 都会泄漏一些内存。相反,如果发生错误且 不为 ,请务必使用 释放错误字符串。 # 关闭与服务器的连接。同时释放 对象使用的内存。 请注意,即使服务器连接尝试失败(由 指示),应用程序也应调用 以释放 对象使用的内存。调用 后,不得再次使用 指针。 # 重置与服务器的通信通道。 此函数将关闭与服务器的连接,并尝试使用之前使用的所有相同参数建立新连接。如果工作连接丢失,这可能对错误恢复有用。 # 以非阻塞方式重置与服务器的通信通道。 这些函数将关闭与服务器的连接,并尝试使用之前使用的所有相同参数建立新连接。如果工作连接丢失,这可能对错误恢复有用。它们与上面的 的不同之处在于它们以非阻塞方式运行。这些函数受到与 、 和 相同的限制。要启动连接重置,请调用 。如果返回 ,则重置失败。如果返回 ,则使用 轮询重置,其方式与使用 创建连接的方式完全相同。 # 报告服务器的状态。它接受与上述 相同的连接参数。无需提供正确的用户名、密码或数据库名称值即可获取服务器状态;但是,如果提供了不正确的值,服务器将记录一次失败的连接尝试。 该函数返回以下值之一: # 服务器正在运行并且似乎正在接受连接。 # 服务器正在运行但处于不允许连接的状态(启动、关闭或崩溃恢复)。 # 无法联系到服务器。这可能表示服务器未运行,或者给定的连接参数有问题(例如,端口号错误),或者存在网络连接问题(例如,防火墙阻止了连接请求)。 # 未尝试联系服务器,因为提供的参数明显不正确或存在某些客户端问题(例如,内存不足)。 # 报告服务器的状态。它接受与上述 相同的连接参数。无需提供正确的用户名、密码或数据库名称值即可获取服务器状态;但是,如果提供了不正确的值,服务器将记录一次失败的连接尝试。 返回值与 相同。 # 允许应用程序使用 或交互式提示来覆盖 对加密客户端证书密钥文件的默认处理。 应用程序传递一个指向具有以下签名的回调函数的指针: 然后 将调用此回调函数,而不是其默认的 处理程序。回调应确定密钥的密码并将其复制到大小为 的结果缓冲区 中。 中的字符串必须以 null 结尾。回调必须返回存储在 中的密码长度(不包括 null 终止符)。失败时,回调应设置 并返回 。有关示例,请参见 源代码中的 。如果用户指定了明确的密钥位置,则在调用回调时,其路径将在 中。如果使用默认密钥路径,则此路径为空。对于作为引擎说明符的密钥,是否使用 OpenSSL 密码回调或定义自己的处理取决于引擎实现。应用程序回调可以选择将未处理的案例委托给 ,或者先调用它,如果它返回 则尝试其他方法,或者完全覆盖它。回调不得通过异常、 等逃脱正常流程控制。它必须正常返回。 # 返回当前的客户端证书密钥密码钩子,如果未设置,则返回 。 32.1.1. 连接字符串 # 几个 函数解析用户指定的字符串以获取连接参数。这些字符串有两种可接受的格式:纯关键字/值字符串和 URI。URI 通常遵循 RFC 3986,但允许使用多主机连接字符串,如下文进一步描述。32.1.1.1. 关键字/值连接字符串 # 在关键字/值格式中,每个参数设置的形式为 ,设置之间用空格分隔。设置等号周围的空格是可选的。要写入空值或包含空格的值,请用单引号将其括起来,例如 。值内的单引号和反斜杠必须用反斜杠转义,即 和 。示例: 识别的参数关键字列在第 32.1.2 节中。32.1.1.2. 连接 URI # 连接 URI 的一般形式是: 其中 是: 而 是: 而 是: URI 方案指示符可以是 或 。其余每个 URI 部分都是可选的。以下示例说明了有效的 URI 语法: 通常出现在 URI 层次结构部分的值也可以作为命名参数给出。例如: 所有命名参数必须匹配第 32.1.2 节中列出的关键字,但为了与 JDBC 连接 URI 兼容, 的实例会被转换为 。如果连接 URI 在其任何部分中包含具有特殊含义的符号,则需要使用百分号编码进行编码。以下是一个示例,其中等号()被替换为 ,空格字符被替换为 : 主机部分可以是主机名或 IP 地址。要指定 IPv6 地址,请将其括在方括号中: 主机部分的解释如参数 所述。特别是,如果主机部分为空或看起来像绝对路径名,则选择 Unix 域套接字连接,否则启动 TCP/IP 连接。但请注意,斜杠是 URI 层次结构部分中的保留字符。因此,要指定非标准的 Unix 域套接字目录,要么省略 URI 的主机部分并将主机指定为命名参数,要么对 URI 主机部分中的路径进行百分号编码: 可以在单个 URI 中指定多个主机组件,每个组件带有可选的端口组件。形式为 的 URI 等同于形式为 的连接字符串。如下文进一步描述,将依次尝试每个主机,直到成功建立连接。32.1.1.3. 指定多个主机 # 可以指定要连接的多个主机,以便按给定顺序尝试它们。在关键字/值格式中,、 和 选项接受逗号分隔的值列表。每个指定的选项中必须给出相同数量的元素,例如,第一个 对应于第一个主机名,第二个 对应于第二个主机名,依此类推。作为例外,如果只指定了一个端口,则它适用于所有主机。在连接 URI 格式中,您可以在 URI 的主机组件中列出多个由逗号分隔的 对。在任一格式中,单个主机名可以解析为多个网络地址。一个常见的例子是同时具有 IPv4 和 IPv6 地址的主机。当指定了多个主机,或者单个主机名被解析为多个地址时,将按顺序尝试所有主机和地址,直到一个成功。如果无法联系到任何主机,则连接失败。如果成功建立了连接,但认证失败,则不会尝试列表中的其余主机。如果使用密码文件,您可以为不同的主机设置不同的密码。列表中所有主机的所有其他连接选项都相同;不可能为不同的主机指定不同的用户名,例如。32.1.2. 参数关键字 # 当前识别的参数关键字是: # 要连接的主机名。如果主机名看起来像绝对路径名,则指定 Unix 域通信而不是 TCP/IP 通信;该值是套接字文件所在目录的名称。(在 Unix 上,绝对路径名以斜杠开头。在 Windows 上,以驱动器号开头的路径也被识别。)如果主机名以 开头,则它被视为抽象命名空间中的 Unix 域套接字(当前在 Linux 和 Windows 上受支持)。未指定 或为空时的默认行为是连接到 中的 Unix 域套接字(或构建 PostgreSQL 时指定的任何套接字目录)。在 Windows 上,默认是连接到 。也接受逗号分隔的主机名列表,在这种情况下,将按顺序尝试列表中的每个主机名;列表中的空项选择上述解释的默认行为。有关详细信息,请参见第 32.1.1.3 节。 # 要连接的主机的数字 IP 地址。这应采用标准的 IPv4 地址格式,例如 。如果您的机器支持 IPv6,您也可以使用这些地址。为此参数指定非空字符串时,始终使用 TCP/IP 通信。如果未指定此参数,将查找 的值以找到相应的 IP 地址——或者,如果 指定了 IP 地址,则将直接使用该值。使用 允许应用程序避免主机名查找,这在有时间限制的应用程序中可能很重要。但是,对于 GSSAPI 或 SSPI 认证方法,以及用于 SSL 证书验证,需要主机名。使用以下规则:如果指定了 而未指定 ,则进行主机名查找。(使用 时,当 首次考虑此主机名时进行查找,这可能导致 阻塞相当长的时间。)如果指定了 而未指定 ,则 的值给出服务器网络地址。如果认证方法需要主机名,则连接尝试将失败。如果同时指定了 和 ,则 的值给出服务器网络地址。除非认证方法需要,否则将忽略 的值,在这种情况下,它将用作主机名。请注意,如果 不是网络地址 处的服务器名称,则认证可能会失败。此外,当同时指定 和 时, 用于在密码文件中标识连接(参见第 32.16 节)。也接受逗号分隔的 值列表,在这种情况下,将按顺序尝试列表中的每个主机。列表中的空项导致使用相应的主机名,或者如果该主机名也为空,则使用默认主机名。有关详细信息,请参见第 32.1.1.3 节。如果没有主机名或主机地址, 将使用本地 Unix 域套接字进行连接;或者在 Windows 上,它将尝试连接到 。 # 服务器主机上要连接的端口号,或 Unix 域连接的套接字文件名扩展名。如果在 或 参数中给出了多个主机,则此参数可以指定一个与主机列表长度相同的逗号分隔的端口列表,或者可以指定一个用于所有主机的单个端口号。空字符串或逗号分隔列表中的空项指定构建 PostgreSQL 时建立的默认端口号。 # 数据库名称。默认为与用户名相同。在某些上下文中,会检查该值以获取扩展格式;有关这些的更多详细信息,请参见第 32.1.1 节。 # 要连接的 PostgreSQL 用户名。默认为运行应用程序的操作系统用户的名称。 # 如果服务器要求密码认证,则使用的密码。 # 指定用于存储密码的文件名(参见第 32.16 节)。默认为 ,或在 Microsoft Windows 上为 。(如果此文件不存在,则不会报告错误。) # 指定客户端要求服务器使用的认证方法。如果服务器未使用所需的方法对客户端进行认证,或者服务器未完全完成认证握手,则连接将失败。也可以提供逗号分隔的方法列表,服务器必须恰好使用其中一种方法才能使连接成功。默认情况下,接受任何认证方法,并且服务器可以完全跳过认证。可以通过添加 前缀来否定方法,在这种情况下,服务器不得尝试列出的方法;接受任何其他方法,并且服务器可以自由选择不对客户端进行认证。如果提供了逗号分隔的列表,则服务器不得尝试任何列出的否定方法。否定和非否定形式不能在同一设置中组合。作为最后的特殊情况, 方法要求服务器不使用认证质询。(它也可以被否定,以要求某种形式的认证。)可以指定以下方法: 服务器必须请求明文密码认证。 服务器必须请求 MD5 哈希密码认证。警告 对 MD5 加密密码的支持已弃用,并将在 PostgreSQL 的未来版本中移除。有关迁移到其他密码类型的详细信息,请参见第 20.5 节。 服务器必须通过 GSSAPI 请求 Kerberos 握手或建立 GSS 加密通道(另请参见 )。 服务器必须请求 Windows SSPI 认证。 服务器必须与客户端成功完成 SCRAM-SHA-256 认证交换。 服务器必须向客户端请求 OAuth 持有者令牌。 服务器不得提示客户端进行认证交换。(这不禁止通过 TLS 进行客户端证书认证,也不禁止通过其加密传输进行 GSS 认证。) # 此选项控制客户端对通道绑定的使用。设置为 意味着连接必须使用通道绑定, 意味着客户端将在可用时选择通道绑定,而 阻止使用通道绑定。如果 PostgreSQL 编译时启用了 SSL 支持,则默认值为 ;否则默认值为 。通道绑定是服务器向客户端认证自身的一种方法。仅在使用 SCRAM 认证方法的 PostgreSQL 11 或更高版本服务器的 SSL 连接上受支持。 # 连接时等待的最长时间,以秒为单位(写为十进制整数,例如 )。零、负数或未指定意味着无限期等待。此超时分别适用于每个主机名或 IP 地址。例如,如果您指定两个主机且 为 ,则如果未在 5 秒内建立连接,每个主机都将超时,因此等待连接的总时间可能长达 10 秒。 # 为此连接设置 配置参数。除了相应服务器选项接受的值外,您可以使用 从客户端当前区域设置(Unix 系统上的 环境变量)确定正确的编码。 # 指定在连接开始时发送到服务器的命令行选项。例如,将其设置为 或 将会话的 参数值设置为 。此字符串中的空格被视为分隔命令行参数,除非用反斜杠()转义;写入 表示字面反斜杠。有关可用选项的详细讨论,请参阅第 19 章。 # 为 配置参数指定一个值。 # 为 配置参数指定一个后备值。如果未通过连接参数或 环境变量为 提供值,则将使用此值。指定后备名称在希望设置默认应用程序名称但允许用户覆盖的通用实用程序中很有用。 # 控制是否使用客户端 TCP keepalive。默认值为 ,表示开启,但如果不希望 keepalive,可以将其更改为 ,表示关闭。对于通过 Unix 域套接字进行的连接,将忽略此参数。 # 控制 TCP 在多少秒不活动后应向服务器发送 keepalive 消息。值为 使用系统默认值。对于通过 Unix 域套接字进行的连接,或者如果 keepalive 被禁用,则忽略此参数。仅在支持 或等效套接字选项的系统以及 Windows 上受支持;在其他系统上,它无效。 # 控制 TCP 在多少秒后应重新传输服务器未确认的 keepalive 消息。值为 使用系统默认值。对于通过 Unix 域套接字进行的连接,或者如果 keepalive 被禁用,则忽略此参数。仅在支持 或等效套接字选项的系统以及 Windows 上受支持;在其他系统上,它无效。 # 控制客户端到服务器的连接在被视为死亡之前可以丢失的 TCP keepalive 数量。值为 使用系统默认值。对于通过 Unix 域套接字进行的连接,或者如果 keepalive 被禁用,则忽略此参数。仅在支持 或等效套接字选项的系统上受支持;在其他系统上,它无效。 # 控制传输的数据在连接被强制关闭之前可以保持未确认的毫秒数。值为 使用系统默认值。对于通过 Unix 域套接字进行的连接,将忽略此参数。仅在支持 的系统上可用;在其他系统上,它无效。 # 此选项确定连接是否应使用复制协议而不是普通协议。这是 PostgreSQL 复制连接以及 等工具内部使用的,但也可由第三方应用程序使用。有关复制协议的描述,请参阅第 54.4 节。支持以下不区分大小写的值:、、、 连接进入物理复制模式。 连接进入逻辑复制模式,连接到 参数中指定的数据库。、、、 连接是常规连接,这是默认行为。在物理或逻辑复制模式下,只能使用简单查询协议。 # 此选项确定是否以及以何种优先级与服务器协商安全的 GSS TCP/IP 连接。有三种模式: 仅尝试非 GSSAPI 加密连接。(默认)如果存在 GSSAPI 凭据(即,在凭据缓存中),则首先尝试 GSSAPI 加密连接;如果失败或没有凭据,则尝试非 GSSAPI 加密连接。当 PostgreSQL 编译时
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
-csearch_path=PQexec(conn, "SELECT pg_catalog.set_config('search_path', '', false)")libpqlibpqexecPQconnectdbParamsPGconn *PQconnectdbParams(const char * const *keywords, const char * const *values, int expand_dbname);keywordsvaluesPQsetdbLoginPQconnectStartParamsPQconnectPollkeywordskeywordsvaluesexpand_dbnamedbname=dbnamedbnamekeywordsdbnamedbnamePQconnectdbPGconn *PQconnectdb(const char *conninfo);conninfoPQsetdbLoginPGconn *PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd);PQconnectdbNULLdbName=conninfoPQconnectdbPQconnectdbParamspgttyPQsetdbPGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName);NULLloginpwdPQsetdbLoginPQconnectStartParamsPQconnectStartPQconnectPollPGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname);PGconn *PQconnectStart(const char *conninfo);PostgresPollingStatusType PQconnectPoll(PGconn *conn);PQconnectdbParamsPQconnectdbPQconnectStartParamskeywordsvaluesexpand_dbnamePQconnectdbParamsPQconnectStartconninfoPQconnectdbPQconnectStartParamsPQconnectStartPQconnectPollhostaddrPQtracePQconnectPollPQconnectStartPQconnectStartParamsnulllibpqPGconnPGconnPQstatus(conn)CONNECTION_BADPQconnectStartPQconnectStartParamslibpqPQsocket(conn)PQconnectPollPQconnectPoll(conn)PGRES_POLLING_READINGselect()poll()PQsocketPollselect(2)poll(2)PQconnectPoll(conn)PQconnectPoll(conn)PGRES_POLLING_WRITINGPQconnectPoll(conn)PQconnectPollPGRES_POLLING_WRITINGPQconnectPoll(conn)PGRES_POLLING_FAILEDPGRES_POLLING_OKPQstatusCONNECTION_BADCONNECTION_OKPQconnectPollCONNECTION_STARTEDCONNECTION_MADECONNECTION_AWAITING_RESPONSECONNECTION_AUTH_OKCONNECTION_SSL_STARTUPCONNECTION_GSS_STARTUPCONNECTION_CHECK_WRITABLECONNECTION_CHECK_STANDBYCONNECTION_CONSUMEswitch(PQstatus(conn)) { case CONNECTION_STARTED: feedback = "正在连接..."; break; case CONNECTION_MADE: feedback = "已连接到服务器..."; break; . . . default: feedback = "正在连接..."; }PQconnectPollconnect_timeoutPQconnectStartPQconnectPollPQconnectdbPQconnectStartPQconnectStartParamsPQfinishPQsocketPollPQsocketPQconnectStartParamstypedef int64_t pg_usec_time_t; int PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time);forReadforWriteend_timetime_tend_time-1end_time0PQgetCurrentTimeUSec00-1errno(3)forReadforWritePQsocketPollpoll(2)select(2)poll(2)POLLINPOLLOUTselect(2)readfdswritefdsPQconndefaultsPQconninfoOption *PQconndefaults(void);typedef struct { char *keyword; /* 选项的关键字 */ char *envvar; /* 后备环境变量名 */ char *compiled; /* 后备编译时默认值 */ char *val; /* 选项的当前值,或 NULL */ char *label; /* 连接对话框中字段的标签 */ char *dispchar; /* 指示如何在连接对话框中显示此字段。值为: "" 按原样显示输入值 "*" 密码字段 - 隐藏值 "D" 调试选项 - 默认不显示 */ int dispsize; /* 对话框中字段的大小(字符数) */ } PQconninfoOption;PQconnectdbPQconninfoOptionvalPQconninfoFreePQconndefaultsPQconninfoPQconninfoOption *PQconninfo(PGconn *conn);PQconnectdbPQconninfoOptionPQconndefaultsPQconninfoPQconninfoParsePQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);NULLPQconnectdbPQconninfoOptionPQconninfoOptionvalNULLerrmsgNULL*errmsgNULLmalloc*errmsgNULLNULLPQconninfoFreePQconninfoParseerrmsgNULLPQfreememPQfinishPGconnvoid PQfinish(PGconn *conn);PQstatusPQfinishPGconnPQfinishPGconnPQresetvoid PQreset(PGconn *conn);PQresetStartPQresetPollint PQresetStart(PGconn *conn);PostgresPollingStatusType PQresetPoll(PGconn *conn);PQresetPQconnectStartParamsPQconnectStartPQconnectPollPQresetStart01PQresetPollPQconnectPollPQpingParamsPQpingParamsPQconnectdbParamsPGPing PQpingParams(const char * const *keywords, const char * const *values, int expand_dbname);PQPING_OKPQPING_REJECTPQPING_NO_RESPONSEPQPING_NO_ATTEMPTPQpingPQpingPQconnectdbPGPing PQping(const char *conninfo);PQpingParamsPQsetSSLKeyPassHook_OpenSSLPQsetSSLKeyPassHook_OpenSSLsslpasswordlibpqvoid PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);int callback_fn(char *buf, int size, PGconn *conn);libpqPQdefaultSSLKeyPassHook_OpenSSLsizebufbufbufbuf[0] = '\0'0libpqPQdefaultSSLKeyPassHook_OpenSSLconn->sslkeyPQdefaultSSLKeyPassHook_OpenSSL0longjmp(...)PQgetSSLKeyPassHook_OpenSSLPQgetSSLKeyPassHook_OpenSSLNULLPQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);libpqkeyword = valuekeyword = 'a value'\'\\host=localhost port=5432 dbname=mydb connect_timeout=10postgresql://[userspec@][hostspec][/dbname][?paramspec]userspecuser[:password]hostspec[host][:port][,...]paramspecname=value[&...]postgresql://postgres://postgresql://postgresql://localhostpostgresql://localhost:5433postgresql://localhost/mydbpostgresql://user@localhostpostgresql://user:secret@localhostpostgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapppostgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapppostgresql:///mydb?host=localhost&port=5433ssl=truesslmode=require=%3D%20postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doffpostgresql://[2001:db8::1234]/databasehostpostgresql:///dbname?host=/var/lib/postgresqlpostgresql://%2Fvar%2Flib%2Fpostgresql/dbnamepostgresql://host1:port1,host2:port2,host3:port3/host=host1,host2,host3 port=port1,port2,port3hosthostaddrporthostaddrhostaddrhost:porthost@host/tmplocalhosthostaddr172.28.40.9hosthosthostaddrverify-fullhosthostaddrPQconnectPollPQconnectPollPQconnectPollhostaddrhosthostaddrhosthostaddrhostaddrhosthosthostaddrhosthostaddrhosthostaddrlibpqlocalhostporthosthostaddrdbnameuserpasswordpassfile~/.pgpass%APPDATA%\postgresql\pgpass.confrequire_auth!nonepasswordmd5gssgssencmodesspiscram-sha-256oauthnonechannel_bindingrequirepreferdisablepreferdisableconnect_timeout10connect_timeout5client_encodingclient_encodingautoLC_CTYPEoptions-c geqo=off--geqo=offgeqooff\\\application_nameapplication_namefallback_application_nameapplication_namePGAPPNAMEapplication_namekeepalives10keepalives_idle0TCP_KEEPIDLEkeepalives_interval0TCP_KEEPINTVLkeepalives_count0TCP_KEEPCNTtcp_user_timeout0TCP_USER_TIMEOUTreplicationpg_basebackuptrueonyes1databasedbnamefalseoffno0gssencmodedisablepreferComprehensive assistance with postgresql development, generated from official documentation.
This skill should be triggered when:
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.
PGconn
Pattern 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.
keyword
Pattern 3: Example:
host=localhost port=5432 dbname=mydb connect_timeout=10
Pattern 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
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
116,600 周安装