Partition table management method of distributed database

By implementing local scheduling and lightweight locking mechanisms in the distributed database, the problems of global lock blocking and deadlock during dynamic partition creation are solved, improving the high concurrency performance and availability of the system, and achieving efficient partition management and query consistency.

CN123178407APending Publication Date: 2026-11-27TIANJIN NANKAI UNIV GENERAL DATA TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611687456.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-10-29
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

Existing distributed databases rely on global strong locks for synchronization when dynamically creating and eliminating partitions. This leads to the blocking of system read and write operations in high-concurrency scenarios, resulting in a significant performance drop. Furthermore, when multiple nodes trigger concurrently, it is very easy to cause distributed deadlocks, which cannot meet the requirements of high performance and high availability.

Method used

By implementing localized scheduling and lightweight locking mechanisms between coordinating nodes and data nodes, partitioning operations are performed only locally and level 4 locks are used to avoid blocking by global level 8 locks. Combined with differentiated pre-built step size mechanisms and fault-tolerant retry mechanisms, the concurrency and consistency of partition creation are ensured.

Benefits of technology

Completely eliminates global lock blocking, significantly improves high-concurrency performance and availability, enables plug-and-play table creation, eliminates visibility traps in asynchronous completion, ensures distributed query consistency, and provides lightweight fault-tolerant self-healing capabilities, reducing operational complexity.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123178407A_ABST
    Figure CN123178407A_ABST
Patent Text Reader

Abstract

The application discloses a partition table management method of a distributed database and relates to the technical field of databases.The method comprises the following steps: obtaining and verifying a partition maintenance period and a life cycle attribute by analysis; obtaining continuous partition boundaries that need to be supplemented by one-time boundary calculation in a table building transaction, and encapsulating the partition boundaries in the same distributed global transaction with a main table building statement; registering a partition maintenance job at each node, and only applying a lightweight table lock that does not conflict with business read-write operations when locally executing an increase or decrease partition operation; executing a differentiated pre-building step mechanism, so that the number M of partitions that are pre-created by a data node is greater than the number N of partitions that are pre-created by a coordination node; and calculating an expiration threshold according to the life cycle attribute and deleting a historical partition.The application decouples data writing and structure changing, avoids global strong lock blocking, and improves system performance and availability in a high-concurrency scenario.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of database technology, and in particular relates to a method for managing partitioned tables in distributed databases. Background Technology

[0002] In existing distributed database systems, partitioned table technology is typically used to handle the storage and retrieval needs of massive amounts of data. The Interval dynamic partitioning mechanism allows the database to automatically create new partitions based on preset time or numerical intervals when data exceeding the currently defined partition range is inserted, greatly simplifying the maintenance costs for database administrators.

[0003] However, in a distributed architecture based on a Coordinator Node (CN) and Data Nodes (DN), the implementation of dynamically creating partitions via Intervals faces significant bottlenecks in distributed coordination and concurrency control. Specifically, during the generation and distribution phase of the distributed execution plan, the Coordinator Node needs to perform partition pruning based on globally consistent partition metadata (including partition boundaries, order, and consecutive partition numbers). Since distributed execution heavily relies on the continuity and consistency of partition numbers, the creation of dynamic partitions cannot be completed locally on a single node.

[0004] When out-of-bounds data is inserted into the system and triggers the Interval dynamic partition creation logic, the operation is essentially transformed into a cluster-wide structural change operation (DDL operation). To ensure strict synchronization of partition metadata across all nodes in the cluster, existing implementations typically require applying a high-level global exclusive lock (e.g., an 8-level lock, AccessExclusiveLock) to the partition table across the entire cluster.

[0005] This mechanism based on global strong lock synchronization has the following significant drawbacks in practical applications: First, in high-concurrency insertion scenarios, high-level locks will block all other read and write operations, causing a significant drop in system throughput, severe jitter in business response latency, and serious impact on system performance.

[0006] Secondly, since multiple coordinating nodes in a distributed cluster may simultaneously receive out-of-bounds data insertion requests, when multiple nodes concurrently trigger dynamic partition creation, distributed deadlocks are very likely to occur due to competition for distributed lock resources and the uncertainty of the locking order, which seriously threatens the availability of the database.

[0007] In summary, the existing interval dynamic partition creation mechanism based on global strong lock synchronization cannot meet the high performance and high availability requirements of distributed databases in high-concurrency scenarios. Therefore, a new technical solution is urgently needed to resolve the contradiction between dynamic partition expansion and global lock conflicts in distributed environments. Summary of the Invention

[0008] In view of this, the present invention aims to propose a partition table management method for distributed databases to solve the technical problems of existing distributed databases relying on global strong lock synchronization when dynamically creating and eliminating partitions, which leads to the blocking of system read and write operations and a significant decrease in performance in high-concurrency scenarios, and is prone to distributed deadlock when multiple nodes are triggered concurrently.

[0009] To achieve the above objectives, the technical solution of the present invention is implemented as follows: This invention provides a method for managing partitioned tables in a distributed database, applicable to a distributed cluster architecture comprising a global transaction manager, multiple coordinating nodes, and multiple data nodes, comprising the following steps: The data definition language statements are received by the coordination node, parsed and obtained as partition maintenance cycle and data lifecycle attributes, and the attributes are validated in multiple dimensions. In response to the table creation operation, within the table creation transaction, the user-declared partition start boundary is extracted and compared with the current system time. If there is a time difference, all consecutive partition boundaries that need to be filled are calculated through a one-time boundary calculation, and the generated catch-up filling operation is encapsulated in the same distributed global transaction as the main table creation statement. Each node in the distributed cluster registers and activates its corresponding partition maintenance job. The partition maintenance job runs in the background on each node. When adding or deleting partitions on the local node, only a lightweight table lock that does not conflict with the business read and write operations is applied to the target partition table, without triggering a distributed global transaction lock. The partition maintenance job executes a differentiated pre-built step size mechanism based on the node role. When executed on the coordinating node, it maintains the pre-creation of partitions with N partition maintenance cycle intervals. When executed on the data node, it maintains the pre-creation of partitions with M partition maintenance cycle intervals, where M is greater than N. Calculate the expiration threshold based on data lifecycle attributes, identify and delete historical partitions whose boundary values ​​are earlier than the expiration threshold.

[0010] Furthermore, the attributes undergo multi-dimensional validity checks, including: The target table for verification must be a range-partitioned table; The data type of the verification partition key must be strictly limited to timestamp type or timestamp type with time zone; The time interval parameters for partition maintenance cycle and data lifecycle are subject to mandatory range specification, requiring their values ​​to be between 1 hour and 1 year. Verify that existing partition definitions do not contain partitions with the maximum value.

[0011] Furthermore, all continuous partition boundaries that need to be filled are obtained through a one-time boundary calculation, specifically including: Construct a range partition start and end point definition state structure, where the start value is the user-declared initial partition start boundary and the step value is the partition maintenance cycle; The termination time for alignment is calculated using the following formula: ;in, This indicates the internally set alignment end time. Indicates the current system time. Indicates the partition maintenance cycle; Using the kernel's batch partition creation interface, a list of consecutive partition sequence definitions is generated in one go, with the start and end times as the range and the step size as the interval. Remove the last partition definition from the list of consecutive partition sequences to obtain a padded partition list with perfectly uniform boundaries, and then perform the partition creation operation based on the padded partition list.

[0012] Furthermore, the generated catch-up and completion operations are encapsulated within the same distributed global transaction as the primary table creation statement, specifically including: After the coordinating node generates the execution plan, it distributes the partition creation operation to all data nodes; Data nodes perform partition creation and record Redo logs locally; The coordinating node sends a prepare command to all data nodes. After receiving a successful prepare response from all data nodes, it sends a commit command to all data nodes. After receiving a successful commit response from all data nodes, the table creation command returns a successful response to the client.

