婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > 如何為PostgreSQL的表自動添加分區

如何為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')

五、加入定時任務

到此這篇關于如何為PostgreSQL的表自動添加分區的文章就介紹到這了,更多相關PostgreSQL的表添加分區內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • PostgreSQL LIST、RANGE 表分區的實現方案
  • PostgreSQL 創建表分區
  • 淺析postgresql 數據庫 TimescaleDB 修改分區時間范圍
  • 利用python為PostgreSQL的表自動添加分區
  • 淺談PostgreSQL 11 新特性之默認分區
  • PostgreSQL之分區表(partitioning)
  • PostgreSQL分區表(partitioning)應用實例詳解
  • PostgreSQL教程(三):表的繼承和分區表詳解
  • 淺談PostgreSQL表分區的三種方式

標簽:晉城 衡陽 株洲 錦州 烏海 珠海 來賓 蚌埠

巨人網絡通訊聲明:本文標題《如何為PostgreSQL的表自動添加分區》,本文關鍵詞  如,何為,PostgreSQL,的,表,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《如何為PostgreSQL的表自動添加分區》相關的同類信息!
  • 本頁收集關于如何為PostgreSQL的表自動添加分區的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 宁波市| 武冈市| 白朗县| 天水市| 金溪县| 连城县| 凤阳县| 平湖市| 改则县| 噶尔县| 宿迁市| 德阳市| 鄂州市| 呼伦贝尔市| 合水县| 澄城县| 通州市| 镇安县| 双鸭山市| 长沙市| 杨浦区| 南华县| 河源市| 克山县| 车险| 通河县| 色达县| 土默特左旗| 衡南县| 浦北县| 佛坪县| 陇川县| 南召县| 富川| 麦盖提县| 凉城县| 河间市| 土默特右旗| 安化县| 廊坊市| 莱阳市|