Automattic\WooCommerce\Internal\DataStores\Orders

OrdersTableStatusUnionQuery::build_union_sqlprivateWC 1.0

Assembles the UNION ALL rewrite from the validated pieces. Each branch is wrapped in a derived table (instead of using parenthesized UNION members) so that the per-branch ORDER BY + LIMIT is honored across MySQL, MariaDB and SQLite.

Method of the class: OrdersTableStatusUnionQuery{}

No Hooks.

Returns

String. The rewritten SQL query.

Usage

// private - for code of main (parent) class only
$result = $this->build_union_sql( $types, $statuses, $direction, $branch_rows, $limits ): string;
$types(string[]) (required)
Queried order types.
$statuses(string[]) (required)
Queried order statuses.
$direction(string) (required)
Sort direction ('ASC' or 'DESC').
$branch_rows(int) (required)
Number of rows each branch must fetch (offset + row count).
$limits(string) (required)
The outer LIMIT clause, including the keyword.

OrdersTableStatusUnionQuery::build_union_sql() code WC 11.0.0

private function build_union_sql( array $types, array $statuses, string $direction, int $branch_rows, string $limits ): string {
	global $wpdb;

	$branches = array();

	foreach ( $types as $type ) {
		foreach ( $statuses as $status ) {
			$branch = $wpdb->prepare(
				"SELECT id, date_created_gmt FROM {$this->orders_table} WHERE type = %s AND status = %s ORDER BY date_created_gmt {$direction} LIMIT {$branch_rows}", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				$type,
				$status
			);

			$branches[] = 'SELECT id, date_created_gmt FROM ( ' . $branch . ' ) union' . count( $branches );
		}
	}

	return 'SELECT id FROM ( ' . implode( ' UNION ALL ', $branches ) . " ) candidates ORDER BY date_created_gmt {$direction} {$limits}";
}