[0013] Furthermore, the partitioned maintenance operation implements a differentiated pre-built step size mechanism based on the node role, specifically including: Scan the local system tables to obtain the timestamp of the largest existing partition boundary; Calculate the target alignment time starting from the timestamp of the largest partition boundary; Coordinating node calculation to ;in, This indicates the target alignment time of the coordinating nodes. Indicates the number of partitions pre-created by the coordinating node; Data node calculation to ;in, Indicates the target alignment time of the data node. Indicates the number of partitions pre-created for the data node; Starting from the timestamp of the largest partition boundary, the partition addition operation is continuously executed in steps of the partition maintenance cycle until the target alignment time is covered.

[0014] Furthermore, the expiration threshold time is calculated based on the data lifecycle attributes, specifically including: On the coordinating node side, the expiration threshold time is calculated as follows: ;in, This indicates the expiration threshold time on the coordinating node side. Indicates the data lifecycle; On the data node side, the expiration threshold is calculated at the following time: ;in, This indicates the expiration threshold time on the data node side. Deletion delay on the data node side; The data node's elimination time is more past than the coordinating node's, which means that partitions awaiting physical elimination are deleted first at the coordinating node.

[0015] Furthermore, distributed database partition table management methods also include fault tolerance retry and attribute reset mechanisms: If the new partitioning task fails, an exponential backoff retry mechanism with a fixed upper limit will be automatically triggered. The retry interval is calculated using the following formula: ;in, Indicates the waiting time. Indicates the base waiting time. Indicates the current number of retries; If the retries reach the limit and still fail, mark the task as failed and force it to be suspended. Receive attribute reset operations, atomically clean up old invalid task states, reset the retry counter, and restart the scheduled task based on the latest metadata state.

[0016] Based on the same concept, the present invention also provides a partition table management device for a distributed database, applied in a distributed cluster architecture including a global transaction manager, multiple coordinating nodes, and multiple data nodes. The partition table management device for the distributed database includes: The attribute parsing module is used to receive data definition language statements through the coordinating node, parse and obtain partition maintenance cycle and data lifecycle attributes, and perform multi-dimensional legality verification. The boundary catch-up module is used to respond to table creation operations. Within the table creation transaction, it extracts the user-declared partition start boundary and the current system time, calculates the continuous partition boundaries that need to be filled in through a one-time boundary calculation, and encapsulates the catch-up and filling operation and the main table creation statement in the same distributed global transaction. The task scheduling module is used to register and activate partition maintenance jobs on each node in the distributed cluster. When the job is executed locally, only a lightweight table lock that does not conflict with the business read and write operations is applied, and a differentiated pre-built step size mechanism is executed so that the number of partitions M pre-created by the data node is greater than the number of partitions N pre-created by the coordinating node. The lifecycle maintenance module is used to calculate the expiration threshold based on data lifecycle attributes and to identify and delete historical partitions.

[0017] Based on the same concept, the present invention also provides an electronic device, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement a partition table management method for a distributed database.

[0018] Based on the same concept, the present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements a method for managing partitioned tables in a distributed database.

[0019] Compared with existing technologies, the partition table management method for distributed databases described in this invention has the following advantages: 1. Completely eliminate global lock blocking, significantly improving high-concurrency performance and availability: This invention, through localized scheduling and a low-level locking mechanism, downgrades the global level 8 exclusive lock required for traditional dynamic partition creation to a node-local level 4 lock (ShareUpdateExclusiveLock). Since level 4 locks do not conflict with regular read operations (level 1 locks) and write operations (level 3 locks), it fundamentally decouples data writing from structural changes, effectively avoiding system throughput degradation and distributed deadlock problems caused by strong locking in high-concurrency scenarios.

[0020] 2. Achieve plug-and-play table creation and eliminate the visibility trap of asynchronous completion: This invention designs... The alignment and truncation algorithm, with its time complexity optimized, combined with the kernel's underlying batch partition creation interface, bypasses the redundant overhead of the SQL parsing engine, reducing the completion time for massive historical partitions from hours to seconds. Simultaneously, a strong binding mechanism encapsulates the completion operation and the main table creation statement within the same distributed global transaction, ensuring strict consistency between metadata visibility and business availability, and preventing data write failures caused by users not being able to find the target partition during the initial table creation phase.

