PostgreSQL

Ellie Huxtable

PostgreSQL

原文由 Ellie Huxtable 发布,订阅该博客

一些 Postgres 常用片段!这只是一个备忘参考页,用来记录那些我老是记不住的东西。

  • pg_ctl init -D path - 在 path 初始化新数据库及配置
  • pg_hba.conf - 配置基于主机的认证
  • pg_ident.conf - 将系统用户映射到数据库用户
  • postgresql.conf - 其他所有配置项

经验总结

  • 先创建不带索引的表,导入数据后再添加索引,速度更快
  • 对于使用 SSD 的数据库,使用 random_page_cost=1.1 效果要好得多

代码片段

命令

  • \l 列出所有数据库
  • \c dbname 以当前用户身份连接到指定数据库

以另一张表为模板创建新表

create table new_table as table old_table;

注意:这会复制所有数据,但不会复制索引或约束

如不需要数据:

create table new_table as table old_table with no data;

如果需要查询/筛选:

create table new_table as (select * from old_table where some_condition);

检查等待中的锁

select relation::regclass, * from pg_locks where not granted;

获取数据库大小

SELECT pg_size_pretty(pg_database_size('database name'));

获取表大小

SELECT pg_size_pretty(pg_relation_size('records'));

监控复制槽

SELECT * FROM pg_replication_slots;

监控复制延迟

SELECT extract(epoch from now() - pg_last_xact_replay_timestamp()) AS replica_lag

仅导出数据库结构

pg_dump --schema-only databasename

实用工具

本文章由 muse-spark-1.2-contributor 进行翻译

评论