利用python为PostgreSQL的表自动添加分区

 更新时间:2021年01月18日 09:44:44   作者:PostgreSQLChina  
这篇文章主要介绍了利用python为PostgreSQL的表自动添加分区,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

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

pip3 install psycopg2

一、配置数据源

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

[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文件中

#!/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 范围分界结束值

#!/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生成分区表。

示例:

#!/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语句处理

# 多表操作

  for table in ['tbl_game_android_step_log', 'tbl_game_android_game_log','tbl_game_android_pay_log']:
    create_sub_table('test', table);
演示之前:
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)

演示之后:

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')

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

相关文章

  • 基于Python批量镶嵌拼接遥感影像/栅格数据(示例代码)

    基于Python批量镶嵌拼接遥感影像/栅格数据(示例代码)

    这篇文章主要介绍了基于Python批量镶嵌拼接遥感影像/栅格数据,使用时直接修改Mosaic_GDAL函数的入参就行了,选择数据存放的路径会自动拼接,命名也会自己设置无需额外修改,需要的朋友可以参考下
    2023-10-10
  • 如何实现更换Jupyter Notebook内核Python版本

    如何实现更换Jupyter Notebook内核Python版本

    这篇文章主要介绍了如何实现更换Jupyter Notebook内核Python版本,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • 基于Python的微信机器人开发 微信登录和获取好友列表实现解析

    基于Python的微信机器人开发 微信登录和获取好友列表实现解析

    这篇文章主要介绍了Python微信机器人开发 微信登录和获取好友列表实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 基于Python制作一副扑克牌过程详解

    基于Python制作一副扑克牌过程详解

    这篇文章主要介绍了基于Python制作一副扑克牌过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 浅谈openpyxl库,遇到批量合并单元格的问题

    浅谈openpyxl库,遇到批量合并单元格的问题

    这篇文章主要介绍了浅谈openpyxl库,遇到批量合并单元格的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03
  • pytest实战技巧之参数化基本用法和多种方式

    pytest实战技巧之参数化基本用法和多种方式

    本文介绍了pytest参数化的基本用法和多种方式,帮助读者更好地使用这个功能,同时,还介绍了一些高级技巧,如动态生成参数名称、参数化的组合和动态生成参数化装饰器,帮助读者更灵活地使用参数化,感兴趣的朋友参考下吧
    2023-12-12
  • Python实现识别图像中人物的示例代码

    Python实现识别图像中人物的示例代码

    这篇文章主要介绍了通过face_recognition提供的demo代码,简单调整了一下,从而实现识别图像中人物的功能,感兴趣的可以跟随小编一起试试
    2022-01-01
  • 使用python构建一个自己的聊天室

    使用python构建一个自己的聊天室

    这篇文章主要介绍了使用python构建一个自己的聊天室,有助于帮助小伙伴们理解掌握Python的socket编程,需要的朋友可以参考下
    2023-04-04
  • python 提取文件指定列的方法示例

    python 提取文件指定列的方法示例

    这篇文章主要介绍了python 提取文件指定列的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • 利用Python的PyPDF2库提取pdf中的图片

    利用Python的PyPDF2库提取pdf中的图片

    本篇给大家分享一下通过Python的PyPDF2库提取pdf中的图片方法,文中有详细的代码示例和流程步骤,感兴趣的同学可以阅读一下
    2023-05-05

最新评论