PostgreSQL 5.7. Schemas 筆記

PostgreSQL 5.7. Schemas 筆記

https://www.postgresql.org/docs/9.4/ddl-schemas.htmlhtml

A database contains one or more named schemas, which in turn contain tables. Schemas also contain other kinds of named objects, including data types, functions, and operators. The same object name can be used in different schemas without conflict; for example, both schema1 and myschema can contain tables named mytable. Unlike databases, schemas are not rigidly separated: a user can access objects in any of the schemas in the database he is connected to, if he has privileges to do so.
  • 一個數據庫包含多個schema, schema裏包含tables, database 的下一層邏輯結構就是 schema
  • schema 也包括各類 objects, data types, functions, operators
  • 不一樣schem裏的table名能夠相同
在建立一個新的 database 時, PostgreSQL 會自動爲其建立一個 名爲 public 的 schema。 若是未設置 search_path 變量,那 麼 PostgreSQL 會將你建立的全部對象默認放入 public schema 中。_

使用schema帶來的好處sql

  • 容許多用戶使用一個數據庫而不會相互干擾, 數據隔離
  • 將數據庫對象組織到邏輯組中以使其更易於管理
  • 第三方應用程序能夠放在單獨的模式中, 這樣它們就不會與其餘對象的名稱衝突

5.7.1. Creating a Schema

code example:數據庫

CREATE SCHEMA myschema;

訪問schema的表post

schema.table

實際上,更通用的語法postgresql

database.schema.table

在schema裏建立表code

CREATE TABLE myschema.mytable (
 ...
);

刪除空schemahtm

DROP SCHEMA myschema;

刪除schema 而且也刪除其中的對象對象

DROP SCHEMA myschema CASCADE;

爲某個用戶建立schemaget

CREATE SCHEMA schemaname AUTHORIZATION username;

5.7.2. The Public Schema

默認建立的表都在public schemait

下面兩條語句是等價的

CREATE TABLE products ( ... );
CREATE TABLE public.products ( ... );

5.7.3. The Schema Search Path

當執行類 似 SELECT * FROM dogs 這種語句時, PostgreSQL 是怎麼知道要查的是哪一個 schema 中的表 呢?

能夠加schema前綴解決, 也能夠設置 search_path 變量解決

查看

SHOW search_path;
search_path
--------------
 "$user",public
PostgreSQL 有一個少爲人知的系統變量叫做 user , 它表明了當前登陸用戶的名稱。 執行 SELECT user 就能看到其名稱。
對於search_path 裏的$user, 若是當前登陸的角色是 doggy, 那麼全部的查詢都會優先去 doggy schema 中尋找目標表, 若是找不到纔會去 public schema 下找

設置新的schema倒search path裏

SET search_path TO myschema,public;

這樣 默認 建立訪問 table 都在 myschema schema裏

相關文章
相關標籤/搜索