常用 DataBase 相关操作和资源

记录一些常用的 DataBase 相关的东西。

  • 查询
  • 权限
  • 备份
  • 读写

查询

1
2
3
-- 查询所有的 schema
select schema_name from information_schema.schemata;
select nspname from pg_catalog.pg_namespace;

权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--- 创建 Read-Only 用户
GRANT CONNECT ON DATABASE [db_name] TO [user_name];
GRANT USAGE ON SCHEMA public TO [user_name];
-- special table
GRANT SELECT ON [table_name] TO [user_name];
-- all tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO [user_name];
-- grant access to the new tables automatically
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO [user_name];

-- 创建正常用户
CREATE USER [user_name] WITH PASSWORD 'xxxxxxx';
-- only public schema
GRANT ALL PRIVILEGES ON DATABASE [db_name] TO [user_name];
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO [use_rname];

备份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
### psql dump ###
pg_dump -h [host] -Fc -o -U [user_name] [db_name] > backup.dump
sudo -u postgres pg_restore -C [backup.dump]
# Example
pg_dump -h 67.8.78.10 -Fc -o -U myuser mydb > mydb_backup.dump
pg_restore -h 67.8.78.10 -p 5432 -d mydb -U myuser mydb_backup.dump

### psql sql ###
pg_dump -h [host] -U [user_name] [db_name] > mydb_backup.sql
psql -h host -d mydb -U myuser -p 5432 -a -q -f mydb_backup.sql
-h PostgreSQL server IP address
-d database name
-U user name
-p port which PostgreSQL server is listening on
-f path to SQL script
-a all echo
-q quiet
-f file

// complete (all db and objects)
pg_dumpall -U myuser -h 67.8.78.10 --clean --file=backup.dump
// restore from pg_dumpall --clean
psql -f backup.dump postgres #it doesn't matter which db you select here


### mysql ###
mysqldump --host [host] -P [port] -u [user_name] -p[password] [db_name] > backup.sql
# Example
mysqldump --host 192.168.1.15 -P 3306 -u myuser -pmypassword mydb > mydb.sql

读写

1
2
# 从文件中写入 DB
psql -h host -d db_name -U bi -p port -c "\copy table (col1,col2,...coln) FROM '/path/to/data.txt' with delimiter as '|'"

编码

mysql - What’s the difference between utf8_general_ci and utf8_unicode_ci - Stack Overflow

collation - What is the impact of LC_CTYPE on a PostgreSQL database? - Database Administrators Stack Exchange

Creating a UTF-8 Database

UTF8 Postgresql Create Database Like MySQL (including character set, encoding, and lc_type) - Stack Overflow

How to fix a locale setting warning from Perl? - Stack Overflow

资源

参考