天天看點

OushuDB 資料庫基本用法(中)1、概述2、資料庫3、模式

OushuDB 資料庫基本用法(中)1、概述2、資料庫3、模式

1、概述

一個OushuDB叢集管理着多個資料庫(database),每個資料庫又包含多個模式(schema), 一個模式包含多個對象(表,視圖,函數等),是以這些對象之間的層級結構為:

database -> schema -> (tables, functions, views)

每個模式,表,視圖,函數等隻屬于一個database。本章主要介紹每一種對象的常見用法。具體使用文法可以參見參考手冊。

2、資料庫

OushuDB在初始化完成後,會預設生成三個資料庫,可以使用l指令檢視,或者檢視pg_database系統表。

postgres=# \l
                  List of databases
   Name    |  Owner   | Encoding | Access privileges
-----------+----------+----------+-------------------
 postgres  | ChangLei | UTF8     |
 template0 | ChangLei | UTF8     |
 template1 | ChangLei | UTF8     |
(4 rows)           

其中template0和template1為模版資料庫。template1為系統預設用來建立新資料庫的模版資料庫,使用者可以修改。template0預設不接受連接配接,是以不可更改,目的是始終儲存一個幹淨的模版資料庫。

建立一個資料庫的時候,可以指定一個資料庫的模版資料庫。預設為template1,現在OushuDB隻支援以template0,template1和postgres資料庫為模版資料庫。例如:

postgres=# create database tdb; # 建立一個新資料庫,預設以template0為模版
CREATE DATABASE

postgres=#\c postgres  # 連接配接postgres
postgres=# create table test(i int);  # 在postgres資料庫中建立表test
CREATE TABLE

postgres=# create table test_orc(i int) with (appendonly=true, orientation=orc);  # 在postgres資料庫中建立ORC格式表
CREATE TABLE

postgres=# create database dbnew template postgres;
CREATE DATABASE

postgres=#\c dbnew # 連接配接dbnew           

可以看到,dbnew中現在包含test表

dbnew=#\d
               List of relations
 Schema | Name | Type  |  Owner   |   Storage
--------+------+-------+----------+-------------
 public | test | table | ChangLei | append only
(1 row)           

3、模式

一個資料庫包含多個模式(schema),而一個模式可以包含多種命名對象,比如表,資料類型,函數,操作符等。同一個對象名字可以用在不同的模式中而不産生沖突。比如schema1中可以包含表test,schema2中也可以同時包含名字為test的表。從這個意義上,模式很像一個命名空間(namespace)。

當建立一個對象時,預設被放置在public模式中。下面是系統預設建立的schema。

template1=# \dn
       List of schemas
        Name        |  Owner
--------------------+----------
 hawq_toolkit       | ChangLei
 information_schema | ChangLei
 pg_aoseg           | ChangLei
 pg_bitmapindex     | ChangLei
 pg_catalog         | ChangLei
 pg_toast           | ChangLei
 public             | ChangLei
(7 rows)           

通常在這樣幾個場景下,使用者需要使用模式:

● 允許多個使用者同時使用一個資料庫,而不産生名字沖突。

● 把資料庫對象組織成多個schema,好像是多個命名空間一樣

● 第三方應用可以把它們的對象放到一個單獨的schema中,而不和其他對象産生從圖。

注意:schema不可以嵌套,也就是說,schema中不可以再包含schema。

下面是建立schema的例子。

create schema myschema;           

建立或者存取一個schema中的對象,可以使用{schema}.{object}形式,例如:

create table myschema.test(i int);
select * from myschema.test;           

删除一個空的schema,可以使用:

drop schema myschame;           

删除不空的schema,可以使用cascade關鍵詞:

drop schema myschema cascade;           

使用{schema}.{object}形式,通常用起來不是很友善。可以通過設定schema搜尋路徑來簡化。”SHOW search_path”指令可以給出目前的schema搜尋路徑。”SET search_path TO schema-name1, schema-name2”可以設定schema搜尋路徑。例如:

postgres=# show search_path;
  search_path
----------------
 "$user",public
(1 row)

postgres=# create schema myschema;
CREATE SCHEMA

postgres=# set search_path = public, myschema;
SET

postgres=# show search_path;
   search_path
------------------
 public, myschema
(1 row)