佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > 如何為PostgreSQL的表自動(dòng)添加分區(qū)

如何為PostgreSQL的表自動(dòng)添加分區(qū)

熱門(mén)標(biāo)簽:地方門(mén)戶網(wǎng)站 Linux服務(wù)器 AI電銷 呼叫中心市場(chǎng)需求 百度競(jìng)價(jià)排名 鐵路電話系統(tǒng) 服務(wù)外包 網(wǎng)站排名優(yōu)化

PostgreSQL 引進(jìn)“分區(qū)”表特性,解放了之前采用“表繼承”+ “觸發(fā)器”來(lái)實(shí)現(xiàn)分區(qū)表的繁瑣、低效。而添加分區(qū),都是手動(dòng)執(zhí)行 SQL。

演示目的:利用 python 來(lái)為 PostgreSQL 的表自動(dòng)添加分區(qū)。

python版本: python3+

pip3 install psycopg2

一、配置數(shù)據(jù)源

database.ini 文件:記錄數(shù)據(jù)庫(kù)連接參數(shù)

[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() 函數(shù)讀取database.ini文件并返回連接參數(shù)。config() 函數(shù)位于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

三、創(chuàng)建子表腳本

pg_add_partition_table.py 文件:其中 create_table函數(shù)是創(chuàng)建子表SQL。其中參數(shù)

參數(shù)名 含義
db 指向數(shù)據(jù)庫(kù)
table 主表
sub_table 正要新建的子表名
start_date 范圍分界開(kāi)始值
end_date 范圍分界結(jié)束值

#!/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()

四、執(zhí)行文件main.py

main.py:主文件;通過(guò)執(zhí)行main生成分區(qū)表。

示例:

#!/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');

上面示例單獨(dú)為表tbl_game_android_step_log;創(chuàng)建分區(qū);若多個(gè)表;用for語(yǔ)句處理

 # 多表操作
  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')

五、加入定時(shí)任務(wù)

到此這篇關(guān)于如何為PostgreSQL的表自動(dòng)添加分區(qū)的文章就介紹到這了,更多相關(guān)PostgreSQL的表添加分區(qū)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • PostgreSQL LIST、RANGE 表分區(qū)的實(shí)現(xiàn)方案
  • PostgreSQL 創(chuàng)建表分區(qū)
  • 淺析postgresql 數(shù)據(jù)庫(kù) TimescaleDB 修改分區(qū)時(shí)間范圍
  • 利用python為PostgreSQL的表自動(dòng)添加分區(qū)
  • 淺談PostgreSQL 11 新特性之默認(rèn)分區(qū)
  • PostgreSQL之分區(qū)表(partitioning)
  • PostgreSQL分區(qū)表(partitioning)應(yīng)用實(shí)例詳解
  • PostgreSQL教程(三):表的繼承和分區(qū)表詳解
  • 淺談PostgreSQL表分區(qū)的三種方式

標(biāo)簽:衡水 黃山 仙桃 崇左 蘭州 銅川 湖南 湘潭

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《如何為PostgreSQL的表自動(dòng)添加分區(qū)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    花莲县| 上高县| 安多县| 昭苏县| 乐亭县| 五峰| 南开区| 广河县| 霍城县| 马关县| 饶河县| 重庆市| 通榆县| 威宁| 乌海市| 屏山县| 营口市| 衡东县| 建宁县| 兴义市| 东光县| 金华市| 江安县| 娄底市| 得荣县| 罗城| 绵阳市| 彭水| 改则县| 乌鲁木齐县| 襄汾县| 喜德县| 名山县| 淮北市| 泾阳县| 原阳县| 千阳县| 安吉县| 青岛市| 四川省| 宁明县|