PostgreSQL(02): PostgreSQL常用命令
目录
PostgreSQL 常用命令
满足验证条件的用户, 可以用psql命令进入pg的命令行交互模式
用户管理相关
查看用户列表
\du和\du+
postgres=# \du;
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
ubuntu | | {}
postgres=# \du+;
List of roles
Role name | Attributes | Member of | Description
-----------+------------------------------------------------------------+-----------+-------------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} |
ubuntu | | {} |
查看role的全局权限和口令, pg通过host登录, 验证的是role的密码
postgres=# select rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, substring(rolpassword, 1, 18) from pg_authid;
rolname | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcanlogin | rolreplication | rolbypassrls | rolconnlimit | substring
---------------------------+----------+------------+---------------+-------------+-------------+----------------+--------------+--------------+--------------------
postgres | t | t | t | t | t | t | t | -1 |
pg_database_owner | f | t | f | f | f | f | f | -1 |
pg_read_all_data | f | t | f | f | f | f | f | -1 |
pg_write_all_data | f | t | f | f | f | f | f | -1 |
pg_monitor | f | t | f | f | f | f | f | -1 |
pg_read_all_settings | f | t | f | f | f | f | f | -1 |
pg_read_all_stats | f | t | f | f | f | f | f | -1 |
pg_stat_scan_tables | f | t | f | f | f | f | f | -1 |
pg_read_server_files | f | t | f | f | f | f | f | -1 |
pg_write_server_files | f | t | f | f | f | f | f | -1 |
pg_execute_server_program | f | t | f | f | f | f | f | -1 |
pg_signal_backend | f | t | f | f | f | f | f | -1 |
pg_checkpoint | f | t | f | f | f | f | f | -1 |
ubuntu | f | t | f | f | t | f | f | -1 |
(14 rows)
创建用户
4个sql执行的结果没什么区别, 口令都会用SHA-256加密
postgres=# CREATE USER test_user1 WITH PASSWORD 'secret_passwd';
CREATE ROLE
postgres=# CREATE USER test_user2 WITH ENCRYPTED PASSWORD 'secret_passwd';
CREATE ROLE
postgres=# CREATE ROLE test_user3 WITH LOGIN PASSWORD 'secret_passwd';
CREATE ROLE
postgres=# CREATE ROLE test_user4 WITH LOGIN ENCRYPTED PASSWORD 'secret_passwd';
CREATE ROLE
-- 查看添加的结果
postgres=# select rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, substring(rolpassword, 1, 18) from pg_authid;
rolname | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcanlogin | rolreplication | rolbypassrls | rolconnlimit | substring
---------------------------+----------+------------+---------------+-------------+-------------+----------------+--------------+--------------+--------------------
postgres | t | t | t | t | t | t | t | -1 |
pg_database_owner | f | t | f | f | f | f | f | -1 |
...
ubuntu | f | t | f | f | t | f | f | -1 |
test_user1 | f | t | f | f | t | f | f | -1 | SCRAM-SHA-256$4096
test_user2 | f | t | f | f | t | f | f | -1 | SCRAM-SHA-256$4096
test_user3 | f | t | f | f | t | f | f | -1 | SCRAM-SHA-256$4096
test_user4 | f | t | f | f | t | f | f | -1 | SCRAM-SHA-256$4096
(18 rows)
查看user表
template1=# SELECT * FROM pg_user;
usename | usesysid | usecreatedb | usesuper | userepl | usebypassrls | passwd | valuntil | useconfig
------------+----------+-------------+----------+---------+--------------+----------+----------+-----------
postgres | 10 | t | t | t | t | ******** | |
ubuntu | 16388 | f | f | f | f | ******** | |
test_user2 | 16390 | f | f | f | f | ******** | |
test_user3 | 16391 | f | f | f | f | ******** | |
test_user4 | 16392 | f | f | f | f | ******** | |
test_user1 | 16389 | f | f | f | f | ******** | |
(6 rows)
修改用户口令
postgres=# ALTER ROLE test_user1 WITH password 'secret_passwd1';
ALTER ROLE
赋予权限
可以直接将一个用户的权限赋给另一个用户(以及收回)
GRANT myuser TO myuser1;
REVOKE myuser FROM myuser1;
查看用户权限之间的引用关系
postgres=# SELECT
r.rolname,
ARRAY(SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
WHERE m.member = r.oid) as memberof
FROM pg_catalog.pg_roles r
WHERE r.rolname NOT IN ('pg_signal_backend','rds_iam',
'rds_replication','rds_superuser',
'rdsadmin','rdsrepladmin')
ORDER BY 1;
rolname | memberof
---------------------------+--------------------------------------------------------------
pg_checkpoint | {}
pg_database_owner | {}
pg_execute_server_program | {}
pg_monitor | {pg_read_all_settings,pg_read_all_stats,pg_stat_scan_tables}
pg_read_all_data | {}
pg_read_all_settings | {}
pg_read_all_stats | {}
pg_read_server_files | {}
pg_stat_scan_tables | {}
pg_write_all_data | {}
pg_write_server_files | {}
postgres | {}
test_user1 | {}
test_user2 | {}
test_user3 | {}
test_user4 | {}
ubuntu | {}
(17 rows)
DATABASE 相关
数据库列表
\l
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges
-----------+----------+----------+---------+---------+------------+-----------------+-----------------------
postgres | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
template0 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | libc | =c/postgres +
| | | | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | libc | =c/postgres +
| | | | | | | postgres=CTc/postgres
(3 rows)
选中数据库
\c [dbname]
postgres=# \c template1
You are now connected to database "template1" as user "postgres".
创建数据库
创建数据库并指定owner, 修改owner
-- 如果不指定, 则owner为当前用户
template1=# CREATE DATABASE test_db1;
CREATE DATABASE
-- 指定用户
template1=# CREATE DATABASE test_db2 OWNER test_user2;
CREATE DATABASE
template1=# CREATE DATABASE test_db3;
CREATE DATABASE
template1=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges
-----------+------------+----------+---------+---------+------------+-----------------+-----------------------
...
test_db1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
test_db2 | test_user2 | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
test_db3 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
(6 rows)
-- 修改owner
template1=# ALTER DATABASE test_db3 OWNER to test_user3;
ALTER DATABASE
-- 查看修改结果
template1=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges
-----------+------------+----------+---------+---------+------------+-----------------+-----------------------
...
test_db1 | postgres | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
test_db2 | test_user2 | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
test_db3 | test_user3 | UTF8 | C.UTF-8 | C.UTF-8 | | libc |
删除数据库
template1=# DROP DATABASE test_db3;
DROP DATABASE
-- 删除前判断是否存在
template1=# DROP DATABASE IF EXISTS test_db3;
NOTICE: database "test_db3" does not exist, skipping
DROP DATABASE
授权数据库给用户
只是授权, 和owner有区别
-- 授权部分权限
template1=# GRANT CONNECT ON DATABASE test_db1 TO test_user1;
GRANT
-- 授权全部权限
template1=# GRANT ALL PRIVILEGES ON DATABASE test_db1 TO test_user2;
GRANT
查看数据库权限, 将sql中的 test_user2 换成要检查的目标用户
SELECT 'test_user2', datname, array(
SELECT privs FROM unnest(ARRAY[
(CASE WHEN has_database_privilege('test_user2',c.oid,'CONNECT') THEN 'CONNECT' ELSE NULL END),
(CASE WHEN has_database_privilege('test_user2',c.oid,'CREATE') THEN 'CREATE' ELSE NULL END),
(CASE WHEN has_database_privilege('test_user2',c.oid,'TEMPORARY') THEN 'TEMPORARY' ELSE NULL END),
(CASE WHEN has_database_privilege('test_user2',c.oid,'TEMP') THEN 'TEMP' ELSE NULL END)])
foo(privs)
WHERE privs IS NOT NULL
) FROM pg_database c;
?column? | datname | array
------------+-----------+---------------------------------
test_user2 | postgres | {CONNECT,TEMPORARY,TEMP}
test_user2 | template1 | {CONNECT}
test_user2 | template0 | {CONNECT}
test_user2 | test_db2 | {CONNECT,CREATE,TEMPORARY,TEMP}
test_user2 | test_db1 | {CONNECT,CREATE,TEMPORARY,TEMP}
(5 rows)
SCHEMA 相关
每个database都包含一个缺省的schema, 名称为 public, 如果不指定, 则使用这个缺省的 schema.
除了public和用户创建的schema之外, 每个数据库都包含一个pg_catalog的schema, 它包含系统表和所有内置数据类型、函数、操作符. pg_catalog 总是搜索路径中的一部分. 如果它没有明确出现在路径中, 那么它隐含地在所有路径之前搜索. 这样就保证了内置名字总是可以被搜索. 不过, 你可以明确地把pg_catalog放在搜索路径之后, 如果你想使用用户自定义的名字覆盖内置的名字的话.
-- 新增
CREATE SCHEMA aStock;
CREATE SCHEMA schema_name AUTHORIZATION user_name;
-- 删除空schema
DROP SCHEMA aStock;
-- 递归删除非空 schema
DROP SCHEMA aStock CASCADE;
-- 显示搜索路径
SHOW search_path;
-- 变更搜索路径:
SET search_path TO aStock, public;
SET search_path TO myschema;
授权schema给用户
GRANT USAGE ON SCHEMA myschema TO myuser;
-- 如果用户需要建表权限
GRANT USAGE, CREATE ON SCHEMA myschema TO myuser;
TABLE 相关
授权table给用户
GRANT SELECT ON TABLE mytable1, mytable2 TO myuser;
-- 如果需要包含myschema下所有table和view
GRANT SELECT ON ALL TABLES IN SCHEMA myschema TO myuser;
-- 如果需要增删改
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE mytable1, mytable2 TO myuser;
-- 如果需要包含myschema下所有table和view
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA myschema TO myuser;
注意上面的命令, 如果schema下创建了新table, myuser并不能访问, 如果要新建的table也自动授权, 需要使用下面的语句
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT ON TABLES TO myuser;
-- 带增删改
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO myuser;
- OIDs demoted to normal columns: a glance at the past
https://postgresql.verite.pro/blog/2019/04/24/oid-column.html - 表中隐藏的系统字段, 应该是没有网上一些文章说的自带版本控制字段用于乐观锁了
https://www.postgresql.org/docs/14/ddl-system-columns.html
SEQUENCE 相关
GRANT USAGE ON SEQUENCE myseq1, myseq2 TO readwrite;
-- You can also grant permission to all sequences using the following SQL statement:
GRANT USAGE ON ALL SEQUENCES IN SCHEMA myschema TO readwrite;
-- To automatically grant permissions to sequences added in the future:
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT USAGE ON SEQUENCES TO readwrite;
复杂查询
分组后取第一条
根据bank_card_no分组, 取时间最晚的一条, 使用ROW_NUMBER() OVER (PARTITION BY [col1] ORDER BY [col2] [ASC|DESC]) AS [alias]格式
WITH tb1 AS (
SELECT
goods_order.*,
ROW_NUMBER() OVER (PARTITION BY goods_order.bank_card_no ORDER BY created_at DESC ) AS rn
FROM
goods_order
WHERE goods_order.batch_id = 521
)
SELECT * from tb1
WHERE rn=1
对JSONB序列组合去重后更新
和MySQL一样, 如果要update的字段也在取值参数中, 需要多加一层select隔离一下才能执行
UPDATE goods_order
SET card_label = (select json_agg(t001.t) from (
select distinct(jsonb_array_elements(goods_order.card_label || '["tag1","tag2","tag3"]'::jsonb)) as t
) t001)
where
bank_card_no IN ( '123123123123' )
分组取最大最小值, 计数以及打上序号
SELECT
goods_order.*,
max(goods_order.created_at) OVER w AS created_at_max,
min(goods_order.created_at) OVER w AS created_at_min,
count(1) OVER w AS row_count,
ROW_NUMBER() OVER w1 AS seq
FROM
goods_order
WHERE
(
goods_order.data_import_id = 2
OR goods_order.data_import_id = 534
)
WINDOW
w AS (PARTITION BY goods_order.bank_card_no),
w1 AS (PARTITION BY goods_order.bank_card_no ORDER BY created_at DESC)
使用temp view 简化后续查询
CREATE OR REPLACE TEMP VIEW view1 AS
SELECT
goods_order.*,
max(goods_order.created_at) OVER w AS created_at_max,
min(goods_order.created_at) OVER w AS created_at_min,
count(1) OVER w AS row_count,
ROW_NUMBER() OVER w1 AS seq
FROM
goods_order
WHERE
(
goods_order.data_import_id = 2
OR goods_order.data_import_id = 534
)
WINDOW
w AS (PARTITION BY goods_order.bank_card_no),
w1 AS (PARTITION BY goods_order.bank_card_no ORDER BY created_at DESC);
select count(1) from view1;
PostgreSQL(02): PostgreSQL常用命令的更多相关文章
- PostgreSQL与MySQL常用命令比较[转]
PostgreSQL与MySQL常用命令比较 原文链接: http://www.phpwell.com/?p=174 PostgreSQL MySQL 服务启动:1)#service postgres ...
- postgresql的psql常用命令-4
psql是PostgreSQL的一个命令行交互式客户端工具 1. 查看postgresql账号 [root@localhost ~]#cat /etc/passwdroot:x:0:0:root:/r ...
- PostgreSQL客户端psql常用命令
使用psql客户端访问数据库, 列出了psql常用命令和参数. 常用命令 -- 使用指定用户和IP端口登陆 psql -h 10.43.159.11 -p 5432 -U postgres -W -- ...
- [转] postgresql常用命令
PS: 数据库安装后,里面的每个数据库有自己的用户密码,需要dump的时候,指定用户pg_dump -U xxx <数据库> > 某个地址 最近一直在学习Postgresql,下面 ...
- 02:linux常用命令
1.1 linux查看系统基本参数常用命令 1.查看磁盘 [root@linux-node1 ~]# df -hl Filesystem Size Used Avail Use% Mounted on ...
- Linux常用命令02(远程管理)
01 关机/重启 序号 命令 对应英文 作用 01 shutdown 选项 时间 shutdown 关机/重新启动 1.1 shutdown shutdown 命令可以 安全 关闭 或者 重新启动系统 ...
- Linux常用命令02
显示当前目录 pwd (print working directory) 显示当前目录 创建目录 mkdir (make directory) 创建目录(注意不是创建文 ...
- ***OneinStack交互安装FAQ和管理服务常用命令
转自: https://oneinstack.com/install/ 自动生成oneinstack安装连接: https://oneinstack.com/auto/ (进入linux系统后复杂上 ...
- Django中常用命令
Django 基本命令 熟练使用Django常用命令能让你事半功倍!!!! 1. 新建一个 django project django-admin.py startproject project-na ...
- Postgres常用命令之增、删、改、查
增.删.改.查: postgres=# \password postgres 为postgres进行密码设置: postgres=# CREATE USER test WITH PASSWORD '1 ...
随机推荐
- 利用FastReport传递图片参数,在报表上展示签名信息
在一个项目中,客户要求对报表中的签名进行仿手写的签名处理,因此我们原先只是显示相关人员的姓名的地方,需要采用手写方式签名,我们的报表是利用FastReport处理的,在利用楷体处理的时候,开发展示倒是 ...
- Java 求解自幂数(水仙花数)
什么是自幂数 如果在一个固定的进制中,一个 n 位自然数等于自身各个数位上数字的 n 次幂之和,则称此数为自幂数. 例如:在十进制中,153 是一个三位数,各个数位的3次幂之和为 1^3+5^3+3^ ...
- AlphaTensor论文阅读分析
AlphaTensor论文阅读分析 目前只是大概了解了AlphaTensor的思路和效果,完善ing deepmind博客在 https://www.deepmind.com/blog/discove ...
- windows设置开机启动程序
1.新建文件,填写路径 @echo off cd F:\程序路径\ //后面填写3D所在的路径 F: //程序的个盘符 run.bat 把这个文件填写完成后,改个名字,后缀改为bat,并把这个文件放在 ...
- 一天五道Java面试题----第九天(简述MySQL中索引类型对数据库的性能的影响--------->缓存雪崩、缓存穿透、缓存击穿)
这里是参考B站上的大佬做的面试题笔记.大家也可以去看视频讲解!!! 文章目录 1.简述MySQL中索引类型对数据库的性能的影响 2.RDB和AOF机制 3.Redis的过期键的删除策略 4.Redis ...
- 2022年最新编辑Linux基础知识总结
文章目录 1.Linux的目录结构 2.远程操作Linux和上传文件到Linux 3.文本编辑 4.快捷键 5.登录.注销.关机.重启 6.用户管理 6.1 .新用户注册 6.2.使用新用户登录 6. ...
- 齐博x2模型里边钩子的创建与使用
在模型里边的钩子创建与使用方法跟在控制器里边的钩子创建及使用方法是有所区别的在模型里边创建的钩子,你可以理解为执行一个函数,是无法调用模型里边的类的方法及属性的.比如系统文件\application\ ...
- .Net Core中获取appsettings.json中的节点数据
获取ConnectionStrings节点数据 //appsettings.json { "ConnectionStrings": { //DEV "DbConn&quo ...
- Android 跨进程渲染
本项目用于验证 Android 是否能够跨进程渲染 View,最终实现了在子进程创建WebView,主进程显示的功能. 一.跨进程渲染的意义 有一些组件比如 WebView 如果在主进程初始化,会大大 ...
- 论文笔记 - RETRIEVE: Coreset Selection for Efficient and Robust Semi-Supervised Learning
Motivation 虽然半监督学习减少了大量数据标注的成本,但是对计算资源的要求依然很高(无论是在训练中还是超参搜索过程中),因此提出想法:由于计算量主要集中在大量未标注的数据上,能否从未标注的数据 ...