[0021] 3. Ensure distributed query consistency and eliminate the risk of metadata synchronization gaps: This invention innovatively designs a differentiated pre-built step size mechanism, which sets the number of pre-built partitions for data nodes (DNs). The number of pre-built partitions is greater than the number of coordinating nodes (CNs). (Right now A partition buffer was constructed. This mechanism ensures that as long as the execution plan can be successfully routed on the CN side, the target partition will definitely exist after it is sent to the DN, completely eliminating the risk of query errors such as "target partition does not exist" caused by distributed node clock skew or execution latency.

[0022] 4. Provides lightweight fault tolerance and self-healing capabilities, reducing operational complexity: This invention integrates an exponential backoff retry mechanism and an attribute reset repair mechanism. When extreme anomalies cause task failure, database administrators do not need to manually intervene in the underlying complex scheduling record tables. They can simply use standard attribute reset commands to atomically clean up invalid states and restart the task, significantly reducing the operational costs of distributed databases during the fault recovery phase.

[0023] 5. Achieve automated management throughout the entire lifecycle and ensure concurrency safety: This invention realizes automated physical removal of expired partitions through the TTL attribute and designs a DN-side deletion delay mechanism ( This ensures that partitions slated for retirement are deleted first on the CN side, avoiding errors caused by routing to already deleted partitions. Simultaneously, by combining time-domain physical isolation with Multi-Version Concurrency Control (MVCC) isolation mechanisms, the safety of partition creation and retirement operations during concurrent execution is guaranteed. Attached Figure Description

[0024] The accompanying drawings, which form part of this invention, are used to provide a further understanding of the invention. The illustrative embodiments of the invention and their descriptions are used to explain the invention and do not constitute an undue limitation of the invention. In the drawings: Figure 1 This is a schematic diagram of a distributed automatic partitioning management system architecture provided by an embodiment of the present invention; Figure 2 This is a schematic diagram of a partition boundary alignment and truncation algorithm provided in an embodiment of the present invention; Figure 3 This is a schematic diagram of the partition status of a coordination node and a data node provided in an embodiment of the present invention. Detailed Implementation

[0025] It should be noted that, unless otherwise specified, the embodiments and features described in the present invention can be combined with each other.

[0026] In the description of this invention, it should be understood that the terms "center," "longitudinal," "lateral," "upper," "lower," "front," "rear," "left," "right," "vertical," "horizontal," "top," "bottom," "inner," and "outer," etc., indicating orientations or positional relationships based on the orientations or positional relationships shown in the accompanying drawings, are only for the convenience of describing the invention and simplifying the description, and do not indicate or imply that the device or element referred to must have a specific orientation, or be constructed and operated in a specific orientation, and therefore should not be construed as a limitation of the invention. Furthermore, the terms "first," "second," etc., are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of indicated technical features. Thus, a feature defined with "first," "second," etc., may explicitly or implicitly include one or more of that feature. In the description of this invention, unless otherwise stated, "a plurality of" means two or more.

[0027] In the description of this invention, it should be noted that, unless otherwise explicitly specified and limited, the terms "installation," "connection," and "linking" should be interpreted broadly. For example, they can refer to a fixed connection, a detachable connection, or an integral connection; they can refer to a mechanical connection or an electrical connection; they can refer to a direct connection or an indirect connection through an intermediate medium; and they can refer to the internal connection of two components. Those skilled in the art will understand the specific meaning of the above terms in this invention based on the specific circumstances.

[0028] The present invention will now be described in detail with reference to the accompanying drawings and embodiments.

[0029] like Figures 1 to 3 As shown, the partition table management method for distributed databases, applied to a distributed cluster architecture containing a global transaction manager, multiple coordinating nodes, and multiple data nodes, includes the following steps: The data definition language statements are received by the coordination node, parsed and obtained as partition maintenance cycle and data lifecycle attributes, and the attributes are validated in multiple dimensions. In response to the table creation operation, within the table creation transaction, the user-declared partition start boundary is extracted and compared with the current system time. If there is a time difference, all consecutive partition boundaries that need to be filled are calculated through a one-time boundary calculation, and the generated catch-up filling operation is encapsulated in the same distributed global transaction as the main table creation statement. Each node in the distributed cluster registers and activates its corresponding partition maintenance job. The partition maintenance job runs in the background on each node. When adding or deleting partitions on the local node, only a lightweight table lock (such as a level 4 lock ShareUpdateExclusiveLock) that does not conflict with the business read and write operations is applied to the target partition table, without triggering a distributed global transaction lock. The partition maintenance job executes a differentiated pre-built step size mechanism based on the node role. When executed on the coordinating node, it maintains the pre-creation of partitions with N partition maintenance cycle intervals. When executed on the data node, it maintains the pre-creation of partitions with M partition maintenance cycle intervals, where M is greater than N. Calculate the expiration threshold based on data lifecycle attributes, identify and delete historical partitions whose boundary values ​​are earlier than the expiration threshold.

[0030] The specific embodiments of the present invention are as follows: I. System Overall Architecture and Deep Implementation of Localized Locking Mechanism like Figure 1 As shown, the distributed automatic partitioning management system architecture provided in this embodiment includes a Global Transaction Manager (GTM), coordinating nodes CN1 and CN2, and data nodes DN1 and DN2. The Global Transaction Manager (GTM) is used to allocate global transaction identifiers for distributed transactions and distribute global snapshots; it does not handle the granting, maintenance, or upgrading of table-level locks. In this embodiment, the Global Transaction Manager (GTM) appears externally as a special coordinating node and follows the rules of coordinating nodes regarding partition maintenance job registration, local background execution, local locking, and differentiated pre-built step sizes. Therefore, the partition maintenance job-related components and operations of the coordinating node mentioned below all cover the GTM; however, the GTM does not receive SQL requests from clients and therefore does not participate in the cross-node locking broadcast initiated by the coordinating node as described below. The coordinating node CN is responsible for receiving SQL requests from clients, performing syntax parsing, optimizer rewriting, and generating distributed execution plans. The data nodes DN are responsible for actual data storage and local execution.

[0031] In the architecture design of this invention, each node independently maintains a background scheduling task, namely the pg_job module in the diagram. For example... Figure 1 As shown, the pg_job module within each node runs independently locally, indicated by a self-looping arrow. The key to this design is that when adding or deleting partitions, the operation is performed only locally, requiring only a level 4 lock (ShareUpdateExclusiveLock) to be applied to the local table, without triggering a global data definition language (DDL) lock (level 8 lock).

[0032] like Figure 1As indicated by the bottom label, local add or delete partition DDL operations only use level 4 locks. To fully illustrate the superiority of this design, a deeper analysis combined with the kernel lock conflict matrix is ​​necessary. In the database kernel, the lock level determines the strictness of concurrency control. Level 1 locks are AccessShareLocks, typically used for read operations such as SELECT statements. Level 3 locks are RowExclusiveLocks, typically used for Data Manipulation Language (DML) operations such as INSERT, UPDATE, and DELETE statements. Level 8 locks are AccessExclusiveLocks, a global exclusive lock that blocks all other operations, including reads and writes.

[0033] Table 1 shows the kernel lock conflict matrix, which details the conflict relationships between different lock levels.

[0034] Table 1 This embodiment uses a Level 4 lock, ShareUpdateExclusiveLock. According to the lock conflict matrix shown in Table 1, Level 4 locks do not conflict with Level 1 locks. This means that when a background task performs a partition addition operation locally, read operations on the business side can proceed normally without being blocked. Level 4 locks also do not conflict with Level 3 locks, meaning that when a background task performs a partition addition operation locally, write operations on the business side can proceed normally without being blocked. Level 4 locks only conflict with Level 4 locks, Level 5 locks (ShareLock), Level 6 locks (ShareRowExclusiveLock), Level 7 locks (ExclusiveLock), and Level 8 locks (AccessExclusiveLock). This architecture fundamentally decouples data writing from structural changes. When the background automatically maintains partitions, business read and write operations are not blocked, effectively avoiding the strong locking and cluster-wide blocking problem caused by holding Level 8 locks in traditional solutions, and significantly improving the system's concurrent processing capabilities.

[0035] In a preferred embodiment of the present invention, to clarify why the global exclusive lock (i.e., the level 8 lock AccessExclusiveLock, also known as the aforementioned distributed global transaction lock or global DDL lock) will not be implicitly triggered in this embodiment, the interaction rules between the distributed transaction manager and the local lock manager are explained as follows.

[0036] 1. The generation path of a global exclusive lock In existing distributed database implementations, global exclusive locks are not automatically generated by the Global Transaction Manager (GTM) after detecting table structure changes. GTM is used to assign global transaction identifiers and distribute global snapshots for distributed transactions; it does not handle the granting, maintenance, or upgrading of table-level locks, and therefore lacks a mechanism for "automatically detecting table structure changes and upgrading to a global lock." The actual generation path of a global exclusive lock is as follows: the coordinating node (CN) that receives the structure change (DDL statement) generates a distributed execution plan and then explicitly broadcasts a lock request to all coordinating nodes (CN) and all data nodes (DN) within the cluster via the internal connection pool (Pooler). Only after each node's local lock manager (LockManager) successfully applies an 8-level lock and returns a successful lock response can the DDL statement continue execution. If any node fails to acquire the lock, the coordinating node that initiated the broadcast sends an unlock command to the successfully locked nodes and rolls back the DDL statement. Therefore, the application of a global exclusive lock relies entirely on the cross-node lock broadcast initiated by the coordinating node; this broadcast is the only path for the global lock to propagate within the cluster.

[0037] It should be noted that since GTM does not receive SQL requests from clients, it will not be the initiator of the aforementioned cross-node lock broadcast; at the same time, the partition maintenance jobs of each node (including GTM) are only run locally and only apply local level 4 locks, so no node will initiate, receive or upgrade a global exclusive lock due to the partition maintenance job.

[0038] 2. Methods for blocking the global lock propagation path in this embodiment This embodiment restricts the operation of adding and deleting partitions during runtime to be executed locally on the node that triggers the operation. The specific means of blocking the propagation of global locks include the following three aspects.

[0039] Firstly, the execution path is localized. After the partition maintenance job is derived from or distributed to the job worker thread by the job scheduler thread, it directly triggers the pre-compiled system stored procedure and reuses the kernel's batch partition creation interface to construct partition metadata locally. This avoids repeated parsing by the SQL parsing engine and avoids the execution path where the coordinating node generates a distributed execution plan and then distributes it to remote nodes via the internal connection pool. Since no DDL distribution connection to other nodes is established from the beginning, cross-node lock broadcasting does not occur, and the propagation path of the global exclusive lock is cut off at the source.

[0040] Secondly, the lock scope is localized. Each node's LockManager only maintains the lock request queue within its own node. Its lock conflict determination is only completed within the scope of its own node based on the kernel lock conflict matrix shown in Table 1. It is neither aware of the lock holding status of other nodes nor reports the local lock status to other nodes. Therefore, there is no entry point or propagation channel for the implicit upgrade from a local level 4 lock to a global level 8 lock.

[0041] Third, the determinism of partition metadata derivation. Each node independently derives the required partition boundaries and names using the same partition maintenance period, the same alignment truncation algorithm, and the auto_pYYYYMMDDHH naming rule uniquely determined by the partition boundary timestamp, and performs idempotency checks before creation. Therefore, nodes can obtain continuous and consistent partition numbers and boundary sequences without communicating with each other. While meeting the requirements of distributed execution for the continuity and consistency of partition numbers, the partition creation operation is localized, without having to sacrifice metadata synchronization by applying a global exclusive lock.

[0042] 3. Locking and releasing process during local execution When a partition maintenance job performs add or delete partition operations locally, its locking and releasing process is as follows: the LockManager of this node applies a local level 4 lock, ShareUpdateExclusiveLock, to the target partition table; partition metadata is written and logged within the local transaction; RelationBuildDesc is called to refresh the relcache; the local transaction is committed; and the LockManager releases the level 4 lock. The lock scope of the entire process is limited to this node, and the holding duration of the level 4 lock is the execution duration of the local transaction. According to the kernel lock conflict matrix shown in Table 1, the level 4 lock does not conflict with the level 1 lock AccessShareLock held by the business read operation, the level 2 lock RowShareLock held by the business lock read operation, and the level 3 lock RowExclusiveLock held by the business write operation. It only conflicts with level 4 locks, level 5 locks ShareLock, level 6 locks ShareRowExclusiveLock, level 7 locks ExclusiveLock, and level 8 locks AccessExclusiveLock. Therefore, the partition maintenance job can be executed concurrently with the read and write operations of the foreground business.

[0043] II. Specific Implementation of Partition Attribute Parsing and Configuration Management Component This component is located in the coordinating node of the database kernel and is mainly responsible for intercepting input DDL statements, semantic parsing, multi-dimensional validity verification, and persistent management of globally maintained attributes.

[0044] 1. Syntax Expansion and Attribute Settings This embodiment extends the SQL syntax parse tree of the database kernel, supporting the declaration of partition maintenance period and data lifecycle time (ttl) in the table-level options RelOptions.

[0045] After receiving an SQL statement, the database kernel's parser first performs lexical analysis, breaking the statement down into a token stream. Then, the syntax parser constructs an Abstract Syntax Tree (AST) based on the expanded syntax rules. During this process, the parser identifies the PERIOD and TTL parameters in the WITH clause and attaches them as nodes to the table definition nodes of the AST. Specifically, a new options list is added to the CreateStmt structure to store key-value pairs. The key is either period or ttl, and the value is a constant expression of type Interval.

[0046] The typical table creation syntax execution flow is as follows: Create table t1, containing fields id (integer type), value (text type), and ts (timestamp type). Table options are set to a period of 1 day and a lifespan of 7 days. The partitioning strategy is range partitioning based on the ts field. The initial partition p1 has values ​​less than August 1, 2025.

[0047] A typical table modification syntax execution flow is as follows: Modify table t1, setting the period to 2 days. The parser will then recognize the AlterTableStmt statement, locate the SetRelOptions clause, and update the corresponding RelOptions node in the AST. The system will serialize the new period value and update it to the reloptions field of the system table pg_class, achieving persistent storage of the attribute. This persistence mechanism ensures that the partition management strategy remains effective after a database restart, without requiring reconfiguration.

[0048] 2. Semantic and Constraint Validation Upon receiving the above request, the component will perform strict, strong constraint validation on the structure of the target table and the validity of the time intervals of the input parameters during the kernel parser and semantic analysis Analyze phases. The core validation rules include the following four aspects: First, there are limitations on the partitioning strategy. The target table for validation must be a range-partitioned table. Since the core logic of this system is based on linear expansion within a time window, non-range partitions, such as hash partitions or list partitions, do not possess the semantic meaning of continuously increasing boundaries. Therefore, they will be intercepted by the system and an error will be returned. The semantic analyzer will check the partitioning strategy node in the AST; if it is not of type RANGE, an exception will be thrown, informing the user that only range partitions are supported.

[0049] Second, partition key type restrictions. The data type of the partition key must be strictly limited to timestamp type TIMESTAMP or timestamp type TIMESTAMP WITH TIME ZONE with time zone, to ensure absolute consistency of partition boundary derivation in the time-series data stream. The system will query the system directory table pg_type to obtain the partition key type OID and compare it with whether it belongs to the timestamp type family. If the types do not match, execution will be refused.

[0050] Third, time span threshold limitations. The time interval parameters set for `period` and `ttl` are subject to mandatory range reduction, requiring their values ​​to be between 1 hour and 1 year. If the value is too small, such as at the minute level, it will cause the underlying scheduling tasks to wake up too frequently, resulting in unacceptable system overhead; if the value is too large, such as decades, it defeats the practical purpose of automated lifecycle management. The validation logic converts the input `Interval` type parameter into microseconds and determines whether it falls between 3600000000 microseconds and 31536000000000 microseconds. If it exceeds this range, an error message is returned. Those skilled in the art should understand that the above time thresholds are merely examples and can be dynamically adjusted according to cluster performance in actual applications.

[0051] Fourth, boundary constraints. The system checks existing partition definitions to ensure they do not contain a MAXVALUE partition. This is because a MAXVALUE partition receives all data exceeding normal boundaries; its existence would cause problems with subsequent partition routing. The system iterates through the partition metadata of the current table, checking for partition definitions with `bound_type` set to MAXVALUE. If found, the user is prompted to delete the MAXVALUE partition before enabling automatic partition management.

[0052] 3. Dynamic calculation of execution time window To avoid system resource exhaustion caused by a large number of partition table maintenance tasks occurring at the same time, or DML operations being blocked during peak business periods, this component supports dynamically setting the expected execution time window for background tasks through the globally unified database configuration parameter default_apm_maintenance_time.

[0053] When parsing attributes, the component evaluates the global configuration parameter GUC: if a valid parameter exists, the task trigger time is overridden according to the specified time window; if not configured, the component will capture the system time of the current table creation or modification transaction as the base time for each future loop partition expansion. The system obtains the current timestamp by calling the GetCurrentTimestamp function, serializes it, and stores it in global shared memory or a system table for subsequent scheduling components to read. This mechanism allows database administrators to schedule maintenance tasks during off-peak business hours in the early morning, thereby minimizing the impact on business operations.

[0054] III. Specific Implementation of the Partition Boundary Catching Component This component focuses on resolving the issue of historical partition gaps encountered during the table creation and initialization phase. Under asynchronous maintenance mechanisms, there is a time lag between the visibility of the table structure and the availability of business operations. This component ensures plug-and-play table creation through kernel-level mathematical derivation and the construction of a one-time operation sequence.

[0055] 1. One-time boundary calculation and uniform alignment algorithm Within the table creation transaction, this component automatically extracts the user-declared partition start boundary and compares it with the current system time. If a time difference exists, i.e. the start time is earlier than the current time, the component will directly perform a one-time mathematical calculation at the kernel level to determine all the consecutive partition boundaries that need to be padded.

[0056] To quickly generate these partitions at the underlying level, the component reuses the kernel's internal batch partitioning interface `transformRangePartStartEndStmt`. When it detects that a gap in a partition needs to be filled, the component constructs a range partition start and end point definition state structure `RangePartitionStartEndDefState` in memory.

[0057] The start value is assigned to the user-declared initial partition start boundary, which is the user-defined upper boundary of the partition table, lowBound.

[0058] The endValue is assigned the calculated alignment end boundary value.

[0059] The step size value everyValue is assigned the user-declared partition maintenance period.

[0060] The component then encapsulates this structure into a list `PartitionList` and passes it as an input parameter to the `transformRangePartStartEndStmt` interface. This function reads `PartitionList` and, at the kernel level, splits the coarse-grained `START / END / EVERY` definitions and converts them into multiple specific range partition definitions, thereby generating all the necessary partition definitions in batches at the kernel level.

[0061] In real-world business scenarios, the total time difference that needs to be made up is often not divisible by the set period. For example, the user declares the starting partition boundary as 00:00 on May 1, 2026, and the current system time is 00:00 on May 2, 2026, resulting in a total time difference of 24 hours. Assume the user sets the period to 5 hours.

[0062] If we directly use the current time as the end for padding, dividing 24 hours by 5 hours leaves a remainder of 4 hours, resulting in the last generated partition spanning only 4 hours. This uneven partitioning disrupts statistical analysis and data routing patterns based on time periods. If, to ensure uniformity, we start the recursive calculation from the beginning based on the period, the algorithm's time complexity will degenerate into... ,in This represents the number of partitions that need to be filled in.

[0063] This embodiment designs a An alignment truncation algorithm with low time complexity. Instead of using the current time as the end point for batch building, the component calculates an aligned termination time during computation.

[0064] The mathematical expression is as follows: ; in, This indicates the internally set alignment end time. Indicates the current system time. This indicates the partition maintenance cycle set by the user.

[0065] In the example above, the internal end time is set to 5:00 AM on May 2, 2026. This is achieved through a start / end mechanism. After generating a list of all consecutive partition sequence definitions, the component directly removes the last partition definition from the list. With this algorithm, since the termination time is one cycle longer than the current time, removing the last definition ensures that the remaining partitions in the list completely cover the current time and have a uniform span, eliminating the need for additional judgment logic or spending extra time creating and then deleting them.

[0066] like Figure 2As shown, the upper part illustrates the case where the end point is directly set to the current time 05-02 00:00, resulting in four 5-hour blocks and one 4-hour block, leading to an uneven distribution of the last block. The lower part shows the case of the current algorithm, where the end point extends to the current time plus the period, i.e., 05-02 05:00. This results in five 5-hour blocks and one 4-hour block. The algorithm calculates the true end point END as 05-02 01:00 and marks the last 4-hour block as discarded. This ensures that all retained partitions are standard 5-hour blocks.

[0067] 2. Avoid the overhead of massive repetitive parsing. This component skips the repetitive overhead of the SQL parsing engine by directly constructing the underlying metadata sequence during the table creation phase. When faced with the need to complete the data for tens of thousands of partitions, this component can complete the process in seconds to minutes.

[0068] Test data shows that on three servers with 72-core CPUs and 256GB of memory, creating a partition table that requires two years of data patching and has a one-hour timeframe, and patching 17,550 partitions, took only 21 seconds. In contrast, the traditional solution relies on background tasks to execute ALTER TABLE ADD PARTITION statements one by one, with each statement undergoing lexical analysis, syntax analysis, and execution planning, taking 37 minutes and 4 seconds. This solution directly manipulates metadata through a low-level C language interface, avoiding the overhead of the SQL layer and significantly improving system initialization efficiency.

[0069] 3. Atomicity initialization aligned with metadata availability The asynchronous completion scheme has a fatal visibility trap: if the intermediate partitions have not been created after the table creation is completed, the user will get an error when inserting data.

[0070] This component uses a strong binding mechanism to encapsulate the generated catch-up and completion operations within the same distributed global transaction as the main table creation statement. The table creation command will only return a success message to the client after the historical gaps have been completely filled to the current time and the partition metadata of all data nodes in the cluster is synchronized.

[0071] Specifically, after generating the execution plan, the coordinating node (CN) distributes the partition creation DDL operations to all data nodes (DNs). The DN nodes perform partition creation locally and record Redo logs. Subsequently, the coordinating node (CN) sends a Prepare command to all data nodes (DNs). Upon receiving successful prepare responses from all DN nodes, the CN sends a Commit command to all DN nodes. Upon receiving successful commit responses from all DN nodes, the table creation command returns a success message to the client. This mechanism ensures strict consistency between metadata visibility and business availability, preventing users from encountering data write failures during the initial table creation phase.

[0072] IV. Specific Implementation of the Task Scheduling Component This component is responsible for transforming static table attributes into dynamic distributed scheduled tasks, and it adopts a design philosophy of local scheduling and global fault tolerance.

[0073] 1. Distributed task registration and localized maintenance During table creation or attribute modification transactions, this component automatically connects to the system-level internal scheduling engine pg_job based on the persistence period, lifecycle, and baseline time. This component registers and activates the corresponding partition maintenance job on each node within the cluster.

[0074] In practice, the component inserts a record into the pg_job system table, which includes fields such as job name, execution function name, execution interval (period), and next execution time.

[0075] These jobs run in the background on each node. The resident job scheduler thread periodically scans the system table pg_job. When it detects that a maintenance job has reached its next execution time, the job scheduler thread derives or dispatches it to an independent job worker thread to trigger a pre-compiled system stored procedure, thereby avoiding high-level lock contention during cross-node synchronization.

[0076] Each node's pg_job runs independently without interfering with others, achieving true distributed scheduling. This localized maintenance mechanism not only reduces network communication overhead but also improves the overall stability of the system.

[0077] 2. Step redundancy between CN and DN Because the scheduling trigger times of each node may have slight clock skew or execution delays, it cannot be guaranteed that all nodes will complete partition creation at the same absolute moment. If the coordinating node has completed the creation of the new partition and generated an execution plan, but the partitioning task of that node has not yet been completed when the data is sent to the data node, it will lead to an execution error indicating that the target partition does not exist.

[0078] To address the aforementioned distributed synchronization gap issue, this component is designed with a differentiated pre-built step size mechanism.

[0079] Coordinator node sliding window: When a scheduled task is executed on the coordinator node, it will always maintain a pre-created window from the current time forward. Partitions with a periodic interval, such as the default. The value is equal to 30. Those skilled in the art can adjust this value according to the actual business concurrency.

[0080] Data node sliding window: When a scheduled task is executed on a data node, it maintains the backward pre-creation mechanism. Partitions with a periodic interval, such as the default. It equals 35, and .

[0081] By setting The system constructs a buffer for the step-size redundancy area. Since the data nodes always have more partition reserves than the coordinating node, it ensures that as long as the execution plan can be pruned and routed to the target partition at the coordinating node, the target partition will necessarily already exist after the plan is sent to the data nodes.

[0082] like Figure 3 As shown, after the current timeline, the coordinating node partition status has been maintained for... Each partition. The data node partition status is maintained. One partition. The length of each partition is greater than Each partition has a set of data nodes, with the extra space serving as a buffer. Since user queries always originate from the coordinating node, under normal circumstances, even with execution latency, partitions that can be successfully routed on the coordinating node will also exist on the data nodes. This step-size redundancy mechanism is crucial for ensuring distributed query consistency.

[0083] 3. Fault tolerance, retry, and resource control mechanisms This component integrates the kernel scheduling engine's native fault tolerance capabilities.

[0084] Once a failed new partitioning task is detected, the system will not give up immediately, but will automatically trigger an exponential backoff retry mechanism with a fixed limit, such as 15 times. Those skilled in the art should understand that this limit can be dynamically configured according to the system load.

[0085] The mathematical expression for the retry interval is as follows: ; in, Indicates the waiting time. Indicates the base waiting time. Indicates the current number of retries. The value range is 0 to 14, meaning a maximum of 15 retries.

[0086] If execution still fails after 15 retries, the system will consider the table to be in an abnormal state, mark the pg_job task as failed, and forcibly suspend it. This mechanism effectively prevents deadlock loops caused by frequent errors and protects system resources from being exhausted by invalid tasks. It should be noted that tasks marked as failed and forcibly suspended are not tasks in the Active state, and therefore will not be automatically restarted by the kernel background process after a cluster restart. They must be resumed through the attribute reset operation described below.

[0087] 4. Attribute reset and lightweight repair mechanism After the cluster restarts, the kernel background process will automatically start all tasks in the Active state.

[0088] When a node recovers after a period of downtime, the local scheduling task wakes up and directly triggers the maximum boundary detection logic: It scans the local system table `pg_partition` to obtain the local maximum partition boundary timestamp `Max_Partition_Boundary`. If it finds that the timestamp lags behind the current time plus... Double the period (i.e.) If the maximum partition boundary timestamp is reached, the automatic catch-up logic will be triggered. Starting from the partition maintenance cycle, the partition addition operation will be continuously executed until the target alignment time is covered.

[0089] Even if a task fails due to extreme anomalies, the database administrator (DBA) does not need to manually intervene in the underlying record tables. They only need to execute standard table modification statements on the table, removing the `period` and `ttl` attributes using the `RESET` command and then resetting them using the `SET` command. Upon detecting the attribute reset operation, the component atomically cleans up old, invalid task states, resets the retry counter, and restarts the scheduled task based on the latest metadata state. This lightweight recovery mechanism significantly reduces operational costs.

[0090] 5. Atomic rollback and compensation mechanism for single-node operation failure Because adding or deleting partitions during runtime is executed independently on each node and does not enter a distributed global transaction, a failure of a local operation on any node will not create a distributed transaction state that requires rollback on other nodes, nor does it require cross-node compensation coordination. Depending on the stage of the operation, it can be divided into the following two scenarios.

[0091] (1) Table creation phase: Overall rollback within a distributed global transaction The catch-up and completion operations during the table creation phase are encapsulated within the same distributed global transaction as the main table creation statement, and are coordinated uniformly by the coordinating node CN according to the two-phase commit protocol. If a data node DN fails to create a partition locally, or returns a preparation failure response after receiving a Prepare instruction, the coordinating node CN does not send a Commit instruction to any data node. Each data node rolls back its local transaction according to the two-phase commit protocol. The locks applied locally are automatically released by the lock manager LockManager when the transaction ends. Unused partition metadata and physical files are automatically cleaned up by the local garbage collection mechanism, and the table creation command returns a failure to the client. Since the target table is a newly created table at this time and there is no business read / write access, this rollback will not affect the business, nor will it cause table structure anomalies due to some nodes having committed while others have rolled back.

[0092] (2) Runtime: Atomic rollback of local transactions and absorption of step redundancy Every partition addition or deletion operation triggered by the partition maintenance job during runtime is completed locally on the node as an independent local transaction. When a node (e.g., a data node DN) experiences a timeout for a Level 4 lock request or a partition creation failure due to transient resource constraints, the operation strictly adheres to the atomicity of local transactions: only the local transaction state of the node is marked as rollback (marked as Abort in CLOG). Partition metadata and physical files that have not yet taken effect during this operation are automatically cleaned up by the node's local garbage collection mechanism, leaving no dirty data on the node; the Level 4 locks already applied locally are automatically released by the LockManager upon the end of the local transaction. Since this operation never enters a distributed global transaction or is not broadcast to other nodes, there is no distributed transaction state that needs to be rolled back, nor is it necessary to send distributed rollback instructions to other normal nodes. The partition maintenance jobs and business transactions of other nodes are unaffected.

[0093] For such brief failures of a single node, the differentiated pre-construction step size mechanism between the coordinating node and data nodes ensures that it does not affect business operations. Taking the default M=35 and N=30 (i.e., a difference of 5 period intervals) as an example, suppose a data node DN1 fails to create the partition corresponding to the last period interval in this batch pre-construction (i.e., the partition of the 35th period interval) due to an anomaly during a scheduling process, while the partitions corresponding to the previous 1st to 34th period intervals have all been successfully created and committed locally. In this case, the local maximum partition boundary timestamp Max_Partition_Boundary of this data node will still advance to the specified time. It is significantly ahead of the target alignment time of the coordinating node. Since user queries always originate from the coordinating node, the execution plan that the coordinating node can successfully route through partition pruning will always have a target partition boundary no later than [date missing]. Therefore, after the execution plan is sent to the aforementioned data nodes, the target partition already exists physically, and there will be no execution error of "target partition does not exist". That is, the failure of a single node creation is absorbed by the step-size redundancy area between M and N, without the need for immediate cross-node compensation.

[0094] More generally, as long as the local partition boundary lag caused by the failure does not exceed MN cycle intervals, the lag can be completely absorbed by the step size redundancy area; if the lag exceeds the redundancy range, it will be made up by the following retry mechanism and maximum boundary detection catch-up mechanism.

[0095] (3) Self-healing and manual repair of failed nodes To address the aforementioned failure points, this embodiment provides two levels of self-healing methods and one level of manual repair methods.

[0096] Level 1, Exponential Backoff Retry. The local scheduling engine pg_job on this node automatically triggers a fixed upper limit (e.g., 15 times) of exponential backoff retries, with a retry interval of [time missing]. The value of k ranges from 0 to 14. Because the partition addition operation performs an idempotency check before execution, partitions with the same name or boundary that have been successfully created are automatically skipped during retries, so missing partitions can be silently filled in during subsequent retries.

[0097] The second level involves maximum boundary detection and batch catching up. If the node experiences a crash and restart, all tasks in the Active state will be automatically restarted by the kernel background process after the cluster restarts. When the node's local scheduled task is awakened, the maximum boundary detection logic will be triggered directly, which involves scanning the local system table pg_partition to obtain the local maximum partition boundary timestamp Max_Partition_Boundary and determining whether it is behind the target alignment time. If it lags behind, starting from the timestamp of the largest partition boundary, the partition maintenance cycle is used as the step size to continuously perform the add partition operation in a batch on the local machine until the target alignment time is covered, thereby automatically catching up with and filling in all the missing period interval partitions.

[0098] The third level involves manual repair of attribute resets. If the retries reach the limit and still fail, the task is marked as failed and forcibly suspended. At this point, the task is not considered an Active task and will not be automatically restarted by the kernel background process. The database administrator (DBA) only needs to execute standard table modification statements for the table, remove the period and ttl attributes using the RESET command, and then reset the period and ttl attributes again using the SET command. Upon detecting the attribute reset operation, the component atomically cleans up the old invalid task states, resets the retry counter, and restarts the scheduled task based on the latest metadata state. The restarted task will also perform the aforementioned maximum boundary detection and batch catch-up to restore the partition boundary of the node to the target alignment time.

[0099] V. Specific Implementation of Lifecycle Operation and Maintenance Components This component is the system's executor, responsible for automatically performing on-demand expansion and expiration of partitions according to preset strategies throughout the entire lifecycle of the partition table.

[0100] 1. Backend partition asynchronous pre-build mechanism This component performs maintenance tasks based on the frequency of wake-up by the scheduling component and a preset time window. It utilizes distributed redundancy step sizes to downgrade the lock granularity from a cluster-wide strong lock to a node-local lock.

[0101] Low-level locking mechanism: This adds a local execution of partitioning operations on each node, without triggering distributed global transaction locks. This component only needs to apply level 4 locks to the target partitioned table.

[0102] The execution logic is as follows: The first step is maximum boundary detection. Scan the local system table pg_partition to obtain the timestamp of the maximum partition boundary currently existing in the partition table, Max_Partition_Boundary.

[0103] The second step is to calculate the target alignment time. Starting from the maximum boundary, the target alignment time is calculated based on the node roles.

[0104] Coordination node calculations up to: ; Data nodes are calculated to: ; in This ensures that the partitioned storage of data nodes is superior to that of the coordinating node.

[0105] The third step is batch linear construction. Starting from the maximum boundary, the partitioning operation is continuously performed with the period as the step size until the target time is covered.

[0106] Step 4: Naming Rules. Use the format auto_pYYYYMMDDHH for naming. When the period is not an integer number of hours (e.g., 2.5 hours), the partition name should be the boundary time rounded up. For example, if the boundary is 2026-05-01 12:30:00, the partition name would be auto_p2026050113.

[0107] Step 5: Idempotency check. Before creation, the component retrieves system metadata. If a partition with the same name or boundary already exists, it is automatically skipped.

[0108] Step 6: Refresh the cache. When the local partition is created, RelationBuildDesc is called to refresh the relcache. The optimizer will then be able to detect the existence of the new partition through the reconstructed relcache during the next query parsing.

[0109] 2. Automated historical elimination mechanism In addition to scaling backwards, this component also undertakes the function of automatically reclaiming storage space, realizing full lifecycle management of data through the TTL attribute.

[0110] The first step is expiration boundary identification. Each time a maintenance task is activated, the component calculates the current system's expiration threshold in real time.

[0111] Coordination node side: ; Data node side: ; in This sets the deletion delay on the data node side. When the table has a period set, the default is 1 period; otherwise, it is 1 hour. This ensures that the eviction time on the data node side is more past than that on the coordinating node side, so that partitions awaiting physical eviction are deleted on the coordinating node first, avoiding errors caused by routing to partitions that have already been deleted by the data node.

[0112] The second step is candidate partition scanning. The component scans local metadata to identify all historical partitions whose boundary values ​​are earlier than the expiration threshold.

[0113] The third step is the safe deletion strategy. To prevent accidental deletion of the entire table due to configuration errors, the component introduces an empty table protection mechanism: even if some partitions meet the expiration conditions, the system will force the retention of at least one partition, namely the partition with the latest expiration time, to ensure the logical integrity of the table structure.

[0114] The fourth step is seamless physical deletion. Identified expired partitions will be physically deleted using the DROP PARTITION action.

[0115] Step 5: Local transaction processing. The deletion operation is completed in a local independent transaction, quickly releasing disk space on the underlying storage node (DN).

[0116] Step 6: Refresh the cache. When the local partition deletion is complete, the Relcache will be refreshed. The optimizer will then be able to detect the deletion of the old partition through the rebuilt Relcache during the next query.

[0117] 3. Concurrency safety mechanisms The following two mechanisms work together to ensure the safety of concurrent operations.

[0118] Time-domain physical isolation: Pre-built partitions are future partitions with boundaries greater than the current time, while Drop evicts historically expired partitions with boundaries less than the current time minus the TTL. The sets of partitions operated on by both methods are completely disjoint, therefore physically, it is impossible to simultaneously create and delete the same partition.

[0119] Multi-Version Concurrency Control (MVCC) isolation: Even if a new partition creation operation is delayed for a long time due to extremely special reasons, and is still not completed by the time it should be evicted, according to MVCC rules, the scan step will not find the partition that has not yet been committed, and it will not be deleted. This is because the metadata insertion operation of the new partition is not visible to other transactions before the transaction is committed.

[0120] Based on the same inventive concept, embodiments of the present invention also provide a partition table management device for a distributed database, applied to a distributed cluster architecture including a global transaction manager, multiple coordinating nodes, and multiple data nodes. The device includes: an attribute parsing module, used to receive data definition language statements through the coordinating nodes, parse and obtain partition maintenance cycle and data lifecycle attributes, and perform multi-dimensional legality verification; a boundary catching-up module, used to respond to table creation operations, extract the user-declared partition start boundary and the current system time within the table creation transaction, calculate the required continuous partition boundaries through a one-time boundary calculation, and encapsulate the catching-up and completion operation with the main table creation statement in the same distributed global transaction; a task scheduling module, used to register and activate partition maintenance jobs on each node in the distributed cluster, whereby the job, when executed locally, only applies lightweight table locks (i.e., level 4 locks ShareUpdateExclusiveLock) that do not conflict with business read / write operations, and executes a differentiated pre-creation step size mechanism, ensuring that the number of partitions M pre-created by the data nodes is greater than the number of partitions N pre-created by the coordinating nodes; and a lifecycle maintenance module, used to calculate the expiration threshold time based on the data lifecycle attributes, identify and delete historical partitions. For details on the specific implementation methods and beneficial effects of the operations performed by each module in this device embodiment, please refer to the detailed description in the foregoing method embodiment; further details will not be repeated here.

[0121] Based on the same inventive concept, embodiments of the present invention also provide an electronic device, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement any of the above-mentioned distributed database partition table management methods.

[0122] Based on the same inventive concept, embodiments of the present invention also provide a computer-readable storage medium storing a computer program thereon, which, when executed by a processor, implements any of the above-described methods for managing partitioned tables in a distributed database.

[0123] Through the specific embodiments described above, the present invention has the following significant advantages over the prior art: First, this invention completely eliminates global lock blocking through localized scheduling and a low-level locking mechanism, significantly improving the system's high-concurrency performance and availability. In the traditional process of creating dynamic partitions in distributed databases, level 8 global exclusive locks are often required, forcibly blocking read and write operations across the entire cluster. This invention innovatively designs an architecture where each node independently maintains a background scheduling task, restricting the operation of adding or deleting partitions to local execution on the node, requiring only a level 4 lock, ShareUpdateExclusiveLock, to be applied to the target partition table. Based on the principle of kernel lock conflict matrix, level 4 locks do not conflict with level 1 locks used for read operations or level 3 locks used for write operations. This architectural design fundamentally decouples data writing from structural changes, allowing read and write operations on the business side to proceed normally while partitions are automatically maintained in the background. This effectively avoids system throughput degradation and distributed deadlock problems caused by strong locking in high-concurrency scenarios, greatly improving the overall concurrent processing capability of the database.

[0124] Secondly, this invention achieves plug-and-play table creation, eliminates the visibility trap caused by asynchronous completion, and significantly reduces system initialization time. Addressing the historical partition gap problem encountered during the table creation initialization phase, this invention designs a time complexity of... The alignment truncation algorithm calculates the termination time of the alignment. This method utilizes the kernel's low-level batch partitioning interface to generate a continuous sequence of partitions at once, then identifies and discards the last partition whose span is less than the period. This approach not only ensures that the boundaries of all retained partitions are completely uniform but also completely skips the redundant overhead of the SQL parsing engine. Tests show that this solution can complete the processing of tens of thousands of partitions within seconds, while traditional solutions can take tens of minutes. Furthermore, this invention encapsulates the catch-up and completion operation with the main table creation statement within the same distributed global transaction through a strong binding mechanism. It uses a two-phase commit protocol to ensure that the metadata of all data nodes is synchronized and ready before returning success to the client. This mechanism strictly guarantees the consistency of metadata visibility and business availability, avoiding data write failures caused by users not being able to find the target partition during the initial stage of table creation.

[0125] Third, this invention innovatively designs a differentiated pre-built step size mechanism, which effectively ensures the consistency of distributed queries and provides lightweight fault tolerance and self-healing capabilities. Since the scheduling triggering time of each node in a distributed cluster may have slight clock skew or execution delay, this invention addresses this by setting the number of pre-created partitions for each data node. Greater than the number of partitions pre-created by the coordinating node A step-size redundancy zone was constructed. Since the data nodes always have more partition reserves than the coordinating node, it ensures that as long as the execution plan can be successfully routed at the coordinating node, the target partition will definitely exist after being sent to the data nodes, completely eliminating the risk of query errors caused by distributed synchronization gaps. Simultaneously, this invention integrates an exponential backoff retry mechanism and an attribute reset repair mechanism. In the event of task failure due to extreme anomalies, the database administrator does not need to manually intervene in the complex underlying scheduling record tables; they can simply use a standard attribute reset command to atomically clean up invalid states and restart the task, significantly reducing the operational costs of the distributed database during the fault recovery phase.

[0126] Fourth, this invention achieves automated management of the entire data lifecycle and ensures the safety of concurrent operations through multiple isolation mechanisms. This invention implements automated physical eviction of expired partitions through data lifecycle attributes and designs a data node-side deletion delay mechanism, making the eviction time on the data node side more past than that on the coordinating node side. This ensures that partitions awaiting physical eviction are deleted first on the coordinating node side, effectively avoiding errors caused by routing to partitions already deleted by data nodes. Furthermore, this invention guarantees concurrency safety through a dual mechanism of time-domain physical isolation and multi-version concurrency control isolation. Pre-built future partitions and historically expired partitions to be evicted are physically completely separate, and according to multi-version concurrency control rules, newly created partitions that have not yet been committed will not be scanned and deleted. This design ensures that partition creation and eviction operations do not interfere with each other during concurrent execution, achieving automated and safe reclamation of storage space.

[0127] In summary, the distributed database partition table management method provided by this invention, through multi-dimensional technological innovation, comprehensively solves the technical bottlenecks of existing technologies in terms of performance, consistency, initialization efficiency, and operation and maintenance costs, and has extremely high industrial application value.

[0128] The above are merely preferred embodiments of the present invention and are not intended to limit the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A method for managing partitioned tables in a distributed database, applied to a distributed cluster architecture comprising a global transaction manager, multiple coordinating nodes, and multiple data nodes, characterized in that... Includes the following steps: The data definition language statements are received by the coordination node, parsed and obtained as partition maintenance cycle and data lifecycle attributes, and the attributes are validated in multiple dimensions. In response to the table creation operation, within the table creation transaction, the user-declared partition start boundary is extracted and compared with the current system time. If there is a time difference, all consecutive partition boundaries that need to be filled are calculated through a one-time boundary calculation, and the generated catch-up filling operation is encapsulated in the same distributed global transaction as the main table creation statement. Each node in the distributed cluster registers and activates its corresponding partition maintenance job. The partition maintenance job runs in the background on each node. When adding or deleting partitions on the local node, only a lightweight table lock that does not conflict with the business read and write operations is applied to the target partition table, without triggering a distributed global transaction lock. The partition maintenance job executes a differentiated pre-built step size mechanism based on the node role. When executed on the coordinating node, it maintains the pre-creation of partitions with N partition maintenance cycle intervals. When executed on the data node, it maintains the pre-creation of partitions with M partition maintenance cycle intervals, where M is greater than N. Calculate the expiration threshold based on data lifecycle attributes, identify and delete historical partitions whose boundary values ​​are earlier than the expiration threshold.

2. The method for managing partitioned tables in a distributed database according to claim 1, characterized in that, Perform multi-dimensional validity checks on attributes, including: The target table for verification must be a range-partitioned table; The data type of the verification partition key must be strictly limited to timestamp type or timestamp type with time zone; The time interval parameters for partition maintenance cycle and data lifecycle are subject to mandatory range specification, requiring their values ​​to be between 1 hour and 1 year. Verify that existing partition definitions do not contain partitions with the maximum value.

3. The method for managing partitioned tables in a distributed database according to claim 1, characterized in that, The required continuous partition boundaries are calculated in a single step, specifically including: Construct a range partition start and end point definition state structure, where the start value is the user-declared initial partition start boundary and the step value is the partition maintenance cycle; The termination time for alignment is calculated using the following formula: ;in, This indicates the internally set alignment end time. Indicates the current system time. Indicates the partition maintenance cycle; Using the kernel's batch partition creation interface, a list of consecutive partition sequence definitions is generated in one go, with the start and end times as the range and the step size as the interval. Remove the last partition definition from the list of consecutive partition sequences to obtain a padded partition list with perfectly uniform boundaries, and then perform the partition creation operation based on the padded partition list.

4. The method for managing partitioned tables in a distributed database according to claim 1, characterized in that, The generated catch-up and completion operations are encapsulated within the same distributed global transaction as the primary table creation statement, specifically including: After the coordinating node generates the execution plan, it distributes the partition creation operation to all data nodes; Data nodes perform partition creation and record Redo logs locally; The coordinating node sends a prepare command to all data nodes. After receiving a successful prepare response from all data nodes, it sends a commit command to all data nodes. After receiving a successful commit response from all data nodes, the table creation command returns a successful response to the client.

5. The method for managing partitioned tables in a distributed database according to claim 1, characterized in that, The partition maintenance operation implements a differentiated pre-build step size mechanism based on the node role, specifically including: Scan the local system tables to obtain the timestamp of the largest existing partition boundary; Calculate the target alignment time starting from the timestamp of the largest partition boundary; Coordinating node calculation to ;in, This indicates the target alignment time of the coordinating nodes. Indicates the number of partitions pre-created by the coordinating node; Data node calculation to ;in, Indicates the target alignment time of the data node. Indicates the number of partitions pre-created for the data node; Starting from the timestamp of the largest partition boundary, the partition addition operation is continuously executed in steps of the partition maintenance cycle until the target alignment time is covered.

6. The method for managing partitioned tables in a distributed database according to claim 1, characterized in that, The expiration threshold is calculated based on data lifecycle attributes, specifically including: On the coordinating node side, the expiration threshold time is calculated as follows: ;in, This indicates the expiration threshold time on the coordinating node side. Indicates the data lifecycle; On the data node side, the expiration threshold is calculated at the following time: ;in, This indicates the expiration threshold time on the data node side. Deletion delay on the data node side; The data node's elimination time is more past than the coordinating node's, which means that partitions awaiting physical elimination are deleted first at the coordinating node.

7. The method for managing partitioned tables in a distributed database according to claim 1, characterized in that, Distributed database partition table management methods also include fault tolerance retry and attribute reset mechanisms: If the new partitioning task fails, an exponential backoff retry mechanism with a fixed upper limit will be automatically triggered. The retry interval is calculated using the following formula: ;in, Indicates the waiting time. Indicates the base waiting time. Indicates the current number of retries; If the retries reach the limit and still fail, mark the task as failed and force it to be suspended. Receive attribute reset operations, atomically clean up old invalid task states, reset the retry counter, and restart the scheduled task based on the latest metadata state.

8. A partition table management device for a distributed database, applied in a distributed cluster architecture including a global transaction manager, multiple coordinating nodes, and multiple data nodes, for executing the partition table management method for a distributed database as described in any one of claims 1-7, characterized in that, The partition table management device for a distributed database includes: The attribute parsing module is used to receive data definition language statements through the coordinating node, parse and obtain partition maintenance cycle and data lifecycle attributes, and perform multi-dimensional legality verification. The boundary catch-up module is used to respond to table creation operations. Within the table creation transaction, it extracts the user-declared partition start boundary and the current system time, calculates the continuous partition boundaries that need to be filled in through a one-time boundary calculation, and encapsulates the catch-up and filling operation and the main table creation statement in the same distributed global transaction. The task scheduling module is used to register and activate partition maintenance jobs on each node in the distributed cluster. When the job is executed locally, only a lightweight table lock that does not conflict with the business read and write operations is applied, and a differentiated pre-built step size mechanism is executed so that the number of partitions M pre-created by the data node is greater than the number of partitions N pre-created by the coordinating node. The lifecycle maintenance module is used to calculate the expiration threshold based on data lifecycle attributes and to identify and delete historical partitions.

9. An electronic device comprising a memory and a processor, the memory storing a computer program, characterized in that, When the processor executes a computer program, it implements the partition table management method of the distributed database as described in any one of claims 1 to 7.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When a computer program is executed by a processor, it implements the partition table management method of a distributed database as described in any one of claims 1 to 7.