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


Posted in Python onJanuary 18, 2021

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通过matplotlib绘制动画简单实例
Dec 13 Python
使用python编写udp协议的ping程序方法
Apr 22 Python
python 常用的基础函数
Jul 10 Python
在Mac下使用python实现简单的目录树展示方法
Nov 01 Python
pytorch自定义初始化权重的方法
Aug 17 Python
Pandas实现DataFrame按行求百分数(比例数)
Dec 27 Python
postman和python mock测试过程图解
Feb 22 Python
python爬虫开发之Request模块从安装到详细使用方法与实例全解
Mar 09 Python
django rest framework使用django-filter用法
Jul 15 Python
Python中的None与 NULL(即空字符)的区别详解
Sep 24 Python
基于Python爬取搜狐证券股票过程解析
Nov 18 Python
教你用Python写一个植物大战僵尸小游戏
Apr 25 Python
如何查看python关键字
Jan 17 #Python
Python日志打印里logging.getLogger源码分析详解
Jan 17 #Python
Python中的面向接口编程示例详解
Jan 17 #Python
Python学习之time模块的基本使用
Jan 17 #Python
python中re模块知识点总结
Jan 17 #Python
史上最详细的Python打包成exe文件教程
Jan 17 #Python
python制作微博图片爬取工具
Jan 16 #Python
You might like
phpMyAdmin 安装及问题总结
2009/05/28 PHP
laravel学习教程之关联模型
2016/07/30 PHP
laravel 实现根据字段不同值做不同查询
2019/10/23 PHP
window.open的功能全解析
2006/10/10 Javascript
jQuery的Ajax的自动完成功能控件简要说明
2013/02/22 Javascript
js实现飞入星星特效代码
2014/10/17 Javascript
javascript中动态函数用法实例分析
2015/05/14 Javascript
学习JavaScript设计模式(单例模式)
2015/11/26 Javascript
jquery实现具有收缩功能的垂直导航菜单
2016/02/16 Javascript
浅析Bootstrip的select控件绑定数据的问题
2016/05/10 Javascript
JavaScript实现简易的天数计算器实例【附demo源码下载】
2017/01/18 Javascript
js遍历json对象所有key及根据动态key获取值的方法(必看)
2017/03/09 Javascript
详细讲解vue2+vuex+axios
2017/05/27 Javascript
JS实现百度网盘任意文件强制下载功能
2018/08/31 Javascript
Layui table field初始化加载时进行隐藏的方法
2019/09/19 Javascript
JavaScript实现左右滚动电影画布
2020/02/06 Javascript
[06:43]DAC2018 4.5 SOLO赛 Maybe vs Paparazi
2018/04/06 DOTA
python中stdout输出不缓存的设置方法
2014/05/29 Python
举例详解Python中循环语句的嵌套使用
2015/05/14 Python
Python 实现文件打包、上传与校验的方法
2019/02/13 Python
PyQt5实现简单数据标注工具
2019/03/18 Python
如何使用 Flask 做一个评论系统
2020/11/27 Python
Python的scikit-image模块实例讲解
2020/12/30 Python
HTML5自定义属性前缀data-及dataset的使用方法(html5 新特性)
2017/08/24 HTML / CSS
天巡全球:Skyscanner Global
2017/06/20 全球购物
法拉利英国精品店:Ferraris Boutique UK
2019/07/20 全球购物
2014年道德讲堂实施方案
2014/03/05 职场文书
法人授权委托书范本
2014/04/04 职场文书
汽车销售经理岗位职责
2014/06/09 职场文书
2014年班组建设工作总结
2014/12/01 职场文书
创业计划书之溜冰场
2019/10/25 职场文书
Django给表单添加honeypot验证增加安全性
2021/05/06 Python
go 实现简易端口扫描的示例
2021/05/22 Golang
nginx 配置指令之location使用详解
2022/05/25 Servers
MySQL一劳永逸永久支持输入中文的方法实例
2022/08/05 MySQL
python 镜像环境搭建总结
2022/09/23 Python