如何为PostgreSQL的表自动添加分区
PostgreSQL引进“分区”表特性,解放了之前采用“表继承”+“触发器”来实现分区表的繁琐、低效。而添加分区,都是手动执行SQL。
演示目的:利用python来为PostgreSQL的表自动添加分区。
python版本:python3+
pip3installpsycopg2
一、配置数据源
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
fromconfigparserimportConfigParser
defconfig(section,filename='database.ini'):
#createaparser
parser=ConfigParser()
#readconfigfile
parser.read(filename)
#getsection,defaulttopostgresql
db={}
ifparser.has_section(section):
params=parser.items(section)
forparaminparams:
db[param[0]]=param[1]
else:
raiseException('Section{0}notfoundinthe{1}file'.format(section,filename))
returndb
三、创建子表脚本
pg_add_partition_table.py文件:其中create_table函数是创建子表SQL。其中参数
| 参数名 | 含义 |
|---|---|
| db | 指向数据库 |
| table | 主表 |
| sub_table | 正要新建的子表名 |
| start_date | 范围分界开始值 |
| end_date | 范围分界结束值 |
#!/usr/bin/python3
importpsycopg2
fromconfigimportconfig
#example:createtabletbl_game_android_step_log_2021_07PARTITIONOFtbl_game_android_step_logFORVALUESFROM('2021-07-01')TO('2021-08-01');
defcreate_table(db,table,sub_table,start_date,end_date):
"""createsubtableinthePostgreSQLdatabase"""
command="createtable{0}PARTITIONOF{1}FORVALUESFROM('{2[0]}')TO('{2[1]}');".format(sub_table,table,(start_date,end_date))
conn=None
try:
#readtheconnectionparameters
params=config(section=db)
#connecttothePostgreSQLserver
conn=psycopg2.connect(**params)
cur=conn.cursor()
#createtableonebyone
cur.execute(command)
#closecommunicationwiththePostgreSQLdatabaseserver
cur.close()
#committhechanges
conn.commit()
except(Exception,psycopg2.DatabaseError)aserror:
print(error)
finally:
ifconnisnotNone:
conn.close()
四、执行文件main.py
main.py:主文件;通过执行main生成分区表。
示例:
#!/usr/bin/python3
importdatetime
fromdatetimeimportdate
fromdateutil.relativedeltaimport*
frompg_add_partition_tableimportcreate_table
#Getthe1stdayofthenextmonth
defget_next_month_first_day(d):
returndate(d.year+(d.month==12),d.month==12ord.month+1,1)
defcreate_sub_table(db,table):
#Getcurrentdate
d1=date.today()
#Getnextmonth'sdate
d2=d1+relativedelta(months=+1)
#Getthe1stdayofthenextmonth;Asthestartingvalueofthepartitionedtable
start_date=get_next_month_first_day(d1)
#Getsthe1stofthenexttwomonthsastheendvalueofthepartitionedtable
end_date=get_next_month_first_day(d2)
#getsubtablename
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语句处理
#多表操作
fortablein['tbl_game_android_step_log','tbl_game_android_game_log','tbl_game_android_pay_log']:
create_sub_table('test',table);
]
演示之前:
adsas=>select*frompg_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
(2rows)
演示之后:
adsas=>select*frompg_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
Partitionkey:RANGE(visit_time)
Partitions:tbl_game_android_step_log_2020_12FORVALUESFROM('2020-12-0100:00:00')TO('2021-01-0100:00:00'),
tbl_game_android_step_log_2021_01FORVALUESFROM('2021-01-0100:00:00')TO('2021-02-0100:00:00')
五、加入定时任务
到此这篇关于如何为PostgreSQL的表自动添加分区的文章就介绍到这了,更多相关PostgreSQL的表添加分区内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!