Skip to content

Database Sequences

Xe Plugin includes a sequence generator for creating database tables that generate sequential, gapless auto-increment numbers. This is useful for systems requiring predictable sequential identifiers (such as invoice numbers, order reference IDs, or booking IDs).


Generating a Sequence

Run the make:sequence command:

php xe make:sequence Invoice

This creates src/Database/Sequences/Invoice.php.


Class Anatomy

The generated class uses WordPress's $wpdb to manage an atomic database table:

namespace Xe_Plugin;

class Invoice {

  protected static string $table = '_xe_plugin_invoice';

  // Get full prefixed table name: wp__xe_plugin_invoice
  protected static function table(): string {
    global $wpdb;
    return $wpdb->prefix . self::$table;
  }

  // Create table on activation using dbDelta
  public static function create_table(): void {
    global $wpdb;
    $table_name      = self::table();
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE {$table_name} (
      id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      name VARCHAR(50) NOT NULL,
      number BIGINT(20) UNSIGNED NOT NULL DEFAULT 1,
      PRIMARY KEY (id),
      UNIQUE KEY name (name)
    ) {$charset_collate};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
  }

  // Atomically increment and return the next sequence number
  public static function next( string $name ): int;

  // Get current sequence number without incrementing
  public static function current( string $name ): int;

  // Add a new named sequence
  public static function add( string $name ): bool;

  // Check if a sequence exists
  public static function exists( string $name ): bool;

  // Reset a sequence to a starting value
  public static function reset( string $name, int $number = 1 ): bool;

}

Step-by-Step Usage

1. Initialize the Table in Setup

In src/Setup.php, call create_table() inside the activation() method:

public static function activation() {
  \Xe_Plugin\Invoice::create_table();
}

2. Generate Next Sequential Number

use Xe_Plugin\Invoice;

// Ensure sequence exists
if ( ! Invoice::exists( 'sales-2026' ) ) {
  Invoice::add( 'sales-2026' );
}

// Atomically increment and get next number
$invoice_no = Invoice::next( 'sales-2026' ); // 1
$next_no    = Invoice::next( 'sales-2026' ); // 2

// Format invoice reference: INV-2026-000001
$formatted_ref = sprintf( 'INV-2026-%06d', $invoice_no );

3. Resetting or Peeking Current Number

// Check current number without incrementing
$current = Invoice::current( 'sales-2026' );

// Reset back to 1 (or any custom start)
Invoice::reset( 'sales-2026', 1 );