服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - PostgreSQL - 如何为PostgreSQL的表自动添加分区

如何为PostgreSQL的表自动添加分区

2021-03-08 17:44lottu PostgreSQL

这篇文章主要介绍了如何为PostgreSQL的表自动添加分区,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

PostgreSQL 引进“分区特性,解放了之前采用“表继承”+ “触发器”来实现分区表的繁琐、低效。而添加分区,都是手动执行 SQL。

演示目的:利用 python 来为 PostgreSQL 的表自动添加分区。

python版本: python3+

?
1
pip3 install psycopg2

 

一、配置数据源

database.ini 文件:记录数据库连接参数

?
1
2
3
4
5
6
7
8
9
10
11
12
[adsas]
host=192.168.1.201
database=adsas
user=adsas
password=adsas123
port=5432
[test]
host=192.168.1.202
database=adsas
user=adsas
password=adsas123
port=5432

 

二、config 脚本

config.py 文件:下面的config() 函数读取database.ini文件并返回连接参数。config() 函数位于config.py文件中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/python3
from configparser import ConfigParser
 
def config(section ,filename='database.ini'):
  # create a parser
  parser = ConfigParser()
  # read config file
  parser.read(filename)
 
  # get section, default to postgresql
  db = {}
  if parser.has_section(section):
    params = parser.items(section)
    for param in params:
      db[param[0]] = param[1]
  else:
    raise Exception('Section {0} not found in the {1} file'.format(section, filename))
 
  return db

 

三、创建子表脚本

pg_add_partition_table.py 文件:其中 create_table函数是创建子表SQL。其中参数

 

 

参数名 含义
db 指向数据库
table 主表
sub_table 正要新建的子表名
start_date 范围分界开始值
end_date 范围分界结束值

 

?
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
#!/usr/bin/python3
import psycopg2
from config import config
# example: create table tbl_game_android_step_log_2021_07 PARTITION OF tbl_game_android_step_log FOR VALUES FROM ('2021-07-01') TO ('2021-08-01');
def create_table(db, table, sub_table, start_date, end_date):
  """ create subtable in the PostgreSQL database"""
  command = "create table {0} PARTITION OF {1} FOR VALUES FROM ('{2[0]}') TO ('{2[1]}');".format(sub_table, table, (start_date, end_date))
  conn = None
  try:
    # read the connection parameters
    params = config(section = db)
    # connect to the PostgreSQL server
    conn = psycopg2.connect(**params)
    cur = conn.cursor()
    # create table one by one
    cur.execute(command)
    # close communication with the PostgreSQL database server
    cur.close()
    # commit the changes
    conn.commit()
  except (Exception, psycopg2.DatabaseError) as error:
    print(error)
  finally:
    if conn is not None:
      conn.close()

 

四、执行文件main.py

main.py:主文件;通过执行main生成分区表。

示例:

?
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
#!/usr/bin/python3
import datetime
from datetime import date
from dateutil.relativedelta import *
from pg_add_partition_table import create_table
# Get the 1st day of the next month
def get_next_month_first_day(d):
  return date(d.year + (d.month == 12), d.month == 12 or d.month + 1 , 1)
  
def create_sub_table(db, table):
  # Get current date
  d1 = date.today()
  # Get next month's date
  d2 = d1 + relativedelta(months=+1)
  # Get the 1st day of the next month;As the starting value of the partitioned table
  start_date = get_next_month_first_day(d1)
  # Gets the 1st of the next two months as the end value of the partitioned table
  end_date = get_next_month_first_day(d2)
  # get sub table name
  getmonth = datetime.datetime.strftime(d2, '%Y_%m')
  sub_table = table + '_' + getmonth
  create_table(db, table, sub_table, start_date, end_date)
    
if __name__ == '__main__':
  create_sub_table('test', 'tbl_game_android_step_log');

上面示例单独为表tbl_game_android_step_log;创建分区;若多个表;用for语句处理

?
1
2
3
# 多表操作
 for table in ['tbl_game_android_step_log', 'tbl_game_android_game_log','tbl_game_android_pay_log']:
   create_sub_table('test', table);

]

