perf: 优化淘系支付宝期初余额查询

This commit is contained in:
qiuxiang 2026-11-19 10:44:27 +08:00
parent 691a80e0c3
commit b0074bbfa7

View File

@ -0,0 +1,64 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const TABLE = 'taobao_alipay_bill_rows';
private const INDEX = 'taobao_alipay_opening_balance_idx';
public function up(): void
{
if (config('system_database.mode', 'bootstrap') === 'bootstrap') return;
$schema = Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
if (! $schema->hasTable(self::TABLE) || $schema->hasIndex(self::TABLE, self::INDEX)) return;
$connection = $schema->getConnection();
if (in_array($connection->getDriverName(), ['mysql', 'mariadb'], true)) {
// The opening balance reads the last row for every Alipay account.
// Keep store flags and amounts in the index so the window query does
// not fetch millions of wide source rows.
$wait = (int) $connection->selectOne('SELECT @@SESSION.lock_wait_timeout AS seconds')->seconds;
$connection->statement('SET SESSION lock_wait_timeout=5');
try {
$table = $connection->getQueryGrammar()->wrapTable(self::TABLE);
$index = $connection->getQueryGrammar()->wrap(self::INDEX);
$connection->statement(
'ALTER TABLE ' . $table . ' ADD INDEX ' . $index
. ' (alipay_account, occurred_at, source_row_number, store_name,'
. ' balance_amount, income_amount, expense_amount),'
. ' ALGORITHM=INPLACE, LOCK=NONE',
);
} finally {
$connection->statement('SET SESSION lock_wait_timeout=' . $wait);
}
} else {
$schema->table(self::TABLE, static fn (Blueprint $table) => $table->index(
[
'alipay_account',
'occurred_at',
'source_row_number',
'store_name',
'balance_amount',
'income_amount',
'expense_amount',
],
self::INDEX,
));
}
}
public function down(): void
{
if (config('system_database.mode', 'bootstrap') === 'bootstrap') return;
$schema = Schema::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
if ($schema->hasTable(self::TABLE) && $schema->hasIndex(self::TABLE, self::INDEX)) {
$schema->table(self::TABLE, static fn (Blueprint $table) => $table->dropIndex(self::INDEX));
}
}
};