zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

OushuDB 数据库基本用法(中)

2023-03-15 23:20:29 时间

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)