利用python为PostgreSQL的表自动添加分区
作者:PostgreSQLChina 发布时间:2023-07-07 14:44:58
标签: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')
来源:https://blog.csdn.net/weixin_46199817/article/details/112261389


猜你喜欢
- 前言range() 和 xrange() 是两个函数,可用于在 Python的 for 循环中迭代一定次数。在 Python 3 中,没有
- sql语句reverse(substring(reverse(Path),1,charindex('/',reverse(P
- 1.hashlib的简介hashlib 是一个提供了一些流行的hash(摘要)算法的Python标准库.其中所包括的算法有 md5, sha
- 下面给出ORACLE的一种实现方式,要分2步走:1. 建立 SEQUENCE CREATE [ OR REPLACE ] SEQUENCE
- 一:使用layer.open打开的子页面window.parent.location.reload()//刷新父页面var index =
- 1. 概念1.1 基本概念时间,对于我们来说很重要,什么时候做什么?什么时候发生什么?没有时间的概念,生活就乱了。在日常的运维当中,我们更关
- 本文实例讲述了Python回文字符串及回文数字判定功能。分享给大家供大家参考,具体如下:所谓回文字符串,就是一个字符串,从左到右读和从右到左
- 一、前情提要最近在写一个项目,需要用到子线程,但是我们小学二年级就学过操作系统, 线程的执行是由系统的CPU调度算法所决定的,调度算法按照一
- DBI安装:DBI详细信息参考:http://dbi.perl.org/ 1.下载DBI包: wget http://search.cpan
- 摘要:在本篇博客中,我们将介绍如何在YOLOv5车牌识别的基础上进一步实现字符分割与识别。我们将详细介绍字符分割方法,如投影法和轮廓法,以及
- 今天有朋友问到如下一则案例,ORA-01114,ORA-27067以及OSD-04026错误同时出现:*** ACTION NAME:()
- 一、MySQL删除外键格式:alter table 表名 drop foreign key 外键名;表名就是有外键存在的那个表。外键名可以通
- 1、创建表 createtableTest_Increase( useridnumber(10)NOTNULLprimarykey,/*主键
- MySQL和MariaDB的关系MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可。MariaDB
- 把今天的学习的opencv知识先记录一下!运行环境是:pycharm话不多说,献上代码再说:import cv2 # openc
- 我就废话不多说了,大家还是直接看代码吧~In [1]: import osIn [2]: os.environ["CUDA_VIS
- 介绍图灵完备性(Turing completeness)是通用计算机的一个属性,它表示一个程序可以写另一个程序。比如 go test 命令:
- 以下内容是针对安装tensorflow-CPU版本的。tensorflow已经支持Python3.8版本的安装。可以查看自己的Python版
- 前言本文主要给大家介绍的关于Python批量压缩png的相关资料,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:1.需求为什
- 分析在Python中,字符串是不可变的。所以无法直接删除字符串之间的特定字符。所以想对字符串中字符进行操作的时候,需要将字符串转变为列表,列