配置訪問模式的順序
 
                  更新時間 2025-02-14 10:21:29
                    
 
                    最近更新時間: 2025-02-14 10:21:29
                  
   分享文章 
本文為您介紹如何配置訪問模式的順序。
 TeleDB有一個運行變量叫search_path,其值為模式名列表,用于配置訪問數據對象的順序,如下所示。
當前連接用戶。
teledb=# select current_user;
 current_user 
--------------
 teledb
(1 row)顯示當前search_path,搜索路徑只配置為$user, public,其中 $user為當前用戶名,即上面的current_user 值teledb。
teledb=# show search_path;
   search_path   
-----------------
 "$user", public
(1 row)不指定模式創建數據表,則該表存放于第一個搜索模式下面。第一個模式找不到的情況下選擇第二個,依次順序查找。
teledb=# create table t2(id int, content text);
CREATE TABLE
teledb=# \dt t2
        List of relations
 Schema | Name | Type  |  Owner  
--------+------+-------+---------
 public | t2   | table | teledb
(1 row)
--由于沒有teledb模式,所以表默認放到了public模式下
-- 創建teledb模式后再次建表,表建到了teledb模式下
teledb=# create schema teledb;
CREATE SCHEMA
teledb=# create table t3(id int, content text);
CREATE TABLE
teledb=# \dt t3
        List of relations
 Schema  | Name | Type  |  Owner  
---------+------+-------+---------
 teledb | t3   | table | teledb
(1 row)指定表位于某個模式下,不同模式下表名可以相同。在public模式下創建t3表
teledb=# create table public.t3(id int, content text);
CREATE TABLE
teledb=# \dt public.t3
        List of relations
 Schema | Name | Type  |  Owner  
--------+------+-------+---------
 public | t3   | table | teledb
(1 row)同名的表查詢時,沒有指定shema時,始終只會查到前面模式的表數據。
-- 插入數據到public.t3表
teledb=# insert into public.t3 values(1,'test');
INSERT 0 1
-- 由于teledb模式在第一順位,且存在同名表,所以始終是teledb模式下的空表
teledb=# select * from t3;
 id | content 
----+---------
(0 rows)
-- 指定public模式去查詢可以查到插入的數據
teledb=# select * from public.t3;
 id | content 
----+---------
  1 | test
(1 row)訪問不在搜索路徑的對象時,需要寫全路徑。
teledb=# create table test1.t4 (id int, name char);
CREATE TABLE
teledb=# select * from t4;
ERROR:  relation "t4" does not exist
LINE 1: select * from t4;
                      ^
teledb=# select * from test1.t4;
 id | name 
----+------
(0 rows)上面出錯是因為模式test1沒有配置在search_path搜索路徑中。
