配置访问模式的顺序

最近更新时间: 2025-02-18 16:02:00

TDSQL PG数据库有一个运行变量叫search_path,其值为模式名列表,用于配置访问数据对象的顺序,如下所示:

  1. 当前连接用户。
  • 复制
    复制成功
postgres=# select current_user;
 current_user 
--------------
 tbase
(1 row)
  1. 总共三个模式。
  • 复制
    复制成功
postgres=# \dn
   List of schemas
     Name     | Owner 
--------------+-------
 public       | tbase
 tbase        | tbase
 tbase_schema | tbase
(3 rows)
  1. 搜索路径只配置为"$user", public,其中"$user"为当前用户名,即上面的current_user值“tbase”。
  • 复制
    复制成功
postgres=# show search_path ;
   search_path   
-----------------
 "$user", public
(1 row)
  1. 不指定模式创建数据表,则该表存放于第一个搜索模式下面。
  • 复制
    复制成功
postgres=# create table t(id int,mc text);
CREATE TABLE
postgres=# \dt
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 tbase  | t    | table | tbase
(1 row)
  1. 指定表位于某个模式下,不同模式下表名可以相同。
  • 复制
    复制成功
postgres=# create table public.t(id int,mc text);
CREATE TABLE
postgres=# \dt public.t 
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | t    | table | tbase
(1 row)

postgres=# create table tbase_schema.t1(id int,mc text); 
CREATE TABLE
postgres=# 
  1. 访问不在搜索路径对象时,需要写全路径。
  • 复制
    复制成功
postgres=# select * from t1;
ERROR:  relation "t1" does not exist
LINE 1: select * from t1;
                      ^
postgres=# select * from tbase_schema.t1;
 id | mc 
----+----
(0 rows)

上面出错就是因为模式tbase_schema没有配置在search_path搜索路径中。