演示之前:

?
1
2
3
4
5
6
adsas=> select * from pg_partition_tree('tbl_game_android_step_log');
        relid        |    parentrelid    | isleaf | level
-----------------------------------+---------------------------+--------+-------
 tbl_game_android_step_log     |              | f   |   0
 tbl_game_android_step_log_2020_12 | tbl_game_android_step_log | t   |   1
(2 rows)

演示之后:

?
1
2
3
4
5
6
7
8
9
adsas=> select * from pg_partition_tree('tbl_game_android_step_log');
        relid        |    parentrelid    | isleaf | level
-----------------------------------+---------------------------+--------+-------
 tbl_game_android_step_log     |              | f   |   0
 tbl_game_android_step_log_2020_12 | tbl_game_android_step_log | t   |   1
 tbl_game_android_step_log_2021_01 | tbl_game_android_step_log | t   |   1
Partition key: RANGE (visit_time)
Partitions: tbl_game_android_step_log_2020_12 FOR VALUES FROM ('2020-12-01 00:00:00') TO ('2021-01-01 00:00:00'),
      tbl_game_android_step_log_2021_01 FOR VALUES FROM ('2021-01-01 00:00:00') TO ('2021-02-01 00:00:00')

五、加入定时任务

到此这篇关于如何为PostgreSQL的表自动添加分区的文章就介绍到这了,更多相关PostgreSQL的表添加分区内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/lottu/archive/2021/01/04/14228477.html

延伸 · 阅读

精彩推荐
  • PostgreSQL深入理解PostgreSQL的MVCC并发处理方式

    深入理解PostgreSQL的MVCC并发处理方式

    这篇文章主要介绍了深入理解PostgreSQL的MVCC并发处理方式,文中同时介绍了MVCC的缺点,需要的朋友可以参考下 ...

    PostgreSQL教程网3622020-04-25
  • PostgreSQLPostgresql开启远程访问的步骤全纪录

    Postgresql开启远程访问的步骤全纪录

    postgre一般默认为本地连接,不支持远程访问,所以如果要开启远程访问,需要更改安装文件的配置。下面这篇文章主要给大家介绍了关于Postgresql开启远程...

    我勒个去6812020-04-30
  • PostgreSQLRDS PostgreSQL一键大版本升级技术解密

    RDS PostgreSQL一键大版本升级技术解密

    一、PostgreSQL行业位置 (一)行业位置 在讨论PostgreSQL(下面简称为PG)在整个数据库行业的位置之前,我们先看一下阿里云数据库在全球的数据库行业里的...

    未知1192023-05-07
  • PostgreSQLpostgresql 中的to_char()常用操作

    postgresql 中的to_char()常用操作

    这篇文章主要介绍了postgresql 中的to_char()常用操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    J符离13432021-04-12
  • PostgreSQLPostgreSQL标准建表语句分享

    PostgreSQL标准建表语句分享

    这篇文章主要介绍了PostgreSQL标准建表语句分享,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    码上得天下7962021-02-27
  • PostgreSQLPostgresql查询效率计算初探

    Postgresql查询效率计算初探

    这篇文章主要给大家介绍了关于Postgresql查询效率计算的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Postgresql具有一定的参考学习价...

    轨迹4622020-05-03
  • PostgreSQL分布式 PostgreSQL之Citus 架构

    分布式 PostgreSQL之Citus 架构

    节点 Citus 是一种 PostgreSQL 扩展,它允许数据库服务器(称为节点)在“无共享(shared nothing)”架构中相互协调。这些节点形成一个集群,允许 PostgreSQL 保存比单...

    未知802023-05-07
  • PostgreSQLpostgresql 数据库中的数据转换

    postgresql 数据库中的数据转换

    postgres8.3以后,字段数据之间的默认转换取消了。如果需要进行数据变换的话,在postgresql数据库中,我们可以用"::"来进行字段数据的类型转换。...

    postgresql教程网12482021-10-08